-
Notifications
You must be signed in to change notification settings - Fork 68
/
Copy pathcode_controller.dart
995 lines (824 loc) · 27.4 KB
/
code_controller.dart
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
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
// ignore_for_file: parameter_assignments
import 'dart:async';
import 'package:collection/collection.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:highlight/highlight_core.dart';
import 'package:meta/meta.dart';
import '../../flutter_code_editor.dart';
import '../autocomplete/autocompleter.dart';
import '../code/code_edit_result.dart';
import '../code/key_event.dart';
import '../code_modifiers/insertion.dart';
import '../history/code_history_controller.dart';
import '../history/code_history_record.dart';
import '../search/controller.dart';
import '../search/result.dart';
import '../search/search_navigation_controller.dart';
import '../search/settings_controller.dart';
import '../single_line_comments/parser/single_line_comments.dart';
import '../wip/autocomplete/popup_controller.dart';
import 'actions/comment_uncomment.dart';
import 'actions/copy.dart';
import 'actions/dismiss.dart';
import 'actions/enter_key.dart';
import 'actions/indent.dart';
import 'actions/outdent.dart';
import 'actions/redo.dart';
import 'actions/search.dart';
import 'actions/undo.dart';
import 'search_result_highlighted_builder.dart';
import 'span_builder.dart';
class CodeController extends TextEditingController {
Mode? _language;
/// A highlight language to parse the text with
///
/// Setting a language will change the analyzer to [DefaultLocalAnalyzer].
Mode? get language => _language;
set language(Mode? language) {
setLanguage(language, analyzer: const DefaultLocalAnalyzer());
}
/// `CodeController` uses [analyzer] to generate issues
/// that are displayed in gutter widget.
///
/// Calls [AbstractAnalyzer.analyze] after change with 500ms debounce.
AbstractAnalyzer get analyzer => _analyzer;
AbstractAnalyzer _analyzer;
set analyzer(AbstractAnalyzer analyzer) {
if (_analyzer == analyzer) {
return;
}
_analyzer = analyzer;
unawaited(analyzeCode());
}
AnalysisResult analysisResult;
String _lastAnalyzedText = '';
Timer? _debounce;
final AbstractNamedSectionParser? namedSectionParser;
Set<String> _readOnlySectionNames;
/// A map of specific regexes to style
final Map<String, TextStyle>? patternMap;
/// A map of specific keywords to style
final Map<String, TextStyle>? stringMap;
/// Common editor params such as the size of a tab in spaces
///
/// Will be exposed to all [modifiers]
final EditorParams params;
/// A list of code modifiers
/// to dynamically update the code upon certain keystrokes.
final List<CodeModifier> modifiers;
final bool _isTabReplacementEnabled;
/* Computed members */
String _languageId = '';
///Contains names of named sections, those will be visible for user.
///If it is not empty, all another code except specified will be hidden.
Set<String> _visibleSectionNames = {};
/// Makes the text un-editable, but allows to set the full text.
/// Focusing and moving the selection inside of a [CodeField] will
/// still be possible.
final bool readOnly;
String get languageId => _languageId;
Code _code;
final _styleList = <TextStyle>[];
final _modifierMap = <String, CodeModifier>{};
RegExp? _styleRegExp;
late PopupController popupController;
final autocompleter = Autocompleter();
late final historyController = CodeHistoryController(codeController: this);
@internal
late final searchController = CodeSearchController(codeController: this);
SearchSettingsController get _searchSettingsController =>
searchController.settingsController;
SearchNavigationController get _searchNavigationController =>
searchController.navigationController;
@internal
SearchResult fullSearchResult = SearchResult.empty;
/// The last [TextSpan] returned from [buildTextSpan].
///
/// This can be used in tests to make sure that the updated text was actually
/// requested by the widget and thus notifications are done right.
@visibleForTesting
TextSpan? lastTextSpan;
late final actions = <Type, Action<Intent>>{
CommentUncommentIntent: CommentUncommentAction(controller: this),
CopySelectionTextIntent: CopyAction(controller: this),
IndentIntent: IndentIntentAction(controller: this),
OutdentIntent: OutdentIntentAction(controller: this),
RedoTextIntent: RedoAction(controller: this),
UndoTextIntent: UndoAction(controller: this),
SearchIntent: SearchAction(controller: this),
DismissIntent: CustomDismissAction(controller: this),
EnterKeyIntent: EnterKeyAction(controller: this),
};
static const defaultCodeModifiers = [
IndentModifier(),
CloseBlockModifier(),
TabModifier(),
InsertionCodeModifier.backticks,
InsertionCodeModifier.braces,
InsertionCodeModifier.brackets,
InsertionCodeModifier.doubleQuotes,
InsertionCodeModifier.parentheses,
InsertionCodeModifier.singleQuotes,
];
CodeController({
String? text,
Mode? language,
AbstractAnalyzer analyzer = const DefaultLocalAnalyzer(),
this.namedSectionParser,
Set<String> readOnlySectionNames = const {},
Set<String> visibleSectionNames = const {},
@Deprecated('Use CodeTheme widget to provide theme to CodeField.')
Map<String, TextStyle>? theme,
this.analysisResult = const AnalysisResult(issues: []),
this.patternMap,
this.readOnly = false,
this.stringMap,
this.params = const EditorParams(),
this.modifiers = defaultCodeModifiers,
}) : _analyzer = analyzer,
_readOnlySectionNames = readOnlySectionNames,
_code = Code.empty,
_isTabReplacementEnabled = modifiers.any((e) => e is TabModifier) {
setLanguage(language, analyzer: analyzer);
this.visibleSectionNames = visibleSectionNames;
_code = _createCode(text ?? '');
fullText = text ?? '';
addListener(_scheduleAnalysis);
addListener(_updateSearchResult);
_searchSettingsController.addListener(_updateSearchResult);
// This listener is called when search controller notifies about
// showing or hiding the search popup.
searchController.addListener(_updateSearchResult);
// Create modifier map
for (final el in modifiers) {
_modifierMap[el.char] = el;
}
// Build styleRegExp
final patternList = <String>[];
if (stringMap != null) {
patternList.addAll(stringMap!.keys.map((e) => r'(\b' + e + r'\b)'));
_styleList.addAll(stringMap!.values);
}
if (patternMap != null) {
patternList.addAll(patternMap!.keys.map((e) => '($e)'));
_styleList.addAll(patternMap!.values);
}
_styleRegExp = RegExp(patternList.join('|'), multiLine: true);
popupController = PopupController(onCompletionSelected: insertSelectedWord);
unawaited(analyzeCode());
}
void _updateSearchResult() {
final result = searchController.search(
code,
settings: _searchSettingsController.value,
);
if (result == fullSearchResult) {
return;
}
fullSearchResult = result;
notifyListeners();
}
void _scheduleAnalysis() {
_debounce?.cancel();
if (_lastAnalyzedText == _code.text) {
// If the last analyzed code is the same as current code
// we don't need to analyze it again.
return;
}
_debounce = Timer(const Duration(milliseconds: 500), () async {
await analyzeCode();
});
}
Future<void> analyzeCode() async {
final codeSentToAnalysis = _code;
final result = await _analyzer.analyze(codeSentToAnalysis);
if (_code.text != codeSentToAnalysis.text) {
// If the code has been changed before we got analysis result, discard it.
// This happens on request race condition.
return;
}
analysisResult = result;
_lastAnalyzedText = codeSentToAnalysis.text;
notifyListeners();
}
void setLanguage(
Mode? language, {
required AbstractAnalyzer analyzer,
}) {
if (language == _language) {
return;
}
if (language != null) {
_languageId = language.hashCode.toString();
highlight.registerLanguage(_languageId, language);
}
_language = language;
autocompleter.mode = language;
_updateCode(_code.text);
this.analyzer = analyzer;
notifyListeners();
}
/// Sets a specific cursor position in the text
void setCursor(int offset) {
selection = TextSelection.collapsed(offset: offset);
}
/// Replaces the current [selection] by [str]
void insertStr(String str) {
final sel = selection;
text = text.replaceRange(selection.start, selection.end, str);
final len = str.length;
selection = sel.copyWith(
baseOffset: sel.start + len,
extentOffset: sel.start + len,
);
}
/// Remove the char just before the cursor or the selection
void removeChar() {
if (selection.start < 1) {
return;
}
final sel = selection;
text = text.replaceRange(selection.start - 1, selection.start, '');
selection = sel.copyWith(
baseOffset: sel.start - 1,
extentOffset: sel.start - 1,
);
}
/// Remove the selected text
void removeSelection() {
final sel = selection;
text = text.replaceRange(selection.start, selection.end, '');
selection = sel.copyWith(
baseOffset: sel.start,
extentOffset: sel.start,
);
}
/// Remove the selection or last char if the selection is empty
void backspace() {
if (selection.start < selection.end) {
removeSelection();
} else {
removeChar();
}
}
KeyEventResult onKey(KeyEvent event) {
if (event is KeyDownEvent || event is KeyRepeatEvent) {
return _onKeyDownRepeat(event);
}
return KeyEventResult.ignored; // The framework will handle.
}
KeyEventResult _onKeyDownRepeat(KeyEvent event) {
if (event.isCtrlF(HardwareKeyboard.instance.logicalKeysPressed)) {
showSearch();
return KeyEventResult.handled;
}
if (popupController.shouldShow) {
if (event.logicalKey == LogicalKeyboardKey.arrowUp) {
popupController.scrollByArrow(ScrollDirection.up);
return KeyEventResult.handled;
}
if (event.logicalKey == LogicalKeyboardKey.arrowDown) {
popupController.scrollByArrow(ScrollDirection.down);
return KeyEventResult.handled;
}
}
return KeyEventResult.ignored; // The framework will handle.
}
void onEnterKeyAction() {
if (popupController.shouldShow) {
insertSelectedWord();
return;
}
final currentMatchIndex =
_searchNavigationController.value.currentMatchIndex;
if (searchController.shouldShow && currentMatchIndex != null) {
final fullSelection = code.hiddenRanges.recoverSelection(selection);
final currentMatch = fullSearchResult.matches[currentMatchIndex];
if (fullSelection.start == currentMatch.start &&
fullSelection.end == currentMatch.end) {
_searchNavigationController.moveNext();
return;
}
}
insertStr('\n');
}
/// Inserts the word selected from the list of completions
void insertSelectedWord() {
final previousSelection = selection;
final selectedWord = popupController.getSelectedWord();
final startPosition = value.wordAtCursorStart;
if (startPosition != null) {
final replacedText = text.replaceRange(
startPosition,
selection.baseOffset,
selectedWord,
);
final adjustedSelection = previousSelection.copyWith(
baseOffset: startPosition + selectedWord.length,
extentOffset: startPosition + selectedWord.length,
);
value = TextEditingValue(
text: replacedText,
selection: adjustedSelection,
);
}
popupController.hide();
}
String get fullText => _code.text;
set fullText(String fullText) {
_updateCodeIfChanged(_replaceTabsWithSpacesIfNeeded(fullText));
super.value = TextEditingValue(text: _code.visibleText);
}
int? _insertedLoc(String a, String b) {
final sel = selection;
if (a.length + 1 != b.length || sel.start != sel.end || sel.start == -1) {
return null;
}
return sel.start;
}
@override
set value(TextEditingValue newValue) {
final hasTextChanged = newValue.text != super.value.text;
final hasSelectionChanged = newValue.selection != super.value.selection;
if (!hasTextChanged && !hasSelectionChanged) {
return;
}
if (hasTextChanged) {
final loc = _insertedLoc(text, newValue.text);
if (loc != null) {
final char = newValue.text[loc];
final modifier = _modifierMap[char];
final val = modifier?.updateString(text, selection, params);
if (val != null) {
// Update newValue
newValue = newValue.copyWith(
text: val.text,
selection: val.selection,
);
}
}
if (_isTabReplacementEnabled) {
newValue = newValue.tabsToSpaces(params.tabSpaces);
}
final editResult = _getEditResultNotBreakingReadOnly(newValue);
if (editResult == null) {
return;
}
final selectionSnapshot =
code.hiddenRanges.recoverSelection(newValue.selection);
_updateCodeIfChanged(editResult.fullTextAfter);
if (newValue.text != _code.visibleText) {
if (newValue.text.length > _code.visibleText.length) {
// Manually typed in a text that has become a hidden range.
newValue = newValue.replacedText(_code.visibleText);
} else {
// Some folded block is unfolded.
newValue = TextEditingValue(
text: _code.visibleText,
selection: _code.hiddenRanges.cutSelection(selectionSnapshot),
);
}
}
// Uncomment this to see the hidden text in the console
// as you change the visible text.
//print('\n\n${_code.text}');
}
historyController.beforeCodeControllerValueChanged(
code: _code,
selection: newValue.selection,
isTextChanging: hasTextChanged,
);
super.value = newValue;
if (hasTextChanged) {
autocompleter.blacklist = [newValue.wordAtCursor ?? ''];
autocompleter.setText(this, text);
unawaited(generateSuggestions());
} else if (hasSelectionChanged) {
popupController.hide();
}
}
void applyHistoryRecord(CodeHistoryRecord record) {
_code = record.code.foldedAs(_code);
final fullSelection =
record.code.hiddenRanges.recoverSelection(record.selection);
final cutSelection = _code.hiddenRanges.cutSelection(fullSelection);
super.value = TextEditingValue(
text: code.visibleText,
selection: cutSelection,
);
}
void outdentSelection() {
final tabSpaces = params.tabSpaces;
if (selection.start == -1 || selection.end == -1) {
return;
}
modifySelectedLines((line) {
if (line == '\n') {
return line;
}
if (line.length < tabSpaces) {
return line.trimLeft();
}
final subStr = line.substring(0, tabSpaces);
if (subStr == ' ' * tabSpaces) {
return line.substring(tabSpaces, line.length);
}
return line.trimLeft();
});
}
void indentSelection() {
final tabSpaces = params.tabSpaces;
final tab = ' ' * tabSpaces;
final lines = _code.lines.lines;
if (selection.start == -1 || selection.end == -1) {
return;
}
if (selection.isCollapsed) {
final fullPosition = _code.hiddenRanges.recoverPosition(
selection.start,
placeHiddenRanges: TextAffinity.downstream,
);
final lineIndex = _code.lines.characterIndexToLineIndex(fullPosition);
final columnIndex = fullPosition - lines[lineIndex].textRange.start;
final insert = ' ' * (tabSpaces - (columnIndex % tabSpaces));
value = value.replaced(selection, insert);
return;
}
modifySelectedLines((line) {
if (line == '\n') {
return line;
}
return tab + line;
});
}
/// Comments out or uncomments the currently selected lines.
///
/// Doesn't affect empty lines.
///
/// If any of the selected lines is not a single line comment:
/// adds one level of single line comment to every selected line.
///
/// If all of the selected lines are single line comments:
/// removes one level of single line comment from every selected line.
///
/// When commenting out, adds `// ` or `# ` (or another symbol depending on a language) with a space after.
/// Removes these spaces on uncommenting.
/// (if there are no spaces just removes the comments)
///
/// The method doesn't account for multiline comments
/// and treats them as a normal text (not a comment).
void commentOutOrUncommentSelection() {
if (_anySelectedLineUncommented()) {
_commentOutSelectedLines();
} else {
_uncommentSelectedLines();
}
}
bool _anySelectedLineUncommented() {
return _anySelectedLine((line) {
for (final commentType in SingleLineComments.byMode[language] ?? []) {
if (line.trimLeft().startsWith(commentType) ||
line.hasOnlyWhitespaces()) {
return false;
}
}
return true;
});
}
/// Whether any of the selected lines meets the condition in the callback.
bool _anySelectedLine(bool Function(String line) callback) {
if (selection.start == -1 || selection.end == -1) {
return false;
}
final selectedLinesRange = getSelectedLineRange();
for (int i = selectedLinesRange.start; i < selectedLinesRange.end; i++) {
final currentLineMatchesCondition = callback(_code.lines.lines[i].text);
if (currentLineMatchesCondition) {
return true;
}
}
return false;
}
void _commentOutSelectedLines() {
final sequence = SingleLineComments.byMode[language]?.first;
if (sequence == null) {
return;
}
modifySelectedLines((line) {
if (line.hasOnlyWhitespaces()) {
return line;
}
return line.replaceRange(
0,
0,
'$sequence ',
);
});
}
void _uncommentSelectedLines() {
modifySelectedLines((line) {
if (line.hasOnlyWhitespaces()) {
return line;
}
for (final sequence
in SingleLineComments.byMode[language] ?? <String>[]) {
// If there is a space after a sequence
// we should remove it with the sequence.
if (line.trim().startsWith('$sequence ')) {
return line.replaceFirst('$sequence ', '');
}
// If there is no space after a sequence
// we should remove the sequence.
if (line.trim().startsWith(sequence)) {
return line.replaceFirst(sequence, '');
}
}
// If line is not commented just return it.
return line;
});
}
/// Filters the lines that have at least one character selected.
///
/// IMPORTANT: this method also changes the selection to be:
/// start: start of the first selected line
/// end: end of the last line
///
/// Folded blocks are considered to be selected
/// if they are located between start and end of a selection.
///
/// [modifierCallback] - transformation function that modifies the line.
/// `line` in the callback contains '\n' symbol at the end, except for the last line of the document.
// TODO(yescorp): need to preserve folding..
void modifySelectedLines(
String Function(String line) modifierCallback,
) {
if (readOnly) {
return;
}
if (selection.start == -1 || selection.end == -1) {
return;
}
final lineRange = getSelectedLineRange();
// Apply modification to the selected lines.
final modifiedLinesBuffer = StringBuffer();
for (int i = lineRange.start; i < lineRange.end; i++) {
// Cancel modification entirely if any of the lines is readOnly.
if (_code.lines.lines[i].isReadOnly) {
return;
}
final modifiedString = modifierCallback(_code.lines.lines[i].text);
modifiedLinesBuffer.write(modifiedString);
}
final modifiedLinesString = modifiedLinesBuffer.toString();
final firstLineStart = _code.lines.lines[lineRange.start].textRange.start;
final lastLineEnd = _code.lines.lines[lineRange.end - 1].textRange.end;
// Replace selected lines with modified ones.
final finalFullText = _code.text.replaceRange(
firstLineStart,
lastLineEnd,
modifiedLinesString,
);
_updateCodeIfChanged(finalFullText);
final finalFullSelection = TextSelection(
baseOffset: firstLineStart,
extentOffset: firstLineStart + modifiedLinesString.length,
);
final finalVisibleSelection =
_code.hiddenRanges.cutSelection(finalFullSelection);
// TODO(yescorp): move to the listener both here and in `set value`
// or come up with a different approach
historyController.beforeCodeControllerValueChanged(
code: _code,
selection: finalVisibleSelection,
isTextChanging: true,
);
super.value = TextEditingValue(
text: _code.visibleText,
selection: finalVisibleSelection,
);
}
TextRange getSelectedLineRange() {
final firstChar = _code.hiddenRanges.recoverPosition(
selection.start,
placeHiddenRanges: TextAffinity.downstream,
);
final lastChar = _code.hiddenRanges.recoverPosition(
// To avoid including the next line if `\n` is selected.
selection.isCollapsed ? selection.end : selection.end - 1,
placeHiddenRanges: TextAffinity.downstream,
);
final firstLineIndex = _code.lines.characterIndexToLineIndex(firstChar);
final lastLineIndex = _code.lines.characterIndexToLineIndex(lastChar);
return TextRange(
start: firstLineIndex,
end: lastLineIndex + 1,
);
}
Code get code => _code;
CodeEditResult? _getEditResultNotBreakingReadOnly(TextEditingValue newValue) {
if (readOnly) {
return null;
}
final editResult = _code.getEditResult(value.selection, newValue);
if (!_code.isReadOnlyInLineRange(editResult.linesChanged)) {
return editResult;
}
return null;
}
void _updateCodeIfChanged(String text) {
if (text != _code.text) {
_updateCode(text);
}
}
void _updateCode(String text) {
final newCode = _createCode(text);
_code = newCode.foldedAs(_code);
}
Code _createCode(String text) {
return Code(
text: text,
language: language,
highlighted: highlight.parse(text, language: _languageId),
namedSectionParser: namedSectionParser,
readOnlySectionNames: _readOnlySectionNames,
visibleSectionNames: _visibleSectionNames,
);
}
String _replaceTabsWithSpacesIfNeeded(String text) {
if (modifiers.contains(const TabModifier())) {
return text.replaceAll('\t', ' ' * params.tabSpaces);
}
return text;
}
Future<void> generateSuggestions() async {
final prefix = value.wordToCursor;
if (prefix == null) {
popupController.hide();
return;
}
final suggestions =
(await autocompleter.getSuggestions(prefix)).toList(growable: false);
if (suggestions.isNotEmpty) {
popupController.show(suggestions);
} else {
popupController.hide();
}
}
void foldAt(int line) {
final newCode = _code.foldedAt(line);
super.value = _getValueWithCode(newCode);
_code = newCode;
}
void unfoldAt(int line) {
final newCode = _code.unfoldedAt(line);
super.value = _getValueWithCode(newCode);
_code = newCode;
}
Set<String> get readOnlySectionNames => _readOnlySectionNames;
set readOnlySectionNames(Set<String> newValue) {
_readOnlySectionNames = newValue;
_updateCode(_code.text);
notifyListeners();
}
Set<String> get visibleSectionNames => _visibleSectionNames;
set visibleSectionNames(Set<String> sectionNames) {
_visibleSectionNames = sectionNames;
_updateCode(_code.text);
super.value = _getValueWithCode(_code);
}
/// The value with [newCode] preserving the current selection.
TextEditingValue _getValueWithCode(Code newCode) {
return TextEditingValue(
text: newCode.visibleText,
selection: newCode.hiddenRanges.cutSelection(
_code.hiddenRanges.recoverSelection(value.selection),
),
);
}
void foldCommentAtLineZero() {
final block = _code.foldableBlocks.firstOrNull;
if (block == null || !block.isComment || block.firstLine != 0) {
return;
}
foldAt(0);
}
void foldImports() {
// TODO(alexeyinkin): An optimized method to fold multiple blocks, https://github.com/akvelon/flutter-code-editor/issues/106
for (final block in _code.foldableBlocks) {
if (block.isImports) {
foldAt(block.firstLine);
}
}
}
/// Folds blocks that are outside all of the [names] sections.
///
/// For a block to be not folded, it must overlap any of the given sections
/// in any way.
void foldOutsideSections(Iterable<String> names) {
final foldLines = {..._code.foldableBlocks.map((b) => b.firstLine)};
final sections = names.map((s) => _code.namedSections[s]).whereNotNull();
for (final block in _code.foldableBlocks) {
for (final section in sections) {
if (block.overlaps(section)) {
foldLines.remove(block.firstLine);
break;
}
}
}
// TODO(alexeyinkin): An optimized method to fold multiple blocks, https://github.com/akvelon/flutter-code-editor/issues/106
foldLines.forEach(foldAt);
}
@override
TextSpan buildTextSpan({
required BuildContext context,
TextStyle? style,
bool? withComposing,
}) {
final spanBeforeSearch = _createTextSpan(
context: context,
style: style,
);
final visibleSearchResult =
_code.hiddenRanges.cutSearchResult(fullSearchResult);
// TODO(alexeyinkin): Return cached if the value did not change, https://github.com/akvelon/flutter-code-editor/issues/127
lastTextSpan = SearchResultHighlightedBuilder(
searchResult: visibleSearchResult,
rootStyle: style,
textSpan: spanBeforeSearch,
searchNavigationState: _searchNavigationController.value,
).build();
return lastTextSpan!;
}
TextSpan _createTextSpan({
required BuildContext context,
TextStyle? style,
}) {
// Return parsing
if (_language != null) {
return SpanBuilder(
code: _code,
theme: _getTheme(context),
rootStyle: style,
).build();
}
if (_styleRegExp != null) {
return _processPatterns(text, style);
}
return TextSpan(text: text, style: style);
}
TextSpan _processPatterns(String text, TextStyle? style) {
final children = <TextSpan>[];
text.splitMapJoin(
_styleRegExp!,
onMatch: (Match m) {
if (_styleList.isEmpty) {
return '';
}
int idx;
for (idx = 1;
idx < m.groupCount &&
idx <= _styleList.length &&
m.group(idx) == null;
idx++) {}
children.add(
TextSpan(
text: m[0],
style: _styleList[idx - 1],
),
);
return '';
},
onNonMatch: (String span) {
children.add(TextSpan(text: span, style: style));
return '';
},
);
return TextSpan(style: style, children: children);
}
CodeThemeData _getTheme(BuildContext context) {
return CodeTheme.of(context) ?? CodeThemeData();
}
void dismiss() {
_dismissSuggestions();
_dismissSearch();
}
void _dismissSuggestions() {
if (popupController.enabled) {
popupController.hide();
}
}
void _dismissSearch() {
searchController.hideSearch(returnFocusToCodeField: true);
}
void showSearch() {
searchController.showSearch();
}
@override
void dispose() {
_debounce?.cancel();
historyController.dispose();
searchController.dispose();
super.dispose();
}
}