Skip to content

Commit

Permalink
Merge pull request #6 from mattmundell/any-lang
Browse files Browse the repository at this point in the history
Support any language with JS style block comments
  • Loading branch information
tmcw authored Jan 6, 2025
2 parents 8b0de1c + 7fe72c7 commit e9a9455
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 9 deletions.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,4 +62,5 @@ extensions: [
```

And that's it! This will only do anything if your CodeMirror
is using the JavaScript or TypeScript mode.
is using a language that supports `/* */` style block comments,
like JavaScript and TypeScript.
36 changes: 28 additions & 8 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,36 @@ import { javascriptLanguage } from "@codemirror/lang-javascript";
import { syntaxTree } from "@codemirror/language";
import {
EditorSelection,
type EditorState,
type SelectionRange,
type StateCommand,
} from "@codemirror/state";
import type { KeyBinding } from "@codemirror/view";

// commentTokens: {line: "//", block: {open: "/*", close: "*/"}},
interface Block {
open: string | null,
close: string | null
}
interface CommentTokens {
line: string | null,
block: Block | null
}

const able = (state: EditorState, range: SelectionRange) => {
if (range.empty) {
const data = state.languageDataAt<CommentTokens>("commentTokens", range.from);
for (let i = 0; i < data.length; i++) {
const block = data[i]?.block;
if (block
&& (block.open === "/*")
&& (block.close === "*/"))
return true;
}
}
return false
}

/**
* This is modeled after the CodeMirror Markdown mode's
* ability to continue lists and blockquotes. It's meant to be bound
Expand All @@ -22,11 +47,9 @@ export const insertNewlineContinueComment: StateCommand = ({
const { doc } = state;
let dont: null | { range: SelectionRange } = null;
const changes = state.changeByRange((range) => {
// Don't do anything if we're not in JavaScript mode.
// This should also cover TypeScript, which is just
// JavaScript with extra configuration.
if (!range.empty || !javascriptLanguage.isActiveAt(state, range.from))
if (!able(state, range))
return (dont = { range });

const pos = range.from;
const line = doc.lineAt(pos);

Expand Down Expand Up @@ -82,10 +105,7 @@ export const maybeCloseBlockComment: StateCommand = ({ state, dispatch }) => {
const { doc } = state;
let dont: null | { range: SelectionRange } = null;
const changes = state.changeByRange((range) => {
// Don't do anything if we're not in JavaScript mode.
// This should also cover TypeScript, which is just
// JavaScript with extra configuration.
if (!range.empty || !javascriptLanguage.isActiveAt(state, range.from))
if (!able(state, range))
return (dont = { range });
const pos = range.from;
const line = doc.lineAt(pos);
Expand Down

0 comments on commit e9a9455

Please sign in to comment.