3

Currently I have JavaScript (.js) files that contain multiline strings. Vim's syntax highlighting does not seem to support these, as seen in the image below: Improper multiline syntax highlighting

Anything below the first line is not properly recognized as a string, and everything after the end quote is incorrectly considered a string. Any way to fix this?

2
  • 1
    I know this doesn't answer your question, but your choice of string formatting is usually discouraged in javascript. See google-styleguide.googlecode.com/svn/trunk/… for reference and a way to avoid this problem.
    – SBI
    Feb 19, 2015 at 12:28
  • Yeah my main reason for this format was that I'm not very good at SQL, so when I run into issues I copy and paste the SQL into a MySQL client to test things, and then when I've figured it out I put it back in my project. I found this syntax the easiest to convert to a single line of SQL.
    – Greg
    Feb 19, 2015 at 16:53

1 Answer 1

2

The /usr/share/vim/vim74/syntax/javascript.vim uses this to define what a "string region" is in Javascript:

syn region javaScriptStringD start=+"+ skip=+\\\\\|\\"+ end=+"\|$+ contains=javaScriptSpecial,@htmlPreproc

The end option matches either the " character, or the end of the line $, which is why the syntax highlighting stops after the first line.

We can override this by making a ~/.vim/after/syntax/javascript.vim file with:

syn region javaScriptStringD start=+"+ skip=+\\\\\|\\"+ end=+"+ contains=javaScriptSpecial,@htmlPreproc
syn region javaScriptStringS start=+'+ skip=+\\\\\|\\'+ end=+'+ contains=javaScriptSpecial,@htmlPreproc

One line for "strings", and another for 'strings'. We just removed the |$ part (| for "or", $ for end of line).

Note: I think it would be better to only highlight the string if the previous line escapes the \n (ie. ends with \). I happen to know that the C syntax does this, but I can't seem to steal borrow that and get it working in Javascript :-/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.