Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a vim function to insert a block of static text

Tags:

function

vim

I'd like to be able to do something like this in vim (you can assume v7+ if it helps).

Type in a command like this (or something close)

:inshtml 

and have vim dump the following into the current file at the current cursor location

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml">     <head>         <title></title>     </head>     <body>     </body> </html> 

Can I write a vim function do this is? Is there a better way?

like image 341
Mark Biek Avatar asked Mar 27 '09 16:03

Mark Biek


2 Answers

I do that by keeping under my vim folder a set of files which then I insert using the r command (which inserts the contents of a file, at the current location if no line number is passed) from some function:

function! Class()     " ~/vim/cpp/new-class.txt is the path to the template file     r~/vim/cpp/new-class.txt endfunction 

This is very practical - in my opinion - when you want to insert multi-line text. Then you can, for example, map a keyboard shortcut to call your function:

nmap ^N :call Class()<CR> 
like image 151
Paolo Tedesco Avatar answered Sep 27 '22 22:09

Paolo Tedesco


Late to the party, just for future reference, but another way of doing it is to create a command, e.g.

:command Inshtml :normal i your text here^V<ESC> 

The you can call it as

:Inshtml 

Explanation: the command runs in command mode, and you switch to normal mode with :normal, then to insert mode with 'i', what follows the 'i' is your text and you finish with escape, which is entered as character by entering ^V

It is also possible to add arguments, e.g.

:command -nargs=1 Inshtml :normal i You entered <args>^V<ESC> 

where <args> (entered literally as is) will be replaced with the actual arguments, and you call it with

:Inshtml blah 
like image 44
Dan Andreatta Avatar answered Sep 27 '22 22:09

Dan Andreatta