Skip to content

Commit 750d5be

Browse files
Wrap selected text when typing markdown markers
1 parent 3e9b966 commit 750d5be

2 files changed

Lines changed: 54 additions & 0 deletions

File tree

src/editor/selection-wrap.ts

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import { EditorView } from "@codemirror/view";
2+
3+
const WRAP_PAIRS: Record<string, [string, string]> = {
4+
"*": ["*", "*"],
5+
"_": ["_", "_"],
6+
"`": ["`", "`"],
7+
"'": ["'", "'"],
8+
'"': ['"', '"'],
9+
"=": ["==", "=="],
10+
"~": ["~~", "~~"],
11+
};
12+
13+
function wrapMainSelection(
14+
view: EditorView,
15+
before: string,
16+
after: string
17+
): boolean {
18+
const { main, ranges } = view.state.selection;
19+
if (ranges.length !== 1 || main.empty) return false;
20+
21+
const { from, to } = main;
22+
const selected = view.state.doc.sliceString(from, to);
23+
view.dispatch({
24+
changes: { from, to, insert: `${before}${selected}${after}` },
25+
selection: {
26+
anchor: from + before.length,
27+
head: from + before.length + selected.length,
28+
},
29+
});
30+
return true;
31+
}
32+
33+
export const selectionWrapOnType = EditorView.domEventHandlers({
34+
keydown(event, view) {
35+
if (
36+
event.defaultPrevented ||
37+
event.metaKey ||
38+
event.ctrlKey ||
39+
event.altKey ||
40+
event.isComposing
41+
) {
42+
return false;
43+
}
44+
45+
const pair = WRAP_PAIRS[event.key];
46+
if (!pair) return false;
47+
48+
const didWrap = wrapMainSelection(view, pair[0], pair[1]);
49+
if (didWrap) event.preventDefault();
50+
return didWrap;
51+
},
52+
});

src/editor/setup.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import {
1515
import { closeBrackets, closeBracketsKeymap } from "@codemirror/autocomplete";
1616
import { obsidianTheme } from "./theme";
1717
import { markdownRenderPlugin } from "./markdown-render";
18+
import { selectionWrapOnType } from "./selection-wrap";
1819

1920
export function createEditor(
2021
parent: HTMLElement,
@@ -29,6 +30,7 @@ export function createEditor(
2930
drawSelection(),
3031
highlightActiveLine(),
3132
EditorView.lineWrapping,
33+
selectionWrapOnType,
3234

3335
// Keymaps
3436
keymap.of([

0 commit comments

Comments
 (0)