Before you start writing plug-ins, you need to verify that Vim supports Ruby by using the following command to identify:
$ VIM--version | grep +ruby
If the output is empty, your current vim does not support Ruby, you need to recompile, and enable support for Ruby.
By the way, my current environment is:
Vim 7.4
Ruby 2.1.0
There's no problem with environmental inspection. So start. Create a Demo.vim file in the ~/.vim/plugin directory.
At the beginning, write the following code:
If!has (' Ruby ')
echo "error:required vim compiled with +ruby"
finish
endif
This code is written in Viml, and it checks to see if Vim supports Ruby.
Then determine if the plug-in has been loaded to avoid repeated loading:
if exists (' G:loaded_ruby_demo_plugin ')
finish
endif let
g:loaded_ruby_demo_plugin = 1
All the checks are no problem, then start the body of the plugin. Define a function first.
function! DEMOFUN1 ()
ruby<<eof
buf = vim::buffer.current
puts "current Buffer name: #{buf.name} number: #{ Buf.number} length: #{buf.length} "
EOF
endfunction
function and endfunction are used in vim to define functions, and in part between "ruby<<eof" and "EOF" is the Ruby code. This example is the name, number, and total number of rows that output the current buffer. Execute command: Call DEMOFUN1 (), you should be able to see the output results.
Then give an example of the function of the parameter processing.
function! DemoFun2 (arg1)
ruby<< eof
puts "you input: #{vim.evaluate (' A:arg1 ')}"
EOF
endfunction
This defines a function that receives a parameter and then outputs it. Use Vim.evaluate to convert VIM's variables into ruby variables.
To make it easier for us to define two more commands to simplify the invocation of these two functions.
command! -nargs=0 DemoFun1 Call DEMOFUN1 ()
command!-nargs=1-rang DemoFun2 call DemoFun2 (<f-args>)
To get the complete code you can access: https://gist.github.com/wusuopu/c1182efefa85d4f6839b
Next, let's talk about the use of ruby in Vim.
VIM provides Ruby with a vim module that allows you to access the Vim interface in Ruby. Two global variables are also available: $curwin, $curbuf, which represent the current Window object and the current buffer object, respectively.
The VIM module has buffer and window two objects, which are used to manipulate buffers and windows respectively. The Vim module also provides message, set_option, command, and evaluate four functions.
To see more helpful information, you can execute the following commands in VIM:
Well, write so much first, the rest of you to try it.