The way to set key bindings which only work within commented lines



I want to set key bindings which only work within commented lines, but can’t find the way.

For example, now I’m working with R and when I run ‘Log Cursor Scope’ command on a commented line I get below as the scopes at the cursor.

  • source.r
  • comment.line.number-sign.r

I know that I can set key bindings for ordinal code lines with below.

"atom-text-editor[data-grammar='source r']":

Therefore I tried the config below, but it does not works.

"atom-text-editor[data-grammar='comment line number-sign r']":

Can I set keybindings which only works for the scope comment.line.number-sign.r?



That trick that you’re using is designed to target a grammar, not a particular language construct. For what you want, you’re looking more for the system that is covered in Overloading Key Bindings. You want to target atom-text-editor[data-grammar='source r'] but then check to see if the cursor is within a comment. If not, use e.abortKeyBinding().


Thank you for the suggestion.
I’m quite new to Coffee and have not yet grasped how to do it precisely, but going to find the way.


I got it. I leave a command I define and hope it will be someone’s help (or I could get better solutions).

What I wanted to do is to create a new commented line when I hit the enter key with the cursor in a commented region.
I use R and there is roxygen2 package to write a documentation for a package as commented lines in source files. It’s convenient if a commented region continues when I hit enter on writing roxygen-style comment.

The command I define is:

atom.commands.add "atom-text-editor[data-grammar='source r']",
  'custom:comment-aware-newline': (e) ->
    editor = atom.workspace.getActiveTextEditor()
    cursor = editor?.getLastCursor()
    scope_descriptor = cursor?.getScopeDescriptor()?.getScopesArray()
    if "comment.line.number-sign.r" in scope_descriptor
      editor?.insertText("# ")
    else if "comment.line.number-sign.roxygen.r" in scope_descriptor
      editor?.insertText("#' ")

Then I write in the keymap.cson (Sorry, I wrote wrong code for this and fixed after posted):

"atom-text-editor[data-grammar='source r'] ":
  "enter": "custom:comment-aware-newline"