forked from mechatroner/vscode_rainbow_csv
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathextension.js
More file actions
2870 lines (2509 loc) 路 133 KB
/
Copy pathextension.js
File metadata and controls
2870 lines (2509 loc) 路 133 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
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
996
997
998
999
1000
const vscode = require('vscode');
const path = require('path');
const fs = require('fs');
const os = require('os');
const child_process = require('child_process');
const fast_load_utils = require('./fast_load_utils.js');
// See DEV_README.md file for additional info.
// TODO advertise copy to excel as one of the main feature if no bugs reported.
const csv_utils = require('./rbql_core/rbql-js/csv_utils.js');
var rbql_csv = null; // Using lazy load to improve startup performance.
function ll_rbql_csv() {
if (rbql_csv === null)
rbql_csv = require('./rbql_core/rbql-js/rbql_csv.js');
return rbql_csv;
}
var rainbow_utils = null; // Using lazy load to improve startup performance.
function ll_rainbow_utils() {
if (rainbow_utils === null) {
rainbow_utils = require('./rainbow_utils.js');
}
return rainbow_utils;
}
// TODO consider checking `vscode.env.appHost == 'desktop'` instead.
const is_web_ext = (os.homedir === undefined); // Runs as web extension in browser.
var web_extension_uri = null;
const preview_window_size = 100;
const scratch_buf_marker = 'vscode_rbql_scratch';
const dynamic_csv_highlight_margin = 50; // TODO make configurable
let whitespace_aligned_files = new Set();
let alternate_row_background_decoration_type = null;
let tracked_field_decoration_types = [];
// TODO consider wrapping this into a class with enable()/disable() methods. The class could also access the global virtual alignment mode.
let custom_virtual_alignment_modes = new Map(); // file_name -> VA_EXPLICITLY_ENABLED|VA_EXPLICITLY_DISABLED
const VA_EXPLICITLY_ENABLED = "enabled";
const VA_EXPLICITLY_DISABLED = "disabled";
let whole_doc_alignment_stats = new Map();
var result_set_parent_map = new Map();
var cached_table_parse_result = new Map(); // TODO store doc timestamp / size to invalidate the entry when the doc changes.
var manual_comment_prefix_stoplist = new Set();
// Although these buttons are now available as context menu actions we keep them because they are part of the extension traditions.
var rbql_status_bar_button = null;
var align_shrink_button = null;
var copy_back_button = null;
var column_info_button = null;
var dynamic_dialect_select_button = null;
var rbql_context = null;
var debug_log_output_channel = null;
var last_rbql_queries = new Map(); // Query history does not replace this structure, it is also used to store partially entered queries for preview window switch.
var client_html_template = null;
var dialect_selection_html_template = null;
// This `global_state` is persistent across VSCode restarts.
var global_state = null;
var rbql_preview_panel = null;
var dialect_panel = null;
var doc_first_edit_subscription = null;
var column_info_cursor_subscription = null;
var alt_background_cursor_subscription = null;
var last_closed_rainbow_doc_info = null;
var _unit_test_last_rbql_report = null; // For unit tests only.
var _unit_test_last_warnings = null; // For unit tests only.
let cursor_timeout_handle_for_column_info = null;
let cursor_timeout_handle_for_alt_row_background = null;
let rainbow_token_event = null;
let comment_token_event = null;
let row_background_decoration_event = null;
let column_tracking_decoration_event = null;
let sticky_header_disposable = null;
let inlay_hint_disposable = null;
const PLAINTEXT = 'plaintext';
const DYNAMIC_CSV = 'dynamic csv';
const QUOTED_POLICY = 'quoted';
const WHITESPACE_POLICY = 'whitespace';
const QUOTED_RFC_POLICY = 'quoted_rfc';
const SIMPLE_POLICY = 'simple';
let extension_context = {
lint_results: new Map(),
lint_status_bar_button: null,
dynamic_document_dialects: new Map(),
custom_comment_prefixes: new Map(), // TODO consider making custom comment prefixes records persistent.
original_language_ids: new Map(),
toggle_enabled_rows_backgrounds: new Map(),
tracked_columns: new Map(),
reenable_rainbow_language_infos: new Map(), // This only needed for "Rainbow On" functionality that reverts "Rainbow Off" effect.
autodetection_stoplist: new Set(),
autodetection_temporarily_disabled_for_rbql: false,
dynamic_dialect_for_next_request: null,
logging_enabled: false,
logging_next_context_id: 1,
virtual_alignment_mode: 'disabled',
double_width_alignment: true,
virtual_alignment_char: 'middot',
virtual_alignment_vertical_grid: false,
comment_prefix: '',
};
const dialect_map = {
'csv': [',', QUOTED_POLICY],
'tsv': ['\t', SIMPLE_POLICY],
'csv (semicolon)': [';', QUOTED_POLICY],
'csv (pipe)': ['|', SIMPLE_POLICY],
'csv (whitespace)': [' ', WHITESPACE_POLICY],
[DYNAMIC_CSV]: [null, null]
};
const COMMENT_TOKEN = 'comment';
const rainbow_token_types = ['rainbow1', 'rainbow2', 'rainbow3', 'rainbow4', 'rainbow5', 'rainbow6', 'rainbow7', 'rainbow8', 'rainbow9', 'rainbow10'];
const all_token_types = rainbow_token_types.concat([COMMENT_TOKEN]);
const tokens_legend = new vscode.SemanticTokensLegend(all_token_types);
function is_eligible_scheme(vscode_doc) {
// Make sure that the the doc has a valid scheme.
// We don't want to handle virtual docs and docs created by other extensions, see https://code.visualstudio.com/api/extension-guides/virtual-documents#events-and-visibility and https://github.com/mechatroner/vscode_rainbow_csv/issues/123
// VScode also opens pairing virtual `.git` documents for git-controlled files that we also want to skip, see https://github.com/microsoft/vscode/issues/22561.
// "vscode-test-web" scheme is used for browser unit tests.
return vscode_doc && vscode_doc.uri && ['file', 'untitled', 'vscode-test-web'].indexOf(vscode_doc.uri.scheme) != -1;
}
function is_eligible_doc(vscode_doc) {
// For new untitled scratch documents `fileName` would be "Untitled-1", "Untitled-2", etc, so we won't enter this branch.
return vscode_doc && vscode_doc.uri && vscode_doc.fileName && is_eligible_scheme(vscode_doc);
}
function is_rainbow_dialect_doc(vscode_doc) {
return is_eligible_doc(vscode_doc) && dialect_map.hasOwnProperty(vscode_doc.languageId);
}
function make_dialect_info(delim, policy) {
return {'delim': delim, 'policy': policy};
}
function make_dynamic_dialect_key(file_path) {
return 'dynamic_dialect:' + file_path;
}
async function save_dynamic_info(extension_context, file_path, dialect_info) {
await save_to_global_state(make_dynamic_dialect_key(file_path), dialect_info);
extension_context.dynamic_document_dialects.set(file_path, dialect_info);
}
async function remove_dynamic_info(file_path) {
await save_to_global_state(make_dynamic_dialect_key(file_path), undefined);
extension_context.dynamic_document_dialects.delete(file_path);
}
function get_dynamic_info(file_path) {
// Filetypes (lang modes) are not preserved across doc reopen but surprisingly preserved across VSCode restarts so we are also storing them in persistent global state.
// Persistent dialect info has some minor drawbacks (e.g. performance also restart not completely resetting the state is an issue by itself in some scenarios) and could be reconsidered if more serious issues are found.
if (extension_context.dynamic_document_dialects.has(file_path)) {
return extension_context.dynamic_document_dialects.get(file_path);
}
// Failed to get from the session-local dynamic_document_dialects - check if we have it persistently stored from a previous session.
let dialect_info = get_from_global_state(make_dynamic_dialect_key(file_path), null);
if (dialect_info && dialect_info.hasOwnProperty('delim') && dialect_info.hasOwnProperty('policy')) {
extension_context.dynamic_document_dialects.set(file_path, dialect_info);
return dialect_info;
}
return null;
}
function safe_lower(src_str) {
if (!src_str)
return src_str;
return src_str.toLowerCase();
}
function get_default_policy(separator) {
// This function is most likely a temporal workaround, get rid of it when possible.
for (let language_id in dialect_map) {
if (!dialect_map.hasOwnProperty(language_id))
continue;
if (dialect_map[language_id][0] == separator)
return dialect_map[language_id][1];
}
return SIMPLE_POLICY;
}
function map_dialect_to_language_id(separator, policy) {
for (let language_id in dialect_map) {
if (!dialect_map.hasOwnProperty(language_id))
continue;
if (dialect_map[language_id][0] == separator && dialect_map[language_id][1] == policy)
return language_id;
}
return DYNAMIC_CSV;
}
// This structure will get properly initialized during the startup.
let absolute_path_map = {
'rbql_client.js': null,
'contrib/textarea-caret-position/index.js': null,
'rbql_suggest.js': null,
'rbql_logo.svg': null,
'rbql_client.html': null,
'dialect_select.html': null,
'dialect_select.js': null,
'rbql mock/rbql_mock.py': null,
'rbql_core/vscode_rbql.py': null
};
function show_single_line_error(error_msg) {
var active_window = vscode.window;
if (!active_window)
return;
// Do not "await" error messages because the promise gets resolved only on error dismissal.
active_window.showErrorMessage(error_msg);
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function report_progress(progress, status_message) {
progress.report({message: status_message});
// Push the current stack to the JS callback queue to allow UI update.
await sleep(0);
}
function get_from_global_state(key, default_value) {
// Load KV pair from the "global state" which is persistent across VSCode restarts.
if (global_state) {
var value = global_state.get(key);
if (value !== null && value !== undefined)
return value;
}
return default_value;
}
async function save_to_global_state(key, value) {
// Save KV pair to the "global state" which is persistent across VSCode restarts.
if (global_state && key) {
await global_state.update(key, value);
return true;
}
return false;
}
async function replace_doc_content(active_editor, active_doc, new_content) {
let invalid_range = new vscode.Range(0, 0, active_doc.lineCount /* Intentionally missing the '-1' */, 0);
let full_range = active_doc.validateRange(invalid_range);
await active_editor.edit(edit => edit.replace(full_range, new_content));
}
function make_header_key(file_path) {
return 'rbql_header_info:' + file_path;
}
function make_with_headers_key(file_path) {
return 'rbql_with_headers:' + file_path;
}
function get_from_config(param_name, default_value, config=null) {
if (!config) {
config = vscode.workspace.getConfiguration('rainbow_csv');
}
return config ? config.get(param_name) : default_value;
}
class TrackedColumns {
// TODO move to rainbow_utils.js and add unit tests
constructor() {
this.column_to_decoration_id = new Map();
}
is_tracked(column_num) {
return this.column_to_decoration_id.has(column_num);
}
get_tracked_columns() {
return Array.from(this.column_to_decoration_id.keys());
}
toggle_tracking(column_num) {
if (this.column_to_decoration_id.has(column_num)) {
this.column_to_decoration_id.delete(column_num);
} else {
if (this.num_tracked() >= tracked_field_decoration_types.length) {
return false;
}
let existing_decoration_ids = Array.from(this.column_to_decoration_id.values());
let new_id = 0;
while (existing_decoration_ids.includes(new_id)) {
new_id += 1;
}
this.column_to_decoration_id.set(column_num, new_id);
}
return true;
}
get_decoration_type(column_num) {
if (!this.column_to_decoration_id.has(column_num)) {
return null;
}
return tracked_field_decoration_types[this.column_to_decoration_id.get(column_num)];
}
num_tracked() {
return this.column_to_decoration_id.size;
}
empty() {
return this.column_to_decoration_id.size == 0;
}
}
class StackContextLogWrapper {
// Use class instead of pure function to avoid passing context name and checking if logging is enabled in the config in each call.
constructor(context_name, caller_context_id=null) {
this.context_name = context_name;
this.logging_enabled = extension_context.logging_enabled;
this.context_id = caller_context_id === null ? extension_context.logging_next_context_id : caller_context_id;
extension_context.logging_next_context_id += 1;
}
log_doc_event(event_name, vscode_doc=null) {
if (!this.logging_enabled)
return;
try {
let full_event = `CID:${this.context_id}, ${this.context_name}:${event_name}`;
if (vscode_doc) {
full_event = `${full_event}, doc_lang:${vscode_doc.languageId}`;
if (vscode_doc.uri) {
let str_uri = vscode_doc.uri.toString(/*skipEncoding=*/true);
full_event = `${full_event}, doc_uri:${str_uri}`;
}
} else {
full_event = `${full_event}, no_doc:1`;
}
// Use "info" level because logging is flag-guarded by the extension-level setting.
debug_log_output_channel.info(full_event);
} catch (_error) {
console.error(`Rainbow CSV: Unexpected log failure. ${this.context_name}:${this.event_name}`);
return;
}
}
log_simple_event(event_name) {
if (!this.logging_enabled)
return;
try {
let full_event = `CID:${this.context_id}, ${this.context_name}:${event_name}`;
debug_log_output_channel.info(full_event);
} catch (_error) {
console.error(`Rainbow CSV: Unexpected log failure. ${this.context_name}:${this.event_name}`);
return;
}
}
}
function get_header_from_document(document, delim, policy, comment_prefix) {
let [header_lnum, header_text] = ll_rainbow_utils().get_header_line(document, comment_prefix);
if (!header_text) {
return [null, null];
}
return [header_lnum, csv_utils.smart_split(header_text, delim, policy, /*preserve_quotes_and_whitespaces=*/false)[0]];
}
function get_header(document, delim, policy, comment_prefix) {
var file_path = document.fileName;
if (file_path) {
let header_info = get_from_global_state(make_header_key(file_path), null);
if (header_info !== null && header_info.header !== null) {
return [header_info.header_line_num, header_info.header];
}
}
return get_header_from_document(document, delim, policy, comment_prefix);
}
function get_dialect(document) {
let language_id = document.languageId;
let delim = null;
let policy = null;
let comment_prefix = '';
if (extension_context.custom_comment_prefixes.has(document.fileName)) {
comment_prefix = extension_context.custom_comment_prefixes.get(document.fileName);
} else {
comment_prefix = extension_context.comment_prefix;
}
if (language_id != DYNAMIC_CSV && dialect_map.hasOwnProperty(language_id)) {
[delim, policy] = dialect_map[language_id];
return [delim, policy, comment_prefix];
}
let dialect_info = null;
if (language_id == DYNAMIC_CSV) {
dialect_info = get_dynamic_info(document.fileName);
}
if (dialect_info) {
return [dialect_info.delim, dialect_info.policy, comment_prefix];
}
// The language id can be `dynamic csv` here e.g. if user just now manually selected the "Dynamic CSV" filetype.
return [null, null, null];
}
function enable_rainbow_ui(active_doc) {
if (dynamic_dialect_select_button) {
dynamic_dialect_select_button.hide();
}
ll_rainbow_utils().show_lint_status_bar_button(vscode, extension_context, active_doc.fileName, active_doc.languageId);
show_rbql_status_bar_button();
show_align_shrink_button(active_doc.fileName);
show_rbql_copy_to_source_button(active_doc.fileName);
let cursor_position_info_enabled = get_from_config('enable_cursor_position_info', false);
if (cursor_position_info_enabled) {
show_column_info_button(); // This function finds active_doc internally, but the possible inconsistency is harmless.
column_info_cursor_subscription = vscode.window.onDidChangeTextEditorSelection(handle_cursor_movement_for_column_info);
}
if (row_background_enabled(active_doc.fileName)) {
alt_background_cursor_subscription = vscode.window.onDidChangeTextEditorSelection(handle_cursor_movement_for_alt_row_background);
}
}
class StickyHeaderProvider {
// We don't utilize typescript `implement` interface keyword, because TS doesn't seem to be exporting interfaces to JS (unlike classes).
constructor() {
}
async provideDocumentSymbols(document) {
// This can trigger multiple times for the same doc because otherwise this won't work in case of e.g. header edit.
let [delim, policy, comment_prefix] = get_dialect(document);
if (!policy) {
return null;
}
let header_lnum = get_header(document, delim, policy, comment_prefix)[0];
if (header_lnum === null /* - this can happen for user-provided "virtual" header */ || header_lnum >= document.lineCount - 1) {
return null;
}
let full_range = new vscode.Range(header_lnum, 0, document.lineCount - 1, 65535);
full_range = document.validateRange(full_range); // Just in case, should be always NOOP.
let header_range = new vscode.Range(header_lnum, 0, header_lnum, 65535);
if (!full_range.contains(header_range)) {
return; // Should never happen.
}
let symbol_kind = vscode.SymbolKind.File; // It is vscode.SymbolKind.File because it shows a nice "File" icon in the upper navigational panel. Another nice option is "Class".
let header_symbol = new vscode.DocumentSymbol('data', '', symbol_kind, full_range, header_range);
return [header_symbol];
}
}
function get_all_rainbow_lang_selector() {
let document_selector = [];
for (let language_id in dialect_map) {
if (dialect_map.hasOwnProperty(language_id)) {
document_selector.push({language: language_id});
}
}
return document_selector;
}
function reconfigure_sticky_header_provider(force=false) {
// Sticky header is enabled in VSCode by default already.
// TODO consider overriding the global config option dynamically for the current language id and workspace only, but if you do this make sure that right click -> disable on the header still disables it.
let enable_sticky_header = get_from_config('enable_sticky_header', false);
if (!enable_sticky_header) {
if (sticky_header_disposable !== null) {
sticky_header_disposable.dispose();
sticky_header_disposable = null;
}
return;
}
if (sticky_header_disposable !== null && force) {
sticky_header_disposable.dispose();
sticky_header_disposable = null;
}
if (sticky_header_disposable !== null) {
// Sticky header provider already exists, nothing to do.
return;
}
let header_symbol_provider = new StickyHeaderProvider();
sticky_header_disposable = vscode.languages.registerDocumentSymbolProvider(get_all_rainbow_lang_selector(), header_symbol_provider);
}
function reenable_inlay_hints_provider() {
// Dispose previous provider to refresh stale hints, including enabling them when disabled or disabling when enabled.
if (inlay_hint_disposable !== null) {
inlay_hint_disposable.dispose();
}
let inlay_hints_provider = new InlayHintProvider();
inlay_hint_disposable = vscode.languages.registerInlayHintsProvider(get_all_rainbow_lang_selector(), inlay_hints_provider);
}
async function configure_inlay_hints_alignment(language_id, log_wrapper) {
// We have 3 invocation contexts here:
// 1. VA is "disabled" but the function was called via the command palette command directly.
// 2. VA is "manual" and the function was called either by the command palette or the "Align" button (essentially the same).
// 3. VA is "always" and the function was called on file open.
if (language_id == 'tsv') {
let active_editor = get_active_editor();
if (active_editor) {
if (active_editor.options.tabSize != 1) {
active_editor.options.tabSize = 1;
log_wrapper.log_doc_event(`Updated editor tab size to single (1) space for this doc`);
}
}
}
try {
let config = vscode.workspace.getConfiguration('editor', {languageId: language_id});
// Adjusting these settings as `configurationDefaults` in package.json doesn't work reliably, so we set it here dynamically.
// Note that there is User and Workspace-level configs options in the File->Preferences->Settings UI - this is important when you are trying to debug the limits.
// Adjusting these settings on the workspace level doesn't quite work because VSCode doesn't always have an active workspace, e.g. you can click [Close Workspace] from the main [File] menu to reproduce the problem. So we adjust the settings on global level instead which should always work.
let update_global_settings = true;
if (config.get('inlayHints.enabled') == 'off') {
// Some users have inlay hints disabled alltogether, see https://github.com/mechatroner/vscode_rainbow_csv/issues/242.
// So we re-enable inlay hints for the current language only since it was explicitly requested via the UI interaction.
await config.update('inlayHints.enabled', 'on', /*configurationTarget=*/update_global_settings, /*overrideInLanguage=*/true);
log_wrapper.log_doc_event(`Updated inlayHints.enabled = 'on' for "${language_id}"`);
}
if (config.get('inlayHints.maximumLength') != 0) {
// Worklog: The first time I tried this the solution was half-working - we wouldn't see the inlay-hiding "three dots", but the alignment was still broken in a weird way. But the problem disappeared on "restart".
await config.update('inlayHints.maximumLength', 0, /*configurationTarget=*/update_global_settings, /*overrideInLanguage=*/true);
log_wrapper.log_doc_event(`Updated inlayHints.maximumLength = 0 for "${language_id}"`);
}
if (config.get('inlayHints.fontFamily') != '') {
await config.update('inlayHints.fontFamily', '', /*configurationTarget=*/update_global_settings, /*overrideInLanguage=*/true);
log_wrapper.log_doc_event(`Updated inlayHints.fontFamily = '' for "${language_id}"`);
}
if (config.get('inlayHints.fontSize') != '') {
await config.update('inlayHints.fontSize', '', /*configurationTarget=*/update_global_settings, /*overrideInLanguage=*/true);
log_wrapper.log_doc_event(`Updated inlayHints.fontSize = '' for "${language_id}"`);
}
if (config.get('inlayHints.padding') != '') {
await config.update('inlayHints.padding', '', /*configurationTarget=*/update_global_settings, /*overrideInLanguage=*/true);
log_wrapper.log_doc_event(`Updated inlayHints.padding = '' for "${language_id}"`);
}
// It would be nice to disable word wrap for the current editor only if aligned (because tables don't wrap) and then enable word wrap again, but there is no way to do this currently.
// Permanent disabling of wordWrap for csvs is a bad idea because in non-aligned mode it actually becomes an advantage for Rainbow non-alignment high info density paradigm.
} catch (e) {
log_wrapper.log_doc_event("Failed to update inlay hints user settings: " + e);
}
}
function enable_dynamic_semantic_tokenization() {
// Some themes can disable semantic highlighting e.g. "Tokyo Night" https://marketplace.visualstudio.com/items?itemName=enkia.tokyo-night, so we explicitly override the default setting in "configurationDefaults" section of package.json.
// We also add all other csv dialects to "configurationDefaults":"editor.semanticHighlighting.enabled" override in order to enable comment line highlighting.
// Conflict with some other extensions might also cause semantic highlighting to completely fail (although this could be caused by the theme issue described above), see https://github.com/mechatroner/vscode_rainbow_csv/issues/149.
let token_provider = new RainbowTokenProvider();
if (rainbow_token_event !== null) {
rainbow_token_event.dispose();
}
let document_selector = { language: DYNAMIC_CSV }; // Use '*' to select all languages if needed.
rainbow_token_event = vscode.languages.registerDocumentRangeSemanticTokensProvider(document_selector, token_provider, tokens_legend);
}
function row_background_enabled(fileName) {
let default_enabled = get_from_config('highlight_rows', false);
return extension_context.toggle_enabled_rows_backgrounds.has(fileName) ? extension_context.toggle_enabled_rows_backgrounds.get(fileName) : default_enabled;
}
function toggle_row_background() {
let active_editor = get_active_editor();
if (!active_editor)
return;
var active_doc = get_active_doc(active_editor);
if (!active_doc)
return;
let [_delim, policy, _comment_prefix] = get_dialect(active_doc);
if (policy == QUOTED_RFC_POLICY) {
// TODO use correct parsing logic to be able to handle multiline records and correctly highlight them
show_single_line_error("Alternating row background highlighting is currently unavailable for CSVs with multiline records");
return;
}
let log_wrapper = new StackContextLogWrapper('toggle_row_background');
log_wrapper.log_doc_event('starting', active_doc);
let enabled_before = row_background_enabled(active_doc.fileName);
let highlighting_enabled = !enabled_before;
extension_context.toggle_enabled_rows_backgrounds.set(active_doc.fileName, highlighting_enabled);
if (highlighting_enabled) {
log_wrapper.log_doc_event('enabled', active_doc);
} else {
log_wrapper.log_doc_event('disabled', active_doc);
// Use empty range array to reset the decorations.
active_editor.setDecorations(alternate_row_background_decoration_type, []);
}
// Always re-register the provider to force decorations update on toggle.
register_row_background_decorations_provider();
if (alt_background_cursor_subscription == null) {
alt_background_cursor_subscription = vscode.window.onDidChangeTextEditorSelection(handle_cursor_movement_for_alt_row_background);
}
}
function register_column_tracking_decorations_provider() {
let decorations_provider = new ColumnTrackingDecorationsProvider();
if (column_tracking_decoration_event !== null) {
column_tracking_decoration_event.dispose();
}
// There is no way to register ranged decorations provider so we register a fake ranged semantic token provider that doesn't provide any tokens.
column_tracking_decoration_event = vscode.languages.registerDocumentRangeSemanticTokensProvider(get_all_rainbow_lang_selector(), decorations_provider, tokens_legend);
}
function toggle_column_tracking() {
let active_editor = get_active_editor();
if (!active_editor)
return;
var active_doc = get_active_doc(active_editor);
if (!active_doc || !is_rainbow_dialect_doc(active_doc))
return;
let log_wrapper = new StackContextLogWrapper('toggle_column_tracking');
log_wrapper.log_doc_event('starting', active_doc);
let position = ll_rainbow_utils().get_cursor_position_if_unambiguous(active_editor);
if (!position) {
return;
}
let [delim, policy, comment_prefix] = get_dialect(active_doc);
let cursor_position_info = ll_rainbow_utils().get_cursor_position_info(vscode, active_doc, delim, policy, comment_prefix, position);
if (!cursor_position_info)
return;
if (cursor_position_info.is_comment) {
vscode.window.showErrorMessage('Unable to track comments');
return;
}
let fileName = active_doc.fileName;
let trackings = extension_context.tracked_columns.has(fileName) ? extension_context.tracked_columns.get(fileName) : new TrackedColumns();
if (trackings.is_tracked(cursor_position_info.column_number)) {
let decoration_type = trackings.get_decoration_type(cursor_position_info.column_number);
// Use empty range array to reset the decorations.
active_editor.setDecorations(decoration_type, []);
log_wrapper.log_doc_event('disabling column tracking', active_doc);
} else {
log_wrapper.log_doc_event('enabling column tracking', active_doc);
}
if (!trackings.toggle_tracking(cursor_position_info.column_number)) {
vscode.window.showErrorMessage(`Unable to track more than ${trackings.num_tracked()} columns`);
return;
}
extension_context.tracked_columns.set(fileName, trackings);
// Always re-register the column tracking decorations provider to refresh the decorations so that toggle effect is immediately visible
register_column_tracking_decorations_provider();
}
function register_row_background_decorations_provider() {
let decorations_provider = new RowBackgroundDecorationsProvider();
if (row_background_decoration_event !== null) {
row_background_decoration_event.dispose();
}
// There is no way to register ranged decorations provider so we register a fake ranged semantic token provider that doesn't provide any tokens.
row_background_decoration_event = vscode.languages.registerDocumentRangeSemanticTokensProvider(get_all_rainbow_lang_selector(), decorations_provider, tokens_legend);
}
function register_comment_tokenization_handler() {
let token_provider = new CommentTokenProvider();
if (comment_token_event !== null) {
comment_token_event.dispose();
}
let document_selector = [];
for (let language_id in dialect_map) {
if (dialect_map.hasOwnProperty(language_id) && language_id != DYNAMIC_CSV) {
// We skip DYNAMIC_CSV here because its provider already handles comment lines.
document_selector.push({language: language_id});
}
}
comment_token_event = vscode.languages.registerDocumentRangeSemanticTokensProvider(document_selector, token_provider, tokens_legend);
}
function get_selected_separator(active_editor, active_doc) {
if (!active_editor || !active_doc)
return '';
let selection = active_editor.selection;
if (!selection) {
return '';
}
if (selection.start.line != selection.end.line) {
return '';
}
let separator = active_doc.lineAt(selection.start.line).text.substring(selection.start.character, selection.end.character);
return separator;
}
async function choose_dynamic_separator(integration_test_options=null) {
let log_wrapper = new StackContextLogWrapper('choose_dynamic_separator');
log_wrapper.log_doc_event('starting', active_doc);
let active_editor = get_active_editor();
if (!active_editor) {
return;
}
var active_doc = get_active_doc(active_editor);
if (!is_eligible_doc(active_doc)) {
return;
}
let selected_separator = get_selected_separator(active_editor, active_doc);
if (!dialect_selection_html_template) {
dialect_selection_html_template = await load_resource_file_universal('dialect_select.html');
}
dialect_panel = vscode.window.createWebviewPanel('rainbow-dialect-select', 'Choose CSV Dialect', vscode.ViewColumn.Beside, {enableScripts: true});
dialect_panel.webview.html = adjust_webview_paths(dialect_panel, dialect_selection_html_template, ['dialect_select.js']);
dialect_panel.webview.onDidReceiveMessage(function(message) { handle_dialect_selection_message(active_doc, dialect_panel, message, selected_separator, log_wrapper, integration_test_options); });
}
function show_choose_dynamic_separator_button() {
if (!dynamic_dialect_select_button)
dynamic_dialect_select_button = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);
dynamic_dialect_select_button.text = 'Choose Separator...';
dynamic_dialect_select_button.tooltip = 'Click to choose Dynamic CSV separator';
dynamic_dialect_select_button.command = 'rainbow-csv.RainbowSeparator';
dynamic_dialect_select_button.show();
}
async function enable_rainbow_features_if_csv(active_doc, log_wrapper) {
log_wrapper.log_doc_event('start enable-rainbow-features-if-csv', active_doc);
if (!is_rainbow_dialect_doc(active_doc)) {
log_wrapper.log_simple_event('abort enable-rainbow-features-if-csv: non-rainbow dialect');
return;
}
var language_id = active_doc.languageId;
if (language_id == DYNAMIC_CSV && extension_context.dynamic_dialect_for_next_request != null) {
await save_dynamic_info(extension_context, active_doc.fileName, extension_context.dynamic_dialect_for_next_request);
extension_context.dynamic_dialect_for_next_request = null;
}
let [delim, policy, comment_prefix] = get_dialect(active_doc);
if (!delim || !policy) {
log_wrapper.log_simple_event('abort enable-rainbow-features-if-csv: missing delim or policy');
// Make sure UI elements are disabled except dynamic separator selection button.
disable_ui_elements();
show_choose_dynamic_separator_button();
return;
}
if (comment_prefix) {
// It is currently impoossible to set comment_prefix on document level, so we have to set it on language level instead.
// This could potentially cause minor problems in very rare situations.
// Applying 'setLanguageConfiguration' doesn't disable static configuration in language-configuration.json.
vscode.languages.setLanguageConfiguration(language_id, { comments: { lineComment: comment_prefix } });
}
if (language_id == DYNAMIC_CSV) {
// Re-enable tokenization to explicitly trigger the highlighting. Sometimes this doesn't happen automatically.
enable_dynamic_semantic_tokenization();
}
enable_rainbow_ui(active_doc);
if (extension_context.virtual_alignment_mode == 'always') {
await configure_inlay_hints_alignment(language_id, log_wrapper);
reenable_inlay_hints_provider();
}
await csv_lint(active_doc, /*is_manual_op=*/false);
log_wrapper.log_simple_event('finish enable-rainbow-features-if-csv');
}
function disable_ui_elements() {
let all_buttons = [extension_context.lint_status_bar_button, rbql_status_bar_button, copy_back_button, align_shrink_button, column_info_button, dynamic_dialect_select_button];
for (let i = 0; i < all_buttons.length; i++) {
if (all_buttons[i])
all_buttons[i].hide();
}
if (column_info_cursor_subscription) {
column_info_cursor_subscription.dispose();
column_info_cursor_subscription = null;
}
if (alt_background_cursor_subscription) {
alt_background_cursor_subscription.dispose();
alt_background_cursor_subscription = null;
}
}
function disable_rainbow_features_if_non_csv(active_doc, log_wrapper) {
log_wrapper.log_doc_event('start disable-rainbow-features-if-non-csv', active_doc);
if (is_rainbow_dialect_doc(active_doc)) {
log_wrapper.log_simple_event('abort disable-rainbow-features-if-non-csv: is rainbow dialect');
return;
}
log_wrapper.log_simple_event('perform disable-rainbow-features-if-non-csv');
disable_ui_elements();
}
function get_active_editor() {
var active_window = vscode.window;
if (!active_window)
return null;
var active_editor = active_window.activeTextEditor;
if (!active_editor)
return null;
return active_editor;
}
function get_active_doc(active_editor=null) {
if (!active_editor)
active_editor = get_active_editor();
if (!active_editor)
return null;
var active_doc = active_editor.document;
if (!active_doc)
return null;
return active_doc;
}
function is_active_doc(vscode_doc) {
let active_doc = get_active_doc();
return (active_doc && active_doc.uri && vscode_doc && vscode_doc.uri && active_doc.uri.toString() == vscode_doc.uri.toString());
}
function virtual_alignment_enabled(virtual_alignment_mode, custom_alignment_mode) {
return (custom_alignment_mode == VA_EXPLICITLY_ENABLED) || (virtual_alignment_mode == "always" && custom_alignment_mode != VA_EXPLICITLY_DISABLED);
}
function config_virtual_alignment_button(align_shrink_button, is_aligned) {
if (is_aligned) {
align_shrink_button.text = 'Shrink';
align_shrink_button.tooltip = 'Click to remove virtual alignment from this file';
align_shrink_button.command = 'rainbow-csv.VirtualShrink';
} else {
align_shrink_button.text = 'Align';
align_shrink_button.tooltip = 'Click to virtually align';
align_shrink_button.command = 'rainbow-csv.VirtualAlign';
}
}
function config_whitespace_alignment_button(align_shrink_button, is_aligned) {
if (is_aligned) {
align_shrink_button.text = 'Shrink';
align_shrink_button.tooltip = 'Click to shrink table - trim whitespaces from fields';
align_shrink_button.command = 'rainbow-csv.Shrink';
} else {
align_shrink_button.text = 'Align';
align_shrink_button.tooltip = 'Click to align table with extra whitespaces';
align_shrink_button.command = 'rainbow-csv.Align';
}
}
function show_align_shrink_button(file_path) {
if (!align_shrink_button)
align_shrink_button = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);
if (extension_context.virtual_alignment_mode == 'disabled') {
let is_aligned = whitespace_aligned_files.has(file_path);
config_whitespace_alignment_button(align_shrink_button, is_aligned);
} else {
let custom_alignment_mode = custom_virtual_alignment_modes.get(file_path);
let is_aligned = virtual_alignment_enabled(extension_context.virtual_alignment_mode, custom_alignment_mode);
config_virtual_alignment_button(align_shrink_button, is_aligned);
}
align_shrink_button.show();
}
function do_show_column_info_button(full_report, short_report) {
if (!column_info_button)
column_info_button = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 1000);
column_info_button.text = short_report;
column_info_button.tooltip = full_report;
column_info_button.show();
}
function make_hover(document, language_id, position, cancellation_token) {
if (!get_from_config('enable_tooltip', false)) {
return;
}
let [delim, policy, comment_prefix] = get_dialect(document);
let cursor_position_info = ll_rainbow_utils().get_cursor_position_info(vscode, document, delim, policy, comment_prefix, position);
if (!cursor_position_info || cancellation_token.isCancellationRequested)
return null;
let enable_tooltip_column_names = get_from_config('enable_tooltip_column_names', false);
let header = get_header(document, delim, policy, comment_prefix)[1];
if (!header) {
return null;
}
let [_full_text, short_report] = ll_rainbow_utils().format_cursor_position_info(cursor_position_info, header, enable_tooltip_column_names, /*show_comments=*/true, /*max_label_length=*/25);
let mds = new vscode.MarkdownString();
// Using a special pseudo-language grammar trick for highlighting the hover text using the same color as the column doesn't work anymore due to https://github.com/microsoft/vscode/issues/53723.
mds.appendText(short_report);
return new vscode.Hover(mds);
}
function show_column_info_button() {
let active_editor = get_active_editor();
if (!active_editor) {
return false;
}
let position = ll_rainbow_utils().get_cursor_position_if_unambiguous(active_editor);
if (!position) {
return false;
}
let active_doc = get_active_doc(active_editor);
let [delim, policy, comment_prefix] = get_dialect(active_doc);
let cursor_position_info = ll_rainbow_utils().get_cursor_position_info(vscode, active_doc, delim, policy, comment_prefix, position);
if (!cursor_position_info)
return false;
let enable_tooltip_column_names = get_from_config('enable_tooltip_column_names', false);
let header = get_header(active_doc, delim, policy, comment_prefix)[1];
if (!header)
return false;
let [full_report, short_report] = ll_rainbow_utils().format_cursor_position_info(cursor_position_info, header, enable_tooltip_column_names, /*show_comments=*/false, /*max_label_length=*/25);
do_show_column_info_button(full_report, short_report);
return true;
}
function show_rbql_status_bar_button() {
if (!rbql_status_bar_button)
rbql_status_bar_button = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);
rbql_status_bar_button.text = 'Query';
rbql_status_bar_button.tooltip = 'Click to run SQL-like RBQL query';
rbql_status_bar_button.command = 'rainbow-csv.RBQL';
rbql_status_bar_button.show();
}
function show_rbql_copy_to_source_button(file_path) {
let parent_table_path = result_set_parent_map.get(safe_lower(file_path));
if (!parent_table_path || parent_table_path.indexOf(scratch_buf_marker) != -1)
return;
let parent_basename = path.basename(parent_table_path);
if (!copy_back_button)
copy_back_button = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);
copy_back_button.text = 'Copy Back';
copy_back_button.tooltip = `Copy to parent table: ${parent_basename}`;
copy_back_button.command = 'rainbow-csv.CopyBack';
copy_back_button.show();
}
async function csv_lint(active_doc, is_manual_op) {
if (!active_doc)
active_doc = get_active_doc();
if (!is_rainbow_dialect_doc(active_doc)) {
return null;
}
var file_path = active_doc.fileName; // For new untitled scratch documents this would be "Untitled-1", "Untitled-2", etc...
var language_id = active_doc.languageId;
let lint_cache_key = `${file_path}.${language_id}`;