0

I feel like what I am trying to do couldn't be easier. I have this file after/syntax/custom.vim. It outlines some very simple syntax highlighting rules I want applied to all file types. The highlighting rules work. Hardcoding f_type to python or something and forcing the filetype will work great! I am attempting to do the following in my .vimrc:

let f_type = &syntax
execute printf("autocmd BufNewFile,BufRead * set syntax=%s.custom", f_type)

I also tried doing &filetype but this and &syntax always return an empty string. Any help at all would be lovely.

I followed this Vimscript: how to get current filetype as a variable

some reason this is not working...

Update: I figured out a solution that works but it is... silly.

command APPLYCUSTOM execute printf("set syntax=%s.custom", &syntax)
autocmd VimEnter * APPLYCUSTOM

This seems to work but if I consolidate this to one line it will throw an error (but still work) same thing when trying on the Syntax event.

John
  • 1
  • 2
  • My question is what you want to accomplish. Because if you want run script globally then why not insert your code into `.vimrc`? – Hauleth Sep 06 '18 at 15:02

1 Answers1

0

No, your solution isn't silly, it has to do with the timing of the execution. The first one assigns to f_type the value of 'syntax' as it is during initialization. When ~/.vimrc is sourced, no buffer has yet been loaded, so there's no filetype nor syntax!

The second one moves the evaluation of &syntax to the runtime of the custom APPLYCUSTOM command, and that runs on VimEnter, which is far later (but still will only apply to the first opened file!)

To avoid the need of the custom command, you need to evaluate during autocmd execution:

autocmd BufNewFile,BufRead * execute 'setlocal syntax=' . &syntax . '.custom'

This can be written in a nicer way by using :let:

autocmd BufNewFile,BufRead * let &l:syntax .= '.custom'

Alternative

However, I would instead benefit from the built-in Syntax event, and directly source the syntax script instead of augmenting the syntax via a compound name. (Plugins may be confused by that, and I also don't think it's helpful to have custom included in all syntax names (e.g. when including syntax in the statusline)):

autocmd Syntax * runtime after/syntax/custom.vim

You only need to ensure that this comes after :syntax on in your ~/.vimrc, so that it gets executed after the original syntax script.

Ingo Karkat
  • 167,457
  • 16
  • 250
  • 324