1

I would like vim to detect and store the number of commented lines (prefixed with #) from the start of a file and then use a variable with the stored value to change a vim-setting in a file-specific manner.

Example:

If I open this file:

# Comment here
# and here
file text starts here

I want the variable to store 2, and then use that value to set which line to start highlighting at (specifically with csv_headerline= in the csv-vim package). The number of commented lines would change from file to file.

I thought there might be a way to use autocmd and set up my .vimrc to have vim look through the first few lines of the file before opening it, but I can't figure out how to do it.

joelostblom
  • 43,590
  • 17
  • 150
  • 159
  • 1
    There's probably a nicer way, but you could `/^[^#]` to go to the first line which doesn't start with a comment character, and `echo line('.')` to get the current line number, subtract one. But it's going to break if you have empty lines, comments mixed with empty lines, then code. – TessellatingHeckler Nov 19 '15 at 00:42

1 Answers1

0

Guided by @TesselatingHeckler's comment, I added the following to my .vimrc:

" Detect comments and identify the header line in csv-files                                                                                                                                                         
autocmd Filetype csv /^[^#] " Place cursor on first non-comment line                                                                                                                                                 
autocmd Filetype csv let b:csv_headerline=line('.') " Set cursor line as csv_headerline                                                                                                                              
autocmd Filetype csv CSVInit " Update vim.csv plugin to be aware of the new headerline                                                                                                                               

(When passing these commands directly to vim -c I had to write line('.')+1, not sure why).

So far it is working with both only commented lines in the beginning of the file and a mix of commented lines and empty lines (limited testing)!

joelostblom
  • 43,590
  • 17
  • 150
  • 159