2

I wrote a function, the function is used to add comments to some lines, the content is as follows:

func Add(x)
  call setline(a:x+1, "\  //**************************************************************")
  call setline(a:x+2, "\  // **** Note ****")
  call setline(a:x+3, "\  //**************************************************************")
endfunc

When I use the Add(100) function in vi, I want the content of the 100th line to remain unchanged, and 3 additional lines are used to add text.

4

Use append() function instead as described in :h setline() help section.

It accepts the line number and and either a text line or a list of text lines that would be inserted/appended after given line number.

func! AddCommentHeader(lnum) abort
    let comment_header = 
                \[
                \'//******************************************************',
                \'//******* Note *****************************************',
                \'//******************************************************'
                \]
    let lnum = a:lnum < 1 ? line('.') : a:lnum

    call append(lnum, comment_header)
endfunc

nnoremap gci :<C-U>call AddCommentHeader(v:count)<CR>

In the example above there is a function that accepts a line number to insert a comment header after. If the line number is 0 or basically less then 1 it would insert comment header right after the current line:

let lnum = a:lnum < 1 ? line('.') : a:lnum

This is ternary operator condition ? return if true : return if false.

The mapping after function maps gci to call a function. There are 2 interesting things there <C-U> and v:count:

  • we would like to provide a count you prepend your mapping with to a function, like if I want to add comment header after line 100 I would do 100gci -- this is what built-in v:count variable for.
  • we don't want default range to be applied to our function which we call from within commandline mode :call ... if we provide a count for it. Try for example to type 100: and see your command line is prefilled with :.,.+99 <--- this thing we delete with <C-U> in the mapping:
    nnoremap gci :<C-U>call AddCommentHeader(v:count)<CR>

PS

Don't forget to use K mapping to call builtin help on a function under cursor. Also :h function-list might be useful.

1
  • Your answer is very helpful, thank you very much. – Self-Motivated Wu Mar 20 at 9:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.