Before writing the plug-in, you need to confirm whether Vim supports Ruby by using the following command:
$ vim --version | grep +ruby
If the output is empty, it indicates that your current vim does not support Ruby. You need to recompile it and enable Ruby support.
By the way, my current environment is:
Vim 1, 7.4
Ruby 2.1.0
Check the environment. In ~ Create a demo. vim file under the/. vim/plugin directory.
Write the following code at the beginning:
if !has('ruby') echo "Error: Required vim compiled with +ruby" finishendif
This code is written in VimL and will check whether Vim supports Ruby.
Next, determine whether the plug-in has been loaded to avoid repeated loading:
if exists('g:loaded_ruby_demo_plugin') finishendiflet g:loaded_ruby_demo_plugin = 1
If all the checks are correct, the plug-in body is started. Define a function first.
function! DemoFun1()ruby<<EOFbuf = VIM::Buffer.currentputs "current buffer name: #{buf.name} number: #{buf.number} length: #{buf.length}"EOFendfunction
Function and endfunction are used to define functions in vim, and ruby code is included between "Ruby <EOF" and "EOF. In this example, the name, number, and total number of the current buffer are output. Run the command: call DemoFun1 (). The output result is displayed.
Next, let's take an example to illustrate how to process the function parameters.
function! DemoFun2(arg1)ruby<< EOFputs "you input: #{VIM.evaluate('a:arg1')}"EOFendfunction
A function is defined here to receive a parameter and output it. Use VIM. evaluate to convert vim variables to Ruby variables.
To facilitate the definition of two more commands, we can simplify the call to 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 briefly describe how to use Ruby in vim.
Vim provides a VIM module for Ruby to access the vim interface in Ruby. At the same time, two global variables are provided: $ curwin and $ curbuf, which represent the current window object and the Current Buffer object respectively.
The VIM module has two objects: Buffer and Window, which are used to operate the Buffer and Window respectively. The VIM module also provides four functions: message, set_option, command, and evaluate.
To view more help information, run the following command in vim:
:help ruby
Well, let's write so much, and try the rest on your own.