How to get syntax for commented lines


#1

I’m trying to get the proper syntax to comment a selected line.

When I try to use the following code I get the wrong commentEnd

editor = atom.workspace.getActiveEditor()
scopes    = editor.getCursorScopes()
// returns ["source.coffee"]
commentStart = atom.syntax.getProperty(scopes, 'editor.commentStart')
// returns `#`
commentEnd   = atom.syntax.getProperty(scopes, 'editor.commentEnd')
// returns `*/`

I was assuming it would return undefined or null if the syntax didn’t have a commentEnd.


#2

I think this is because not all languages have a comment end, but Atom has a default of */. In the scoped-properties for a language if you only specify editor.commentStart Atom knows not to insert a comment end, but I guess getProperty doesn’t have the logic to ignore the default in the same way.


#3

I know, three years have passed, but now there is a solution: using atom.config.getAll instead of atom.config.get (which would be the equivalent of atom.syntax.getProperty).

Using atom.config.getAll(key, scopes) you get an array of ALL the matching config items, AND the corresponding scopes. So, you can cherrypick which commentStart items to keep and which commentEnd entries to ignore.

For example, for coffeescript you would get four commentStart, two for scope .source.coffee (don’t know why two…) and two for scope .source. But for commentEnd you’ll only get two, both for scope .source, meaning you can ignore them, so there’s no specific commentEnd for that language/scope, and you know you were just getting the default value.