I have a folder of third party libraries called add-libraries and the location for this specific library is /home/yapjiahong/projects/cpp/add-libraries/plog/include.

I want to write a function called Include that takes in lib as an argument. Then append that to the end of a string. Then write it out where my cursor is at this is what I currently have:

function Include(lib)
    let path = "/home/yapjiahong/projects/cpp/add-libraries/" . a:lib
    exe "insert!: . l:path

This gives an error and I'm not too sure how to fix it. This alternatives works, but I wanna use a function instead. The alternative:

nnoremap <leader>ff i/home/yapjiahong/projects/cpp/add-libraries/<Esc><Esc>
  • Are you looking for the :map command?
    – Gerard H. Pille
    Dec 2 '20 at 2:05
  • I know :map just lets me remap a command to a preferred keybinding. But I'm trying to make my own command.
    – DexYap
    Dec 2 '20 at 7:06
  • 1
    How did you map the Inc function?
    – Gerard H. Pille
    Dec 2 '20 at 15:37
  • 2
    Welcome to Vi and Vim! Can you please expand on what you're trying to accomplish? You mentioned "snippets" but didn't really explain them, are these stored as files that you want to read from the include directory? Can you give an example of file you would have there and what the end result you'd like? Thanks!
    – filbranden
    Dec 2 '20 at 19:50
  • 1
    Sorry for the late replies. @Gerard I didn't I ended up doing this instead. Because I still can't figure out how to use functions properly.
    – YJH16120
    Dec 5 '20 at 3:04

The :insert command cannot take an argument like you're trying to do, it expects user input for the lines, followed by a single line consisting of a . to finish inserting.

You probably want the append() function instead:

function Include(lib)
    let path = "/home/yapjiahong/projects/cpp/add-libraries/" . a:lib
    call append(line('.') - 1, path)

I think what you want is an abbreviation when you are in insert mode. Try adding the following to your .vim/ftplugin/cpp.vim file:

iabbr <buffer> include() /home/yapjiahong/projects/cpp/add-libraries/plog/include

Now, whenever you are in insert mode and type include() followed by a space or return, the text on the right hand side will automatically replace the text on the lefthand side.

Note: I couldn't get the abbreviation to work with a : in the front.

I hope that helps and is what you were looking for.


Try defining in your vimrc:

:command! Include call Ins()<CR>

And define your function in your vimrc(it is referenced in the comments).

Then use :Include to execute.

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.