Reputation: 3127
I am trying to write a function to cause vim to open the relative header/source file in a split window.
What I have works (see below) apart from the file it opens in the split doesn't have syntax highlighting.
function! SplitOther()
let s:fname = expand("%:p:r")
if expand("%:e") == "h"
set splitright
exe "vsplit" fnameescape(s:fname . ".cpp")
elseif expand("%:e") == "cpp"
set nosplitright
exe "vsplit" fnameescape(s:fname . ".h")
endif
endfunction
autocmd! BufReadPost *.h,*.cpp call SplitOther()
I have tried appending syntax on
to the command (just before the endfunction
) but that doesn't seem to want to work.
I think it happens when the file isn't in a buffer before splitting? I'm not 100% sure though.
I change my function to have allow the definition of file pairs, I'm not sure if it will change my question at all so here's the extended version:
function! SplitOther()
let s:pairs = [ [ "h", "cpp" ], [ "vert", "frag" ] ]
let s:fname = expand("%:p:r")
for [s:left, s:right] in s:pairs
if expand("%:e") == s:left
set splitright
exe "vsplit" fnameescape(s:fname . "." . s:right)
elseif expand("%:e") == s:right
set nosplitright
exe "vsplit" fnameescape(s:fname . "." . s:left)
endif
endfor
endfunction
autocmd! BufReadPost * call SplitOther()
Upvotes: 1
Views: 486
Reputation: 172520
The problem is that filetype detection is triggered by an autocmd
, but by default, autocommands do not nest (cp. :help autocmd-nested
).
Also, by using :autocmd!
with a bang, you're clearing all other such global autocmds; this might affect other customizations or plugins! You should define your own scope via :augroup
, then it's safe. Taken together:
augroup MyAltSplitPlugin
autocmd! BufReadPost * nested call SplitOther()
augroup END
Upvotes: 1
Reputation: 3127
Got it!
When the file was being loaded into the vsplit it's filetype wasn't being set.
I noted that when vsplit is called the new split grabs focus and that is the window that does not have syntax highlighting so you can simply add exe "filetype" "detect"
at the end of the function to tell vim to detect the filetype of the current window.
The result:
function! SplitOther()
let s:pairs = [ [ "h", "cpp" ], [ "vert", "frag" ] ]
let s:fname = expand("%:p:r")
for [s:left, s:right] in s:pairs
if expand("%:e") == s:left
set splitright
exe "vsplit" fnameescape(s:fname . "." . s:right)
break
elseif expand("%:e") == s:right
set nosplitright
exe "vsplit" fnameescape(s:fname . "." . s:left)
break
endif
endfor
exe "filetype" "detect"
endfunction
autocmd! BufRead * call SplitOther()
Upvotes: 2