Search code examples
coffeescriptatom-editorbackslash

Why do Atom snippets need four backslashes at once in their body in order to print a single backslash


I just realized this while setting up a snippet.

'.source':
  'shrug':
    'prefix': 'shrug'
    'body': '¯\\\\_(ツ)_/¯'

In order to print the typical ¯\_(ツ)_/¯ shrug, you need 4 backslashes. Using 2 backslashes doesn't cause any errors, but the backslash won't be printed. I would understand it if why you'd need 2, but why 4?


Solution

  • The four backslashes in atom snippets is due to snippets using the generic CSON notation (Coffeescript style JSON).

    It's well described in this comment on an issue from the atom-snippets repo

    I think that four backslashes makes sense, however notationally inconvenient.

    It has to do with the levels of interpretation a snippet goes through before it ends up in your text buffer:

    1. The snippet is declared in a CSON file, the parsing of string elements in this format is "backslash sensitive" i.e. \n represents the newline character and a \ is represented as .
    2. The snippet then has to be parsed by the snippet body parser. The parser uses one \ to escape the following character, e.g. \ becomes . So the process goes as follows:

      \ --CSON--> \ --BodyParser--> \

    The reason two backslashes used to work, was because the snippet body parser never really handled escaped characters (the escape cases were handled explicitly rather than in a generic way) this was why we had bug #60.

    The process could be made more notationally friendly if the snippets were stored in a custom format. Then we would have more control over how it is parsed, such as not interpreting backslashes before they are being fed to the body parser.