Search code examples
sublimetext3syntax-highlighting

How to tell sublime-text syntax highlighter to capture both single quotes and double quotes?


In sublime-text 3, from menu of Tools > Developer > New Syntax ..., I have found this default code

%YAML 1.2
---
# See http://www.sublimetext.com/docs/3/syntax.html
file_extensions:
  - ec
scope: source.example-c
contexts:
  main:
    # Strings begin and end with quotes, and use backslashes as an escape
    # character
    - match: '"'
      scope: punctuation.definition.string.begin.example-c
      push: double_quoted_string

    # Comments begin with a '//' and finish at the end of the line
    - match: '//'
      scope: punctuation.definition.comment.example-c
      push: line_comment

    # Keywords are if, else for and while.
    # Note that blackslashes don't need to be escaped within single quoted
    # strings in YAML. When using single quoted strings, only single quotes
    # need to be escaped: this is done by using two single quotes next to each
    # other.
    - match: '\b(if|else|for|while)\b'
      scope: keyword.control.example-c

    # Numbers
    - match: '\b(-)?[0-9.]+\b'
      scope: constant.numeric.example-c

  double_quoted_string:
    - meta_scope: string.quoted.double.example-c
    - match: '\\.'
      scope: constant.character.escape.example-c
    - match: '"'
      scope: punctuation.definition.string.end.example-c
      pop: true

  line_comment:
    - meta_scope: comment.line.example-c
    - match: $
      pop: true

Through what it captures by default is double quoting via

    - match: '"'
      scope: punctuation.definition.string.begin.example-c
      push: double_quoted_string

and

  double_quoted_string:
    - meta_scope: string.quoted.double.example-c
    - match: '\\.'
      scope: constant.character.escape.example-c
    - match: '"'
      scope: punctuation.definition.string.end.example-c
      pop: true

If I add this within my code:

    - match: ''''
      scope: punctuation.definition.string.begin.example-c
      push: single_quoted_string

and

  single_quoted_string:
    - meta_scope: string.quoted.single.example-c
    - match: '\\.'
      scope: constant.character.escape.example-c
    - match: '"'
      scope: punctuation.definition.string.end.example-c
      pop: true

The result does not go well when a double quote is inside a single quote:

Syntax Result

How can I fix that?


Solution

  • Change your rules to this:

    - match: "'"
      scope: punctuation.definition.string.begin.example-c
      push: single_quoted_string
    

    and this

      single_quoted_string:
        - meta_scope: string.quoted.single.example-c
        - match: '\\.'
          scope: constant.character.escape.example-c
        - match: "'"
          scope: punctuation.definition.string.end.example-c
          pop: true
    

    YAML can handle both single and double quotes, so if you need to use one or the other in a regex, use the other one to surround the regex.