1

I have created a VIM function that generates a new file based on the arguments passed to it and on some zsh variables I have setup.

Is it possible to extend this function to insert a header into this file immediately as it is created? I'm trying to insert the name of the file on line 1, a time stamp on line 2, and "Instructor: " on line 3.

fu! CreateNote(subject, title)
   exe "e! " . fnameescape($NOTES_DIR . "/MS" . g:year . "/" . a:subject
   . "/" . a:title . ".txt")
endfunction
1

Your function could become something like that:

function! CreateNote(subject, title)
    exe "e! " . fnameescape($NOTES_DIR . "/MS" . g:year . "/" . a:subject . "/" . a:title . ".txt")

   let l:filename=bufname("%")
   let l:timestap=strftime("%c")
   let l:text="Instructor: "

   put! =l:filename
   put! =l:timestap
   put! =l:text

endfunction

The fist line is yours. It then creates 3 variables:

  • The first one use bufname("%") to get the name of the current buffer (:h bufname()).
  • The second one use the function strftime to get the current time. Beware it is a direct call to the C function so it might not be portable, see the doc for more details :h strftime() (You can of course change the format of the timestamp cf. doc)
  • The 3rd one simply contains some text.

Then the 3 last lines uses the function put (:h put):

  • The ! is used to insert before the current line (otherwise as you start on the first line and put insert after the current line, you'd get an empty first line).
  • The = is used to call the expression register allowing to get the content of the variables.

Bonus You can make the function sexier by using a list and iterating through it:

function! CreateNote(subject, title)
    exe "e! " . fnameescape($NOTES_DIR . "/MS" . g:year . "/" . a:subject . "/" . a:title . ".txt")

    let l:header=[ bufname("%"), strftime("%c"), "Instructor: " ]

    for l:line in l:header
        put! =l:line
    endfor
endfunction
  • Also you might be interested in the dedicated Vim site for your future questions about Vim :-) – statox Sep 11 '15 at 4:55

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.