This repository was archived by the owner on Sep 6, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7.5k
Expand file tree
/
Copy pathEditorCommandHandlers.js
More file actions
788 lines (680 loc) · 33.2 KB
/
EditorCommandHandlers.js
File metadata and controls
788 lines (680 loc) · 33.2 KB
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
/*
* Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
/*jslint vars: true, plusplus: true, devel: true, browser: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, $ */
/**
* Text-editing commands that apply to whichever Editor is currently focused
*/
define(function (require, exports, module) {
"use strict";
// Load dependent modules
var Commands = require("command/Commands"),
Strings = require("strings"),
CommandManager = require("command/CommandManager"),
EditorManager = require("editor/EditorManager"),
StringUtils = require("utils/StringUtils"),
TokenUtils = require("utils/TokenUtils");
/**
* List of constants
*/
var DIRECTION_UP = -1;
var DIRECTION_DOWN = +1;
/**
* @private
* Creates regular expressions for multiple line comments prefixes
* @param {Array.<string>} prefixes - Description
* @return {Array.<RegExp>}
*/
function _createLineExpressions(prefixes) {
var lineExps = [];
prefixes.forEach(function (prefix) {
lineExps.push(new RegExp("^\\s*" + StringUtils.regexEscape(prefix)));
});
return lineExps;
}
/**
* @private
* Returns true if any regular expression matches the given string
* @param {string} string
* @param {Array.<RegExp>} expressions
* @return {boolean}
*/
function _matchExpressions(string, expressions) {
var matchAny = false;
expressions.forEach(function (exp) {
matchAny = matchAny || string.match(exp);
});
return matchAny;
}
/**
* @private
* Searchs for an uncommented line between startLine and endLine
* @param {!Editor} editor
* @param {!number} startLine - valid line inside the document
* @param {!number} endLine - valid line inside the document
* @param {!Array.<string>} prefixes - Array of line comment prefixes
* @return {boolean} true if there is at least one uncommented line
*/
function _containsUncommented(editor, startLine, endLine, prefixes) {
var lineExp = _createLineExpressions(prefixes);
var containsUncommented = false;
var i;
var line;
for (i = startLine; i <= endLine; i++) {
line = editor.document.getLine(i);
// A line is commented out if it starts with 0-N whitespace chars, then "//"
if (!_matchExpressions(line, lineExp) && line.match(/\S/)) {
containsUncommented = true;
break;
}
}
return containsUncommented;
}
/**
* Add or remove line-comment tokens to all the lines in the selected range, preserving selection
* and cursor position. Applies to currently focused Editor.
*
* If all non-whitespace lines are already commented out, then we uncomment; otherwise we comment
* out. Commenting out adds the prefix at column 0 of every line. Uncommenting removes the first prefix
* on each line (if any - empty lines might not have one).
*
* @param {!Editor} editor
* @param {!Array.<string>} prefixes, e.g. ["//"]
*/
function lineCommentPrefix(editor, prefixes) {
var doc = editor.document;
var sel = editor.getSelection();
var startLine = sel.start.line;
var endLine = sel.end.line;
// Is a range of text selected? (vs just an insertion pt)
var hasSelection = (startLine !== endLine) || (sel.start.ch !== sel.end.ch);
// In full-line selection, cursor pos is start of next line - but don't want to modify that line
if (sel.end.ch === 0 && hasSelection) {
endLine--;
}
// Decide if we're commenting vs. un-commenting
// Are there any non-blank lines that aren't commented out? (We ignore blank lines because
// some editors like Sublime don't comment them out)
var containsUncommented = _containsUncommented(editor, startLine, endLine, prefixes);
var i, j;
var line;
var trimmedLine;
var commentI;
var updateSelection = false;
// Make the edit
doc.batchOperation(function () {
if (containsUncommented) {
// Comment out - prepend the first prefix to each line
for (i = startLine; i <= endLine; i++) {
doc.replaceRange(prefixes[0], {line: i, ch: 0});
}
// Make sure selection includes the prefix that was added at start of range
if (sel.start.ch === 0 && hasSelection) {
updateSelection = true;
}
} else {
// Uncomment - remove first every prefix on each line (if any)
for (i = startLine; i <= endLine; i++) {
line = doc.getLine(i);
trimmedLine = line.trim();
for (j = 0; j < prefixes.length; j++) {
commentI = line.indexOf(prefixes[j]);
if (trimmedLine.indexOf(prefixes[j]) === 0) {
doc.replaceRange("", {line: i, ch: commentI}, {line: i, ch: commentI + prefixes[j].length});
break;
}
}
}
}
});
// Update the selection after the document batch so it's not blown away on resynchronization
// if this editor is not the master editor.
if (updateSelection) {
// use *current* selection end, which has been updated for our text insertions
editor.setSelection({line: startLine, ch: 0}, editor.getSelection().end);
}
}
/**
* @private
* Moves the token context to the token that starts the block-comment. Ctx starts in a block-comment.
* Returns the position of the prefix or null if gets to the start of the document and didn't found it.
* @param {!{editor:{CodeMirror}, pos:{ch:{string}, line:{number}}, token:{object}}} ctx - token context
* @param {!RegExp} prefixExp - a valid regular expression
* @return {?{line: number, ch: number}}
*/
function _findCommentStart(ctx, prefixExp) {
var result = true;
while (result && !ctx.token.string.match(prefixExp)) {
result = TokenUtils.moveSkippingWhitespace(TokenUtils.movePrevToken, ctx);
}
return result ? {line: ctx.pos.line, ch: ctx.token.start} : null;
}
/**
* @private
* Moves the token context to the token that ends the block-comment. Ctx starts in a block-comment.
* Returns the position of the sufix or null if gets to the end of the document and didn't found it.
* @param {!{editor:{CodeMirror}, pos:{ch:{string}, line:{number}}, token:{object}}} ctx - token context
* @param {!RegExp} suffixExp - a valid regular expression
* @param {!number} suffixLen - length of the suffix
* @return {?{line: number, ch: number}}
*/
function _findCommentEnd(ctx, suffixExp, suffixLen) {
var result = true;
while (result && !ctx.token.string.match(suffixExp)) {
result = TokenUtils.moveSkippingWhitespace(TokenUtils.moveNextToken, ctx);
}
return result ? {line: ctx.pos.line, ch: ctx.token.end - suffixLen} : null;
}
/**
* @private
* Moves the token context to the next block-comment if there is one before end.
* @param {!{editor:{CodeMirror}, pos:{ch:{string}, line:{number}}, token:{object}}} ctx - token context
* @param {!{line: number, ch: number}} end - where to stop searching
* @param {!RegExp} prefixExp - a valid regular expression
* @return {boolean} - true if it found a block-comment
*/
function _findNextBlockComment(ctx, end, prefixExp) {
var index = ctx.editor.indexFromPos(end),
inside = ctx.editor.indexFromPos(ctx.pos) <= index,
result = true;
while (result && inside && !ctx.token.string.match(prefixExp)) {
result = TokenUtils.moveSkippingWhitespace(TokenUtils.moveNextToken, ctx);
inside = ctx.editor.indexFromPos(ctx.pos) <= index;
}
return result && inside && !!ctx.token.string.match(prefixExp);
}
/**
* Add or remove block-comment tokens to the selection, preserving selection
* and cursor position. Applies to the currently focused Editor.
*
* If the selection is inside a block-comment or one block-comment is inside or partially
* inside the selection we uncomment; otherwise we comment out.
* Commenting out adds the prefix before the selection and the suffix after.
* Uncommenting removes them.
*
* If slashComment is true and the start or end of the selection is inside a line-comment it
* will try to do a line uncomment if is not actually inside a bigger block comment and all
* the lines in the selection are line-commented.
*
* @param {!Editor} editor
* @param {!string} prefix, e.g. "<!--"
* @param {!string} suffix, e.g. "-->"
* @param {?Array.<string>} linePrefixes, e.g. ["//"]
*/
function blockCommentPrefixSuffix(editor, prefix, suffix, linePrefixes) {
var doc = editor.document,
sel = editor.getSelection(),
ctx = TokenUtils.getInitialContext(editor._codeMirror, {line: sel.start.line, ch: sel.start.ch}),
startCtx = TokenUtils.getInitialContext(editor._codeMirror, {line: sel.start.line, ch: sel.start.ch}),
endCtx = TokenUtils.getInitialContext(editor._codeMirror, {line: sel.end.line, ch: sel.end.ch}),
prefixExp = new RegExp("^" + StringUtils.regexEscape(prefix), "g"),
suffixExp = new RegExp(StringUtils.regexEscape(suffix) + "$", "g"),
lineExp = linePrefixes ? _createLineExpressions(linePrefixes) : null,
prefixPos = null,
suffixPos = null,
canComment = false,
invalidComment = false,
lineUncomment = false,
newSelection;
var result, text, line;
// Move the context to the first non-empty token.
if (!ctx.token.className && ctx.token.string.trim().length === 0) {
result = TokenUtils.moveSkippingWhitespace(TokenUtils.moveNextToken, ctx);
}
// Check if we should just do a line uncomment (if all lines in the selection are commented).
if (lineExp && (_matchExpressions(ctx.token.string, lineExp) || _matchExpressions(endCtx.token.string, lineExp))) {
var startCtxIndex = editor.indexFromPos({line: ctx.pos.line, ch: ctx.token.start});
var endCtxIndex = editor.indexFromPos({line: endCtx.pos.line, ch: endCtx.token.start + endCtx.token.string.length});
// Find if we aren't actually inside a block-comment
result = true;
while (result && _matchExpressions(ctx.token.string, lineExp)) {
result = TokenUtils.moveSkippingWhitespace(TokenUtils.movePrevToken, ctx);
}
// If we aren't in a block-comment.
if (!result || ctx.token.className !== "comment" || ctx.token.string.match(suffixExp)) {
// Is a range of text selected? (vs just an insertion pt)
var hasSelection = (sel.start.line !== sel.end.line) || (sel.start.ch !== sel.end.ch);
// In full-line selection, cursor pos is start of next line - but don't want to modify that line
var endLine = sel.end.line;
if (sel.end.ch === 0 && hasSelection) {
endLine--;
}
// Find if all the lines are line-commented.
if (!_containsUncommented(editor, sel.start.line, endLine, linePrefixes)) {
lineUncomment = true;
// Block-comment in all the other cases
} else {
canComment = true;
}
} else {
prefixPos = _findCommentStart(startCtx, prefixExp);
suffixPos = _findCommentEnd(startCtx, suffixExp, suffix.length);
}
// If we are in a selection starting and ending in invalid tokens and with no content (not considering spaces),
// find if we are inside a block-comment.
} else if (startCtx.token.className === null && endCtx.token.className === null &&
!editor.posWithinRange(ctx.pos, startCtx.pos, endCtx.pos)) {
result = TokenUtils.moveSkippingWhitespace(TokenUtils.moveNextToken, startCtx);
// We found a comment, find the start and end and check if the selection is inside the block-comment.
if (startCtx.token.className === "comment") {
prefixPos = _findCommentStart(startCtx, prefixExp);
suffixPos = _findCommentEnd(startCtx, suffixExp, suffix.length);
if (prefixPos !== null && suffix !== null && !editor.posWithinRange(sel.start, prefixPos, suffixPos)) {
canComment = true;
}
} else {
canComment = true;
}
// If the start is inside a comment, find the prefix and suffix positions.
} else if (ctx.token.className === "comment") {
prefixPos = _findCommentStart(ctx, prefixExp);
suffixPos = _findCommentEnd(ctx, suffixExp, suffix.length);
// If not try to find the first comment inside the selection.
} else {
result = _findNextBlockComment(ctx, sel.end, prefixExp);
// If nothing was found is ok to comment.
if (!result) {
canComment = true;
} else {
if (!ctx.token.string.match(prefixExp)) {
prefixPos = _findCommentStart(ctx, prefixExp);
} else {
prefixPos = {line: ctx.pos.line, ch: ctx.token.start};
}
suffixPos = _findCommentEnd(ctx, suffixExp, suffix.length);
}
}
// Search if there is another comment in the selection. Do nothing if there is one.
if (!canComment && !invalidComment && !lineUncomment && suffixPos) {
var start = {line: suffixPos.line, ch: suffixPos.ch + suffix.length + 1};
if (editor.posWithinRange(start, sel.start, sel.end)) {
// Start searching at the next token, if there is one.
result = TokenUtils.moveSkippingWhitespace(TokenUtils.moveNextToken, ctx) &&
_findNextBlockComment(ctx, sel.end, prefixExp);
if (result) {
invalidComment = true;
}
}
}
// Make the edit
if (invalidComment) {
return;
} else if (lineUncomment) {
lineCommentPrefix(editor, linePrefixes);
} else {
doc.batchOperation(function () {
if (canComment) {
// Comment out - add the suffix to the start and the prefix to the end.
var completeLineSel = sel.start.ch === 0 && sel.end.ch === 0 && sel.start.line < sel.end.line;
if (completeLineSel) {
doc.replaceRange(suffix + "\n", sel.end);
doc.replaceRange(prefix + "\n", sel.start);
} else {
doc.replaceRange(suffix, sel.end);
doc.replaceRange(prefix, sel.start);
}
// Correct the selection.
if (completeLineSel) {
newSelection = {start: {line: sel.start.line + 1, ch: 0}, end: {line: sel.end.line + 1, ch: 0}};
} else {
var newSelStart = {line: sel.start.line, ch: sel.start.ch + prefix.length};
if (sel.start.line === sel.end.line) {
newSelection = {start: newSelStart, end: {line: sel.end.line, ch: sel.end.ch + prefix.length}};
} else {
newSelection = {start: newSelStart, end: {line: sel.end.line, ch: sel.end.ch}};
}
}
// Uncomment - remove prefix and suffix.
} else {
// Find if the prefix and suffix are at the ch 0 and if they are the only thing in the line.
// If both are found we assume that a complete line selection comment added new lines, so we remove them.
var prefixAtStart = false, suffixAtStart = false;
line = doc.getLine(prefixPos.line).trim();
prefixAtStart = prefixPos.ch === 0 && prefix.length === line.length;
if (suffixPos) {
line = doc.getLine(suffixPos.line).trim();
suffixAtStart = suffixPos.ch === 0 && suffix.length === line.length;
}
// Remove the suffix if there is one
if (suffixPos) {
if (prefixAtStart && suffixAtStart) {
doc.replaceRange("", suffixPos, {line: suffixPos.line + 1, ch: 0});
} else {
doc.replaceRange("", suffixPos, {line: suffixPos.line, ch: suffixPos.ch + suffix.length});
}
}
// Remove the prefix
if (prefixAtStart && suffixAtStart) {
doc.replaceRange("", prefixPos, {line: prefixPos.line + 1, ch: 0});
} else {
doc.replaceRange("", prefixPos, {line: prefixPos.line, ch: prefixPos.ch + prefix.length});
}
}
});
// Update the selection after the document batch so it's not blown away on resynchronization
// if this editor is not the master editor.
if (newSelection) {
editor.setSelection(newSelection.start, newSelection.end);
}
}
}
/**
* Add or remove block-comment tokens to the selection, preserving selection
* and cursor position. Applies to the currently focused Editor.
*
* The implementation uses blockCommentPrefixSuffix, with the exception of the case where
* there is no selection on a uncommented and not empty line. In this case the whole lines gets
* commented in a block-comment.
*
* @param {!Editor} editor
* @param {!String} prefix
* @param {!String} suffix
*/
function lineCommentPrefixSuffix(editor, prefix, suffix) {
var sel = editor.getSelection(),
selStart = sel.start,
selEnd = sel.end,
prefixExp = new RegExp("^" + StringUtils.regexEscape(prefix), "g"),
isLineSelection = sel.start.ch === 0 && sel.end.ch === 0 && sel.start.line !== sel.end.line,
isMultipleLine = sel.start.line !== sel.end.line,
lineLength = editor.document.getLine(sel.start.line).length;
// Line selections already behave like we want to
if (!isLineSelection) {
// For a multiple line selection transform it to a multiple whole line selection
if (isMultipleLine) {
selStart = {line: sel.start.line, ch: 0};
selEnd = {line: sel.end.line + 1, ch: 0};
// For one line selections, just start at column 0 and end at the end of the line
} else {
selStart = {line: sel.start.line, ch: 0};
selEnd = {line: sel.end.line, ch: lineLength};
}
}
// If the selection includes a comment or is already a line selection, delegate to Block-Comment
var ctx = TokenUtils.getInitialContext(editor._codeMirror, {line: selStart.line, ch: selStart.ch});
var result = TokenUtils.moveSkippingWhitespace(TokenUtils.moveNextToken, ctx);
var className = ctx.token.className;
result = result && _findNextBlockComment(ctx, selEnd, prefixExp);
if (className === "comment" || result || isLineSelection) {
blockCommentPrefixSuffix(editor, prefix, suffix);
} else {
// Set the new selection and comment it
editor.setSelection(selStart, selEnd);
blockCommentPrefixSuffix(editor, prefix, suffix);
// Restore the old selection taking into account the prefix change
if (isMultipleLine) {
sel.start.line++;
sel.end.line++;
} else {
sel.start.ch += prefix.length;
sel.end.ch += prefix.length;
}
editor.setSelection(sel.start, sel.end);
}
}
/**
* Invokes a language-specific block-comment/uncomment handler
* @param {?Editor} editor If unspecified, applies to the currently focused editor
*/
function blockComment(editor) {
editor = editor || EditorManager.getFocusedEditor();
if (!editor) {
return;
}
var language = editor.getLanguageForSelection();
if (language.hasBlockCommentSyntax()) {
// getLineCommentPrefix returns null if no line comment syntax is defined
blockCommentPrefixSuffix(editor, language.getBlockCommentPrefix(), language.getBlockCommentSuffix(), language.getLineCommentPrefix());
}
}
/**
* Invokes a language-specific line-comment/uncomment handler
* @param {?Editor} editor If unspecified, applies to the currently focused editor
*/
function lineComment(editor) {
editor = editor || EditorManager.getFocusedEditor();
if (!editor) {
return;
}
var language = editor.getLanguageForSelection();
if (language.hasLineCommentSyntax()) {
lineCommentPrefix(editor, language.getLineCommentPrefix());
} else if (language.hasBlockCommentSyntax()) {
lineCommentPrefixSuffix(editor, language.getBlockCommentPrefix(), language.getBlockCommentSuffix());
}
}
/**
* Duplicates the selected text, or current line if no selection. The cursor/selection is left
* on the second copy.
*/
function duplicateText(editor) {
editor = editor || EditorManager.getFocusedEditor();
if (!editor) {
return;
}
var sel = editor.getSelection(),
hasSelection = (sel.start.line !== sel.end.line) || (sel.start.ch !== sel.end.ch),
delimiter = "";
if (!hasSelection) {
sel.start.ch = 0;
sel.end = {line: sel.start.line + 1, ch: 0};
if (sel.end.line === editor.lineCount()) {
delimiter = "\n";
}
}
// Make the edit
var doc = editor.document;
var selectedText = doc.getRange(sel.start, sel.end) + delimiter;
doc.replaceRange(selectedText, sel.start);
}
/**
* Deletes the current line if there is no selection or the lines for the selection
* (removing the end of line too)
*/
function deleteCurrentLines(editor) {
editor = editor || EditorManager.getFocusedEditor();
if (!editor) {
return;
}
var from,
to,
sel = editor.getSelection(),
doc = editor.document;
from = {line: sel.start.line, ch: 0};
to = {line: sel.end.line + 1, ch: 0};
if (to.line === editor.getLastVisibleLine() + 1) {
// Instead of deleting the newline after the last line, delete the newline
// before the first line--unless this is the entire visible content of the editor,
// in which case just delete the line content.
if (from.line > editor.getFirstVisibleLine()) {
from.line -= 1;
from.ch = doc.getLine(from.line).length;
}
to.line -= 1;
to.ch = doc.getLine(to.line).length;
}
doc.replaceRange("", from, to);
}
/**
* Moves the selected text, or current line if no selection. The cursor/selection
* moves with the line/lines.
* @param {Editor} editor - target editor
* @param {Number} direction - direction of the move (-1,+1) => (Up,Down)
*/
function moveLine(editor, direction) {
editor = editor || EditorManager.getFocusedEditor();
if (!editor) {
return;
}
var doc = editor.document,
sel = editor.getSelection(),
originalSel = editor.getSelection(),
hasSelection = (sel.start.line !== sel.end.line) || (sel.start.ch !== sel.end.ch),
inlineWidget = EditorManager.getFocusedInlineWidget(),
firstLine = editor.getFirstVisibleLine(),
lastLine = editor.getLastVisibleLine();
sel.start.ch = 0;
// The end of the selection becomes the start of the next line, if it isn't already
if (!hasSelection || sel.end.ch !== 0) {
sel.end = {line: sel.end.line + 1, ch: 0};
}
// Make the move
switch (direction) {
case DIRECTION_UP:
if (sel.start.line !== firstLine) {
doc.batchOperation(function () {
var prevText = doc.getRange({ line: sel.start.line - 1, ch: 0 }, sel.start);
if (sel.end.line === lastLine + 1) {
prevText = "\n" + prevText.substring(0, prevText.length - 1);
}
doc.replaceRange("", { line: sel.start.line - 1, ch: 0 }, sel.start);
doc.replaceRange(prevText, { line: sel.end.line - 1, ch: 0 });
// Make sure CodeMirror hasn't expanded the selection to include
// the line we inserted below.
originalSel.start.line--;
originalSel.end.line--;
});
// Update the selection after the document batch so it's not blown away on resynchronization
// if this editor is not the master editor.
editor.setSelection(originalSel.start, originalSel.end);
}
break;
case DIRECTION_DOWN:
if (sel.end.line <= lastLine + (inlineWidget ? -1 : 1)) {
doc.batchOperation(function () {
var nextText = doc.getRange(sel.end, { line: sel.end.line + 1, ch: 0 });
var deletionStart = sel.end;
if (!inlineWidget && sel.end.line === lastLine) {
nextText += "\n";
deletionStart = { line: sel.end.line - 1, ch: doc.getLine(sel.end.line - 1).length };
}
doc.replaceRange("", deletionStart, { line: sel.end.line + 1, ch: 0 });
doc.replaceRange(nextText, { line: sel.start.line, ch: 0 });
});
}
break;
}
}
/**
* Moves the selected text, or current line if no selection, one line up. The cursor/selection
* moves with the line/lines.
*/
function moveLineUp(editor) {
moveLine(editor, DIRECTION_UP);
}
/**
* Moves the selected text, or current line if no selection, one line down. The cursor/selection
* moves with the line/lines.
*/
function moveLineDown(editor) {
moveLine(editor, DIRECTION_DOWN);
}
/**
* Indent a line of text if no selection. Otherwise, indent all lines in selection.
*/
function indentText() {
var editor = EditorManager.getFocusedEditor();
if (!editor) {
return;
}
editor._codeMirror.execCommand("indentMore");
}
/**
* Unindent a line of text if no selection. Otherwise, unindent all lines in selection.
*/
function unidentText() {
var editor = EditorManager.getFocusedEditor();
if (!editor) {
return;
}
editor._codeMirror.execCommand("indentLess");
}
function selectLine(editor) {
editor = editor || EditorManager.getFocusedEditor();
if (editor) {
var sel = editor.getSelection();
var from = {line: sel.start.line, ch: 0};
var to = {line: sel.end.line + 1, ch: 0};
if (to.line === editor.getLastVisibleLine() + 1) {
// Last line: select to end of line instead of start of (hidden/nonexistent) following line,
// which due to how CM clips coords would only work some of the time
to.line -= 1;
to.ch = editor.document.getLine(to.line).length;
}
editor.setSelection(from, to);
}
}
function handleUndoRedo(operation) {
var editor = EditorManager.getFocusedEditor();
var result = new $.Deferred();
if (editor) {
editor[operation]();
result.resolve();
} else {
result.reject();
}
return result.promise();
}
function handleUndo() {
return handleUndoRedo("undo");
}
function handleRedo() {
return handleUndoRedo("redo");
}
/**
* Special command handler that just ignores the command. This is used for Cut, Copy, and Paste.
* These menu items are handled natively, but need to be registered in our JavaScript code so the
* menu items can be created.
*/
function ignoreCommand() {
// Do nothing. The shell will call the native handler for the command.
return (new $.Deferred()).reject().promise();
}
function _handleSelectAll() {
var result = new $.Deferred(),
editor = EditorManager.getFocusedEditor();
if (editor) {
editor.selectAllNoScroll();
result.resolve();
} else {
result.reject(); // command not handled
}
return result.promise();
}
// Register commands
CommandManager.register(Strings.CMD_INDENT, Commands.EDIT_INDENT, indentText);
CommandManager.register(Strings.CMD_UNINDENT, Commands.EDIT_UNINDENT, unidentText);
CommandManager.register(Strings.CMD_COMMENT, Commands.EDIT_LINE_COMMENT, lineComment);
CommandManager.register(Strings.CMD_BLOCK_COMMENT, Commands.EDIT_BLOCK_COMMENT, blockComment);
CommandManager.register(Strings.CMD_DUPLICATE, Commands.EDIT_DUPLICATE, duplicateText);
CommandManager.register(Strings.CMD_DELETE_LINES, Commands.EDIT_DELETE_LINES, deleteCurrentLines);
CommandManager.register(Strings.CMD_LINE_UP, Commands.EDIT_LINE_UP, moveLineUp);
CommandManager.register(Strings.CMD_LINE_DOWN, Commands.EDIT_LINE_DOWN, moveLineDown);
CommandManager.register(Strings.CMD_SELECT_LINE, Commands.EDIT_SELECT_LINE, selectLine);
CommandManager.register(Strings.CMD_UNDO, Commands.EDIT_UNDO, handleUndo);
CommandManager.register(Strings.CMD_REDO, Commands.EDIT_REDO, handleRedo);
CommandManager.register(Strings.CMD_CUT, Commands.EDIT_CUT, ignoreCommand);
CommandManager.register(Strings.CMD_COPY, Commands.EDIT_COPY, ignoreCommand);
CommandManager.register(Strings.CMD_PASTE, Commands.EDIT_PASTE, ignoreCommand);
CommandManager.register(Strings.CMD_SELECT_ALL, Commands.EDIT_SELECT_ALL, _handleSelectAll);
});