@@ -229,28 +229,20 @@ export function CodeJar(editor: HTMLElement, highlight: (e: HTMLElement, pos?: P
229
229
}
230
230
}
231
231
232
- function beforeCursor ( ) {
233
- const s = getSelection ( )
234
- const r0 = s . getRangeAt ( 0 )
235
- const r = document . createRange ( )
236
- r . selectNodeContents ( editor )
237
- r . setEnd ( r0 . startContainer , r0 . startOffset )
238
- return r . toString ( )
239
- }
240
-
241
- function afterCursor ( ) {
242
- const s = getSelection ( )
243
- const r0 = s . getRangeAt ( 0 )
244
- const r = document . createRange ( )
245
- r . selectNodeContents ( editor )
246
- r . setStart ( r0 . endContainer , r0 . endOffset )
247
- return r . toString ( )
232
+ function aroundCursor ( ) {
233
+ let { start, end, dir} = save ( )
234
+ if ( dir === '<-' ) {
235
+ [ start , end ] = [ end , start ]
236
+ }
237
+ const text = toString ( )
238
+ const before = text . slice ( 0 , start )
239
+ const after = text . slice ( end )
240
+ return { before, after}
248
241
}
249
242
250
243
function handleNewLine ( event : KeyboardEvent ) {
251
244
if ( event . key === 'Enter' ) {
252
- const before = beforeCursor ( )
253
- const after = afterCursor ( )
245
+ const { before, after} = aroundCursor ( )
254
246
255
247
const [ padding ] = findPadding ( before )
256
248
let newLinePadding = padding
@@ -284,7 +276,7 @@ export function CodeJar(editor: HTMLElement, highlight: (e: HTMLElement, pos?: P
284
276
if ( isLegacy && event . key === 'Enter' ) {
285
277
event . preventDefault ( )
286
278
event . stopPropagation ( )
287
- if ( afterCursor ( ) === '' ) {
279
+ if ( aroundCursor ( ) . after === '' ) {
288
280
insert ( '\n ' )
289
281
const pos = save ( )
290
282
pos . start = -- pos . end
@@ -314,7 +306,7 @@ export function CodeJar(editor: HTMLElement, highlight: (e: HTMLElement, pos?: P
314
306
if ( event . key === 'Tab' ) {
315
307
event . preventDefault ( )
316
308
if ( event . shiftKey ) {
317
- const before = beforeCursor ( )
309
+ const { before} = aroundCursor ( )
318
310
const [ padding , start ] = findPadding ( before )
319
311
if ( padding . length > 0 ) {
320
312
const pos = save ( )
@@ -405,13 +397,11 @@ export function CodeJar(editor: HTMLElement, highlight: (e: HTMLElement, pos?: P
405
397
return event . key . toUpperCase ( )
406
398
}
407
399
408
- function insert ( inserted : string ) {
409
- let { start, end} = save ( )
410
- const text = toString ( )
411
- const before = text . slice ( 0 , start )
412
- const after = text . slice ( end )
413
- editor . textContent = before + inserted + after
414
- start += inserted . length
400
+ function insert ( text : string ) {
401
+ let { start} = save ( )
402
+ const { before, after} = aroundCursor ( )
403
+ editor . textContent = before + text + after
404
+ start += text . length
415
405
restore ( { start, end : start } )
416
406
}
417
407
0 commit comments