Escaped quotes and syntax highlighting

February 7, 2011 at 5:05 am 5 comments

| Gabriel |

Quotes usually delimit where a string with embedded spaces begin, but sometimes you want the quote to be literal and this requires escaping it. To recycle an example I’ve used before, suppose you wanted to display:

Beavis said "Fire! Fire!"

To get Stata to display this, you would escape the quotes by encompassing them in left and right apostrophes (just like calling a local) so the command would be:

disp `"Beavis said "Fire! Fire!""'

This is a trivial example, but a more realistic application is you might want to put some things that involve quotes inside a local and since the content of the local is itself delimited by quotes you’ll need to escape them.

OK, easy enough, but the problem is that most external text editors don’t appreciate this nuance of Stata syntax and end up showing the rest of the document as quoted text, effectively making the syntax highlighting useless. (Stata’s internal editor doesn’t suffer this problem, but I’m in the habit of using TextMate since prior to Stata 11 the editor didn’t have highlighting and it still doesn’t do code-folding). The solution is to let two syntax-parsing wrongs make a right by putting a single quote in a comment, which Stata will ignore but which the text editor will parse as closing a previous hanging quote. It works like this:

disp `"Beavis said "Fire! Fire!""'
* " this line exists only to let the text editor's parser know that everything is back to normal
disp "see, it works. this quoted text should show up as quoted whereas the word 'disp' appears as a command"

Entry filed under: Uncategorized. Tags: , .

Plan B Telecommunications has broadcast your message into space!


  • 1. Nick Cox  |  February 7, 2011 at 3:51 pm

    You could define local macros

    . local lq “`””
    . local rq “”‘”

    Not desperately attractive, but it might work for later use.

    In your example, I guess only the inner quoted phrase would be highlighted, but I don’t think you’d need the kludge of the extra comment.

    • 2. gabrielrossman  |  February 7, 2011 at 5:06 pm

      good idea, thanks. i did something similar to get an asterisk character in stata2pajek.ado but it hadn’t occurred to me in this context.

  • 3. Pat  |  February 8, 2011 at 7:13 pm

    Really, if you type disp `”Beavis said “Fire! Fire!””‘, Stata will remind you that standards and practices at MTV will not allow him to say that. “Fryer! Fryer!” and “Liar! Liar!” are acceptable substitutions.

  • 4. Billy  |  February 10, 2011 at 1:48 am

    Or, cut it down to one line:

    display `"Beavis said "Fire! Fire!""' //"

  • 5. jwecc  |  November 19, 2012 at 7:30 am

    Thanks, this solved a major headache for me!

The Culture Geeks

%d bloggers like this: