Newline in comments


#1

I don’t know if there’s a package for this, but I never looked and finally decided to (still not look) and fix it. This command will toggle comments on the line you create when pressing enter in a comment. 99% of the time, this is what you’d (read: I’d) want to happen anyway.

(NOTE: Does not work with Tree-sitter, because they scope all comments as block. I’m looking to see if this can be changed, either on the Atom or the Tree sitter end.

# keymap.cson
"atom-text-editor":
  "enter": "custom:newline-in-comment"
// init.js
atom.commands.add("atom-text-editor", "custom:newline-in-comment",
  (event) => {
    const editor = atom.workspace.getActiveTextEditor();

    if (!editor) {
      event.abortKeyBinding();
      return;
    }

    const position = editor.getCursorBufferPosition();
    if (!position) {
      event.abortKeyBinding();
      return;
    }

    const match = editor.lineTextForBufferRow(position.row).match(/\S/);
    if (!match) {
      event.abortKeyBinding();
      return;
    }

    const scopes = editor.scopeDescriptorForBufferPosition([position.row, match.index]).scopes;
    if (!scopes.some(s => s.startsWith("comment.line"))) {
      event.abortKeyBinding();
      return;
    }

    editor.transact(() => {
      editor.insertNewline();
      editor.toggleLineCommentsInSelection();
    });
  }
);

(it’s not very elegant; this was a very iterative process. Found a few bugs, also found some have been patched already after typing out the whole issue text)

I’m now looking at making it support multiple cursors, including a mix of on and off comments.

If you’re wondering about all the edits, it’s because I already had a comment focused package (docblockr; do recommend). My testing showed it doesn’t do what I provide above, but further testing showed it did in fact do it for coffeescript, JS, and some other languages. However, it does it in some way that’s incompatible with Tree-sitter, and not language agnostic, so I think mine wins out (in my unbiased opinion).