Skip to content

Instantly share code, notes, and snippets.

@danieleds
Created September 4, 2014 08:48
Show Gist options
  • Save danieleds/326903084a196055a7c3 to your computer and use it in GitHub Desktop.
Save danieleds/326903084a196055a7c3 to your computer and use it in GitHub Desktop.
CodeMirror: indent with tab or spaces
editor.addKeyMap({
"Tab": function (cm) {
if (cm.somethingSelected()) {
var sel = editor.getSelection("\n");
// Indent only if there are multiple lines selected, or if the selection spans a full line
if (sel.length > 0 && (sel.indexOf("\n") > -1 || sel.length === cm.getLine(cm.getCursor().line).length)) {
cm.indentSelection("add");
return;
}
}
if (cm.options.indentWithTabs)
cm.execCommand("insertTab");
else
cm.execCommand("insertSoftTab");
},
"Shift-Tab": function (cm) {
cm.indentSelection("subtract");
}
});
@danieleds
Copy link
Author

@cnlohr this is from 10 years ago - the API might have changed

@cnlohr
Copy link

cnlohr commented Jul 8, 2024

It looks like you have to make a new extensions, based on the baseextensions now, like this:

const baseExtensions = {
	lineNumbers: lineNumbers(),
	highlightActiveLineGutter: highlightActiveLineGutter(),
	highlightSpecialChars: highlightSpecialChars(),
	history: history(),
	foldGutter: foldGutter(),
	drawSelection: drawSelection(),
	dropCursor: dropCursor(),
	allowMultipleSelections: EditorState.allowMultipleSelections.of(true),
	indentOnInput: indentOnInput(),
	syntaxHighlighting: syntaxHighlighting(defaultHighlightStyle, {
		fallback: true,
	}),
	//bracketMatching: bracketMatching(),
	//closeBrackets: closeBrackets(),
	autocompletion: autocompletion(),
	rectangularSelection: rectangularSelection(),
	crosshairCursor: crosshairCursor(),
	highlightActiveLine: highlightActiveLine(),
	highlightSelectionMatches: highlightSelectionMatches(),
	keymap: keymap.of([
		indentWithTab,    <<<
		...defaultKeymap,
		...searchKeymap,
		...historyKeymap,
		...foldKeymap,
		...completionKeymap,
		...lintKeymap,
		//...closeBracketsKeymap,
	]),
	indentUnit : indentUnit.of("\t"),   <<<
};

It can be toggled with:

	const filteredExtensions = filteredBase(showLineNos ? [] : ["indentUnit"]);
	view.dispatch({
		effects: StateEffect.reconfigure.of([...filteredExtensions, cpp()]),
	});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment