> Hi,
>
> I am trying to write a function to comment all lines of code in a block.
> Note the main purpose for this is to educate myself on vim scripting, given I am
> quite new with it. I am sure there are many other solutions to do it, and much
> better, but I want to do it in this way to learn.
>
> I have written this [1] so far.
>
> The idea is to search backwards the first blank line, and then forwards. Once I
> have all lines that are not blanks, I just add '#' at the beginning of each one.
> It works unless the block is at the very end of the document, for example. In that
> case the search for the 'lastline' fails. Same if the block is at the very beginning.
>
> Any tip or suggestion to fix that?
You could make the regex match at the end of the document, though I
think that will probably make your adjustment mess up and omit the last
line:
let lastline = search('^\s*$\|\%$', 'nW') - 1
Or you could just check whether the search fails or not:
let lastline = search('^\s*$', 'nW')
let lastline = lastline == -1 ? line('$') : lastline - 1
Just a couple of thoughts to get you started. I haven't tested.
:help expr1
:help line()
:help /\%$
Ben.
P.S. Since you mentioned that you're learning Vimscript, here is a
different approach, which is probably the one I would take for starters.
I would think "How would I do this if I were just doing it manually?"
The answer is that I would highlight the current paragraph by using vip
then change to visual block mode with Ctrl-v and then use I to add the
comment leader. I could instruct Vim to do this in Vimscript using a
one-liner:
exec "normal vip\<C-v>I# \<Esc>"
:help :normal
:help :exec
:help expr-string
:help <>
:help CTRL-V
:help v_b_I
> [1]
> function Comment()
> let firstline = search('^\s*$', 'bnW') + 1
> let lastline = search('^\s*$', 'nW') - 1
> for linenum in range(firstline, lastline)
> let oldline = getline(linenum)
> let newline = '#'.oldline
> call setline(linenum, newline)
> endfor
> endfunction
--
You received this message from the "vim_use" maillist.
Do not top-post! Type your reply below the text you are replying to.
For more information, visit http://www.vim.org/maillist.php
No comments:
Post a Comment