File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ } ) ;
Original file line number Diff line number Diff line change @@ -15,6 +15,7 @@ import {
1515import { closeBrackets , closeBracketsKeymap } from "@codemirror/autocomplete" ;
1616import { obsidianTheme } from "./theme" ;
1717import { markdownRenderPlugin } from "./markdown-render" ;
18+ import { selectionWrapOnType } from "./selection-wrap" ;
1819
1920export 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 ( [
You can’t perform that action at this time.
0 commit comments