DEV Community

John Pham
John Pham

Posted on • Edited on • Originally published at pham.codes

Toggling Comments for Custom CodeMirror Modes

Adding the ability to toggle line/block comments for Custom-defined CodeMirror Modes isn't well documented.

For my use case, I defined a SimpleMode. I wanted to allow users to toggle line/block comments either through clicking a GUI button or using a keyboard shortcut. Here's how I did it.


Below are the changes I made that differ from the documentation.

Your Mode File

Describe what a comment looks like.

CodeMirror.defineSimpleMode('mode-name', {
  arguments: [],
  meta: {
+     lineComment: '#'
   },
  start: [
+    {
+      regex: /#.*/,
+      token: 'comment',
+    },
  ]
}
Enter fullscreen mode Exit fullscreen mode

Import the CodeMirror Comment Addon

This file can be found in node_modules/codemirror/addons/comment

Instantiating the CodeMirror Instance

Define a keyboard shortcut to trigger the comment toggle in the CodeMirror options object.

{
  extraKeys: {
    'Ctrl-/': editor.execCommand('toggleComment')
  }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)