-
Notifications
You must be signed in to change notification settings - Fork 1
/
extension.ts
889 lines (808 loc) · 27.9 KB
/
extension.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
// useful API pages
// https://code.visualstudio.com/api/references/vscode-api#TextEditor
// https://code.visualstudio.com/api/references/vscode-api#TextDocument
// https://code.visualstudio.com/api/references/vscode-api#TextLine
// https://code.visualstudio.com/api/references/vscode-api#Selection
// https://code.visualstudio.com/api/references/vscode-api#Position
// https://code.visualstudio.com/api/references/vscode-api#Range
import * as vscode from "vscode"
import { getConfigKey } from "./config"
const DEBUG = process.env.DEBUG_EXTENSION === "true"
/** zero width space that essentially brands changes made by this extension */
const MAGIC_CHARACTER = ""
// regexes
const LINE_COMMENT_TAG = "//"
const BLOCK_COMMENT_START_TAG = "/*"
const BLOCK_COMMENT_END_TAG = "*/"
const JSDOC_START_TAG = "/**"
const JSDOC_END_TAG = "*/"
const JSDOC_LINE_CHAR = "*"
const JSDOC_START_REGEX = /\/\*\*\s?/
const JSDOC_END_REGEX = /\s?\*\//
const JSDOC_LINE_CHAR_REGEX = /\s\*\s/
export const log = (...messages: unknown[]): void => {
if (DEBUG) {
console.log(...messages)
}
}
/**
* helper to guarantee the active editor is defined.
*
* guards against an invariant state by yeeting the entire extension when no
* editor
*
* should **NOT** be possible to ever trigger
*
* @returns currently visible editor, safely
*/
export const getEditor = (): vscode.TextEditor => {
const editor = vscode.window.activeTextEditor
if (!editor) {
throw new Error("no active editor, make sure a file is open")
}
return editor
}
const setCursorSelection = (selection: vscode.Selection) => {
const editor = getEditor()
if (!editor.selection.active.isEqual(selection.active)) {
log(
`adjusting cursor: [${editor.selection.active.line}, ${editor.selection.active.character}] => [${selection.active.line}, ${selection.active.character}]`,
)
}
if (
hasSelection(editor) &&
!editor.selection.anchor.isEqual(selection.anchor)
) {
log(
`adjusting anchor: [${editor.selection.anchor.line}, ${editor.selection.anchor.character}] => [${selection.anchor.line}, ${selection.anchor.character}]`,
)
}
editor.selection = selection
}
/**
* @param line - input
* @returns the line directly proceeding the input
*/
function getPrevLine(
line: vscode.TextLine | number,
): vscode.TextLine | undefined {
const editor = getEditor()
const lineNumber = typeof line === "number" ? line : line.lineNumber
return lineNumber <= 0 ? undefined : editor.document.lineAt(lineNumber - 1)
}
/**
* @param line - input
* @returns the line directly following the input
*/
function getNextLine(
line: vscode.TextLine | number,
): vscode.TextLine | undefined {
const editor = getEditor()
const lineNumber = typeof line === "number" ? line : line.lineNumber
const lastLineNumber = editor.document.lineCount - 1
return lineNumber >= lastLineNumber
? undefined
: editor.document.lineAt(lineNumber + 1)
}
/** @returns the last line of the current selection */
function getSelectionLastLine(): vscode.TextLine {
const editor = getEditor()
return editor.document.lineAt(editor.selection.end.line)
}
/**
* @param position - input
* @returns the char before the position or empty string if at start of line
*/
function getPrevChar(position: vscode.Position): string {
const editor = getEditor()
return editor.document.getText(
new vscode.Range(
position.with({ character: Math.max(position.character - 1, 0) }),
position,
),
)
}
/**
* @param position - input
* @returns the char after the position or empty string if at end of line
*/
function getNextChar(position: vscode.Position): string {
const editor = getEditor()
return editor.document.getText(
new vscode.Range(
position,
position.with({ character: position.character + 1 }),
),
)
}
/**
* @param editor - vscode's currently active text editor
* @returns whether any text is currently selected
*/
const hasSelection = (editor: vscode.TextEditor): boolean =>
!editor.selection.active.isEqual(editor.selection.anchor)
/**
* @param line - target
* @returns position of first non-whitespace character on target line
*/
function getContentStartPos(line: vscode.TextLine | number): vscode.Position {
const editor = getEditor()
return new vscode.Position(
typeof line === "number" ? line : line.lineNumber,
(typeof line === "number"
? editor.document.lineAt(line)
: line
).firstNonWhitespaceCharacterIndex,
)
}
/**
* @param line - target
* @returns position of last character on target line
*/
export function getContentEndPos(
line: vscode.TextLine | number,
): vscode.Position {
const editor = getEditor()
return (typeof line === "number" ? editor.document.lineAt(line) : line).range
.end
}
/**
* @param line - target
* @returns concatenated value of indentation on target line
*/
export const getIndentation = (line: vscode.TextLine | number): string => {
const editor = getEditor()
const currentLine =
typeof line === "number" ? editor.document.lineAt(line) : line
return editor.document.getText(
currentLine.range.with({
end: currentLine.range.end.with({
character: currentLine.firstNonWhitespaceCharacterIndex,
}),
}),
)
}
// #region - fix cursor / selection pos
/**
* if cursor was at end of last line, the comment tag is errantly placed before
* the cursor. this moves the comment tag after the cursor, keeping the cursor
* in the original position before the JSDoc was inserted vscode doesn't have
* the ability to add to line index greater than max
*
* @deprecated - inaccurate results if called _during_ a textEdit. if called
* _after_, the cursor movement is noticeable and somewhat slow
* @param isSingleLineComment - precalculated
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const adjustCursorPos = async (isSingleLineComment: boolean) => {
log("adjusting cursor pos")
const editor = getEditor()
const cursorPos = editor.selection.active
// adjust single line comment cursor
if (isSingleLineComment) {
// if (
// editor.selection.end.isEqual(getContentEndPos(editor.selection.end.line))
// ) {
// if (editor.selection.anchor.isAfter(editor.selection.active)) {
// editor.selection = new vscode.Selection(
// editor.selection.anchor.translate({ characterDelta: -3 }),
// editor.selection.active
// )
// } else {
// editor.selection = new vscode.Selection(
// editor.selection.anchor,
// editor.selection.active.translate({ characterDelta: -3 })
// )
// }
// }
// at end of line
if (cursorPos.isEqual(getContentEndPos(cursorPos.line))) {
// https://code.visualstudio.com/api/references/commands
await vscode.commands.executeCommand("cursorMove", {
to: "left",
by: "character",
value: 3,
select: hasSelection(editor),
})
} else if (
// handle backwards selection range at end of line
editor.selection.anchor.isEqual(
getContentEndPos(editor.selection.anchor.line),
)
) {
editor.selection = new vscode.Selection(
editor.selection.active,
editor.selection.anchor,
)
await vscode.commands.executeCommand("cursorMove", {
to: "left",
by: "character",
value: 3,
select: hasSelection(editor),
})
editor.selection = new vscode.Selection(
editor.selection.active,
editor.selection.anchor,
)
} else {
/* noop */
}
} else {
// adjust multiline comment cursor
// selection ends at end of line
if (
editor.selection.end.isAfterOrEqual(
getContentEndPos(editor.selection.end.line),
)
) {
const adjustedSelectionEndPos = getContentEndPos(
editor.selection.end.line - 1,
)
// ensure cursor is at original side of the selection
const isCursorAtEnd = cursorPos.isEqual(editor.selection.end)
setCursorSelection(
new vscode.Selection(
isCursorAtEnd ? editor.selection.start : adjustedSelectionEndPos,
isCursorAtEnd ? adjustedSelectionEndPos : editor.selection.start,
),
)
}
// selection starts before first non-whitespace char of line
if (
editor.selection.start.isBefore(
getContentStartPos(editor.selection.start.line),
)
) {
const adjustedSelectionStartPos = getContentStartPos(
editor.selection.start.line + 1,
).translate({ characterDelta: 2 })
// ensure cursor is at same side of selection
const isCursorAtStart = cursorPos.isEqual(editor.selection.start)
setCursorSelection(
new vscode.Selection(
isCursorAtStart ? editor.selection.end : adjustedSelectionStartPos,
isCursorAtStart ? adjustedSelectionStartPos : editor.selection.end,
),
)
}
}
}
/**
* primary extension action, removes the JSDoc tags on selected lines if present
* or inserts a JSDoc wrapping the selected lines of text comment
*
* @returns once edit is complete
*/
export const toggleJSDocComment = async (): Promise<boolean> => {
const editor = getEditor()
/** within selection, not live */
let lineFirst = editor.document.lineAt(editor.selection.start.line)
/** within selection, not live */
let lineLast = editor.document.lineAt(editor.selection.end.line)
const lineActive = editor.document.lineAt(editor.selection.active.line)
const lineAnchor = editor.document.lineAt(editor.selection.anchor.line)
/** first line num of selection === last line num */
const isSingleLineSelection = lineFirst.lineNumber === lineLast.lineNumber
let jsdocStart = lineFirst.text.match(JSDOC_START_REGEX)
let jsdocEnd = lineLast.text.match(JSDOC_END_REGEX)
// fix multiline selection when open or close tag not selected
// use start tag on prev line if it exists
/** should actually check all lines between `lineFirst` and `lineLast` */
const isJsdoc =
lineActive.text.trim().startsWith(JSDOC_LINE_CHAR) ||
lineAnchor.text.trim().startsWith(JSDOC_LINE_CHAR)
if (isJsdoc && !jsdocStart && lineFirst.lineNumber !== 0) {
const lineBefore = getPrevLine(lineFirst)
const jsdocMatch = lineBefore?.text.match(JSDOC_START_REGEX)
if (lineBefore && jsdocMatch) {
lineFirst = lineBefore
jsdocStart = jsdocMatch
}
}
// use end tag on next line if it exists
// TODO: use a separate var to store the start and end line of comments
if (
isJsdoc &&
!jsdocEnd &&
lineLast.lineNumber !== editor.document.lineCount - 1
) {
const lineAfter = getNextLine(lineLast)
const jsdocMatch = lineAfter?.text.match(JSDOC_END_REGEX)
if (lineAfter && jsdocMatch) {
lineLast = lineAfter
jsdocEnd = jsdocMatch
}
}
// add hidden text to enable using a replace operation when the cursor is at the end of
// the line without altering the cursor position
if (
!getConfigKey("disableCursorHack") &&
jsdocStart?.index === undefined &&
jsdocEnd?.index === undefined &&
editor.selection.end.character ===
getSelectionLastLine().range.end.character
) {
const originalSelection = new vscode.Selection(
editor.selection.anchor,
editor.selection.active,
)
await editor.insertSnippet(
new vscode.SnippetString(`$0${MAGIC_CHARACTER}`),
editor.selection.end,
{ undoStopAfter: false, undoStopBefore: false },
)
// insert snippet removes the current selection, so restore it
if (!editor.selection.isEqual(originalSelection)) {
setCursorSelection(originalSelection)
}
}
// construct and trigger single batch of changes
return editor.edit((editBuilder) => {
// #region - remove single line jsdoc, selection or no selection
const isJSDocCommentFullLine =
lineFirst.firstNonWhitespaceCharacterIndex === jsdocStart?.index &&
jsdocEnd &&
getContentEndPos(lineFirst).character - jsdocEnd[0].length ===
jsdocEnd.index
if (
isSingleLineSelection &&
jsdocStart?.index !== undefined &&
jsdocEnd?.index !== undefined &&
(new vscode.Range(
lineFirst.lineNumber,
jsdocStart.index,
lineLast.lineNumber,
jsdocEnd.index + jsdocEnd[0].length,
).contains(editor.selection.active) ||
isJSDocCommentFullLine)
) {
log("removing single line jsdoc")
// trailing
if (
jsdocEnd.index + jsdocEnd[0].length ===
getContentEndPos(lineLast).character
) {
editBuilder.replace(
new vscode.Range(
lineFirst.lineNumber,
jsdocStart.index,
lineFirst.lineNumber,
jsdocStart.index + jsdocStart[0].length,
),
"// ",
)
editBuilder.delete(
new vscode.Range(
lineLast.lineNumber,
jsdocEnd.index,
lineLast.lineNumber,
jsdocEnd.index + jsdocEnd[0].length,
),
)
} else {
// internal
editBuilder.replace(
new vscode.Range(
lineFirst.lineNumber,
jsdocStart.index,
lineFirst.lineNumber,
jsdocStart.index + jsdocStart[0].length,
),
"/* ",
)
}
return
}
// #region - remove multi line jsdoc
if (!isSingleLineSelection && jsdocStart?.index && jsdocEnd?.index) {
log("removing multi line jsdoc")
// open & close tags (first and last line)
editBuilder.delete(lineFirst.rangeIncludingLineBreak)
editBuilder.delete(lineLast.rangeIncludingLineBreak)
// continuation comment line's *s
for (
let i = lineFirst.lineNumber + 1;
i <= lineLast.lineNumber - 1;
i += 1
) {
const line = editor.document.lineAt(i)
const jsdocComment = line.text.match(JSDOC_LINE_CHAR_REGEX)
if (jsdocComment?.index) {
editBuilder.replace(
new vscode.Range(
line.lineNumber,
jsdocComment.index,
line.lineNumber,
jsdocComment.index + 3,
),
"// ",
)
}
}
// handled removing existing jsdoc, job done
return
}
// #region - no jsdoc exists but possibly block or line comment
if (isSingleLineSelection) {
const lineCommentIndex = lineFirst.text.indexOf(LINE_COMMENT_TAG)
const isLineCommentFullLine =
lineFirst.firstNonWhitespaceCharacterIndex === lineCommentIndex
const blockCommentStartIndex = lineFirst.text.indexOf(
BLOCK_COMMENT_START_TAG,
)
const blockCommentEndIndex = lineFirst.text.indexOf(BLOCK_COMMENT_END_TAG)
const isBlockCommentFullLine =
lineFirst.firstNonWhitespaceCharacterIndex === blockCommentStartIndex &&
getContentEndPos(lineFirst).character - BLOCK_COMMENT_END_TAG.length ===
blockCommentEndIndex
const isBlockCommentTrailing =
lineFirst.firstNonWhitespaceCharacterIndex !== blockCommentStartIndex &&
(lineFirst.text.length - BLOCK_COMMENT_END_TAG.length ===
blockCommentEndIndex ||
lineFirst.text.length - BLOCK_COMMENT_END_TAG.length - 1 ===
blockCommentEndIndex)
if (
hasSelection(editor) &&
!jsdocStart?.index &&
!jsdocEnd?.index &&
lineCommentIndex === -1 &&
blockCommentStartIndex === -1 &&
blockCommentEndIndex === -1
) {
log("adding new jsdoc comment to line WITH A SELECTION")
editBuilder.insert(editor.selection.start, "/** ")
const nextChar = getNextChar(editor.selection.end)
editBuilder.replace(
new vscode.Range(
editor.selection.end,
editor.selection.end.translate({ characterDelta: 1 }),
),
` */${nextChar === MAGIC_CHARACTER ? "" : nextChar}`,
)
} else if (
blockCommentStartIndex > -1 &&
blockCommentEndIndex > -1 &&
// active cursor within block comment or full line is a block comment
((editor.selection.active.character >= blockCommentStartIndex &&
editor.selection.active.character <
blockCommentEndIndex + BLOCK_COMMENT_END_TAG.length + 1) ||
isBlockCommentFullLine)
) {
log("converting block comment to jsdoc")
const firstChar = editor.document.getText(
new vscode.Range(
lineFirst.lineNumber,
blockCommentStartIndex + BLOCK_COMMENT_START_TAG.length,
lineFirst.lineNumber,
blockCommentStartIndex + BLOCK_COMMENT_START_TAG.length + 1,
),
)
if (isBlockCommentTrailing) {
const indent = getIndentation(lineFirst)
const prevContent = editor.document
.getText(
new vscode.Range(
getContentStartPos(lineFirst),
new vscode.Position(
lineFirst.lineNumber,
blockCommentStartIndex,
),
),
)
.trim()
const nextContent = editor.document
.getText(
new vscode.Range(
new vscode.Position(
lineFirst.lineNumber,
blockCommentEndIndex + BLOCK_COMMENT_END_TAG.length,
),
getContentEndPos(lineLast),
),
)
.trim()
const prevCommentChars = editor.document
.getText(
new vscode.Range(
new vscode.Position(
lineFirst.lineNumber,
blockCommentStartIndex + BLOCK_COMMENT_START_TAG.length,
),
editor.selection.active,
),
)
.trimStart()
const nextCommentChars = editor.document
.getText(
new vscode.Range(
editor.selection.active,
new vscode.Position(lineFirst.lineNumber, blockCommentEndIndex),
),
)
.trimEnd()
editBuilder.replace(
new vscode.Range(
editor.selection.active.with({ character: 0 }),
editor.selection.active,
),
"",
)
editBuilder.insert(
editor.selection.active.with({ character: 0 }),
`${indent}/** ${prevCommentChars}`,
)
editBuilder.replace(
new vscode.Range(
editor.selection.active,
getContentEndPos(editor.selection.active.line),
),
`${nextCommentChars} */\n${indent}${prevContent}${nextContent}`,
)
} else {
editBuilder.replace(
new vscode.Range(
lineFirst.lineNumber,
blockCommentStartIndex,
lineFirst.lineNumber,
blockCommentStartIndex + BLOCK_COMMENT_START_TAG.length,
),
"",
)
editBuilder.insert(
new vscode.Position(lineFirst.lineNumber, blockCommentStartIndex),
`/**${firstChar === " " ? "" : " "}`,
)
}
} else if (
lineCommentIndex > -1 &&
(editor.selection.active.character > lineCommentIndex ||
isLineCommentFullLine)
) {
log("converting line comment to jsdoc")
const indent = getIndentation(lineFirst)
const prevLineText = getPrevLine(lineFirst)?.text.trim()
const nextLineText = getNextLine(lineFirst)?.text.trim()
// already starts with a star
if (lineFirst.text.trim().startsWith(JSDOC_LINE_CHAR)) {
editBuilder.replace(
new vscode.Range(
lineFirst.lineNumber,
lineCommentIndex,
lineFirst.lineNumber,
lineCommentIndex + LINE_COMMENT_TAG.length,
),
"",
)
} else if (
// line comment nested inside jsdoc
prevLineText?.startsWith(JSDOC_START_TAG) ||
prevLineText?.startsWith(JSDOC_LINE_CHAR) ||
nextLineText?.startsWith(JSDOC_LINE_CHAR) ||
nextLineText?.startsWith(JSDOC_END_TAG)
) {
editBuilder.replace(
new vscode.Range(
lineFirst.lineNumber,
lineCommentIndex,
lineFirst.lineNumber,
lineCommentIndex + LINE_COMMENT_TAG.length,
),
"*",
)
} else if (isLineCommentFullLine) {
const firstChar = editor.document.getText(
new vscode.Range(
lineFirst.lineNumber,
lineCommentIndex + LINE_COMMENT_TAG.length,
lineFirst.lineNumber,
lineCommentIndex + LINE_COMMENT_TAG.length + 1,
),
)
// REVIEW: could try to standardize by matching before and after cursor with regex here
editBuilder.replace(
new vscode.Range(
lineFirst.lineNumber,
lineCommentIndex,
lineFirst.lineNumber,
lineCommentIndex + LINE_COMMENT_TAG.length,
),
"",
)
editBuilder.insert(
new vscode.Position(lineFirst.lineNumber, lineCommentIndex),
`/**${firstChar === " " ? "" : " "}`,
)
const lastChar = editor.document.getText(
new vscode.Range(
getContentEndPos(lineFirst).translate(0, -1),
getContentEndPos(lineFirst),
),
)
editBuilder.replace(
new vscode.Range(
getContentEndPos(lineFirst),
getContentEndPos(lineFirst).translate({ characterDelta: 1 }),
),
`${lastChar && lastChar !== " " ? " " : ""}*/`,
)
} else {
// line comment trails code
const prevContent = editor.document
.getText(
new vscode.Range(
getContentStartPos(lineFirst),
new vscode.Position(lineFirst.lineNumber, lineCommentIndex),
),
)
.trim()
const prevCommentChars = editor.document
.getText(
new vscode.Range(
new vscode.Position(
lineFirst.lineNumber,
lineCommentIndex + LINE_COMMENT_TAG.length,
),
editor.selection.active,
),
)
.trimStart()
const nextCommentChars = editor.document
.getText(
new vscode.Range(
editor.selection.active,
getContentEndPos(lineFirst),
),
)
.trimEnd()
editBuilder.replace(
new vscode.Range(
editor.selection.active.with({ character: 0 }),
editor.selection.active,
),
"",
)
editBuilder.insert(
editor.selection.active.with({ character: 0 }),
`${indent}/** ${prevCommentChars}`,
)
editBuilder.replace(
new vscode.Range(
editor.selection.active,
getContentEndPos(editor.selection.active.line),
),
`${nextCommentChars} */\n${indent}${prevContent}`,
)
}
} else {
log("adding NEW jsdoc comment when NO SELECTION")
const prevChar = getPrevChar(editor.selection.active)
const nextChar = getNextChar(editor.selection.active)
const isLineBlank =
lineActive.isEmptyOrWhitespace ||
lineActive.text.includes(MAGIC_CHARACTER)
if (
(!isLineBlank &&
editor.selection.active.character ===
lineActive.firstNonWhitespaceCharacterIndex) ||
(prevChar === " " &&
nextChar === " " &&
editor.selection.active.character >
lineActive.firstNonWhitespaceCharacterIndex)
) {
log(
"add inline jsdoc, cursor at start of non-empty line or has spaces on both sides",
)
editBuilder.insert(editor.selection.active, "/** ")
editBuilder.replace(
new vscode.Range(
editor.selection.active,
editor.selection.active.translate({ characterDelta: 1 }),
),
` */${nextChar && nextChar !== " " ? " " : ""}${nextChar}`,
)
} else {
log(
"add jsdoc on prev line, cursor somewhere in middle, or at end of line, or at start of blank line",
)
const indent = getIndentation(lineFirst)
const prevChars = editor.document.getText(
new vscode.Range(
editor.selection.active.with({ character: 0 }),
editor.selection.active,
),
)
editBuilder.replace(
new vscode.Range(
editor.selection.active.with({ character: 0 }),
editor.selection.active,
),
``,
)
editBuilder.insert(
editor.selection.active.with({ character: 0 }),
`${indent}/** `,
)
editBuilder.replace(
new vscode.Range(
editor.selection.active,
editor.selection.active.translate({ characterDelta: 1 }),
),
// if there are non-whitespace chars on the line, move comment to previous line
isLineBlank
? ` */`
: ` */\n${prevChars}${
nextChar === MAGIC_CHARACTER ? "" : nextChar
}`,
)
}
}
return
}
// #region - insert multi line comment
log("inserting multi line jsdoc")
const indentation = getIndentation(lineFirst)
editBuilder.insert(getContentStartPos(lineFirst), `/**\n${indentation}`)
// target all lines between opening tag exclusive and closing tag inclusive
for (let i = lineFirst.lineNumber; i <= lineLast.lineNumber; i += 1) {
const line = editor.document.lineAt(i)
const contentStart = line.text.slice(
line.firstNonWhitespaceCharacterIndex,
)
const commentTag = contentStart.match(LINE_COMMENT_TAG)
if (commentTag) {
const firstChar = getNextChar(
new vscode.Position(
line.lineNumber,
line.firstNonWhitespaceCharacterIndex + commentTag[0].length,
),
)
editBuilder.replace(
new vscode.Range(
line.lineNumber,
line.firstNonWhitespaceCharacterIndex,
line.lineNumber,
line.firstNonWhitespaceCharacterIndex + commentTag[0].length,
),
` *${firstChar === " " ? "" : " "}`,
)
} else {
editBuilder.insert(getContentStartPos(line), " * ")
}
}
const contentEnd = getContentEndPos(lineLast)
const nextChar = getNextChar(contentEnd)
editBuilder.replace(
new vscode.Range(contentEnd, contentEnd.translate({ characterDelta: 1 })),
`\n${indentation} */${nextChar === MAGIC_CHARACTER ? "" : nextChar}`,
)
})
}
export const activate = (context: vscode.ExtensionContext): void => {
// REVIEW: consider using `registerTextEditorCommand`
const disposable = vscode.commands.registerCommand(
"jsdoc-comment-toggler.toggle",
toggleJSDocComment,
)
// TODO: investigate possible performance issues with this
// when an undo or redo contains our magic character, perform it twice as adding
// and removing the magic character is an extra item on the undo stack
vscode.workspace.onDidChangeTextDocument(
(event) => {
if (event.contentChanges[0]?.text === MAGIC_CHARACTER) {
if (event.reason === vscode.TextDocumentChangeReason.Undo) {
vscode.commands.executeCommand("undo")
} else if (event.reason === vscode.TextDocumentChangeReason.Redo) {
vscode.commands.executeCommand("redo")
} else {
// ignore undefined event reasons (e.g. typing)
}
}
},
null,
context.subscriptions,
)
if (DEBUG) {
vscode.window.showInformationMessage("jsdoc comment toggler loaded")
}
context.subscriptions.push(disposable)
}