As you can see in the following screencast, when I open an HTML file with some CSS in it, there's some part of the file which does not show syntax coloring. Do you have experience of this? Is it normal when one has multiple languages in one file as in this case?
1 Answer
Sometimes, Vim can lose track of where it is highlighting from, especially in complex scenarios (nested languages, in this example).
You can tell Vim where it should sync the syntax highlighting from using the :syn sync
command. From :h :syn-sync
:
There are four ways to synchronize:
- Always parse from the start of the file.
- Based on C-style comments. Vim understands how C-comments work and can figure out if the current line starts inside or outside a comment.
- Jumping back a certain number of lines and start parsing there.
- Searching backwards in the text for a pattern to sync on.
Since we don't know how long the <style>
block will be, and we're not using C-style comments, that leaves us with two solutions (1 and 4).
Solution 1 is the easier of the two, requiring a single line in ~/.vim/after/syntax/html.vim
:
syntax sync fromstart
This will tell Vim to always sync from the very start of the file. This can be slow for long files. However, Vim will cache previously parsed text, so that it only has to parse the file again when and where it needs to.
-
2Clean and effective. And it is not specific to CSS, so it should also fix JavaScript code, if there's some in the HTML file. Thank you very much!– EnlicoSep 25, 2020 at 17:03
-
This answer turned out to be useful even when I've bumped into a wrong syntax coloring in a "pure" CSS file.– EnlicoMay 8, 2021 at 15:15
:syntax sync fromstart
fix this when it occurs? Sometimes Vim loses track of where we are highlighting syntax from and doesn't know how to highlight properly, especially in more complex scenarios like this (nested languages).:h :syn-sync
.~/.vim/after/syntax/html.vim
with that line in it. (I'll leave it for @JakeGrossman to write the answer. Jake, feel free to incorporate this part.)