Skip to content

Commit

Permalink
fix: codemirror editor tab behavior
Browse files Browse the repository at this point in the history
  • Loading branch information
jczhong84 committed Nov 22, 2024
1 parent 7dd47c0 commit 6f3b46f
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { KeyBinding, keymap, Prec } from '@uiw/react-codemirror';
import { useCallback, useMemo } from 'react';

import { CodeMirrorKeyMap } from 'lib/codemirror';
import { indentLess, insertTab } from '@codemirror/commands';

export const useKeyMapExtension = ({
keyMap = {},
Expand Down Expand Up @@ -41,7 +40,6 @@ export const useKeyMapExtension = ({
})),
])
),
keymap.of([{ key: 'Tab', run: insertTab, shift: indentLess }]),
],
[keyBindings, keyMap, transformKey]
);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,29 @@
import { indentLess, indentMore, insertTab } from '@codemirror/commands';
import { indentUnit } from '@codemirror/language';
import { EditorView } from '@uiw/react-codemirror';
import { EditorSelection, EditorState, Extension } from '@codemirror/state';
import { EditorView, keymap } from '@uiw/react-codemirror';
import { useMemo } from 'react';
import { EditorState, Extension } from '@codemirror/state';

// Insert spaces instead of a real tab to reach the next tab stop
const insertSpacesOnTab =
(tabSize: number) =>
({ state, dispatch }) => {
const line = state.doc.lineAt(state.selection.main.from);
const column = state.selection.main.from - line.from;
const spacesToInsert = tabSize - (column % tabSize);

let changes = state.changeByRange((range) => ({
changes: {
from: range.from,
to: range.to,
insert: ' '.repeat(spacesToInsert),
},
range: EditorSelection.cursor(range.from + spacesToInsert),
}));

dispatch(state.update(changes, { userEvent: 'input' }));
return true;
};

export const useOptionsExtension = ({
lineWrapping = true,
Expand All @@ -15,9 +37,27 @@ export const useOptionsExtension = ({

if (options.indentWithTabs) {
extensions.push(indentUnit.of('\t'));
extensions.push(EditorState.tabSize.of(options.tabSize));
extensions.push(
keymap.of([
{
key: 'Tab',
run: insertTab,
shift: indentLess,
},
])
);
} else {
extensions.push(EditorState.tabSize.of(options.tabSize));
extensions.push(indentUnit.of(' '.repeat(options.indentUnit)));
extensions.push(
keymap.of([
{
key: 'Tab',
run: insertSpacesOnTab(options.tabSize),
shift: indentLess,
},
])
);
}

if (lineWrapping) {
Expand Down

0 comments on commit 6f3b46f

Please sign in to comment.