-
Notifications
You must be signed in to change notification settings - Fork 53
/
extension.js
2308 lines (2004 loc) · 106 KB
/
extension.js
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.
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;
}
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();
// 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";
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();
var rbql_status_bar_button = null;
var align_shrink_button = null;
var rainbow_off_status_bar_button = null;
var rainbow_on_status_bar_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 keyboard_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 = null;
let rainbow_token_event = null;
let comment_token_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(),
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,
};
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 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_line] = ll_rainbow_utils().get_header_line(document, comment_prefix);
if (!header_line) {
return null;
}
return csv_utils.smart_split(header_line, 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;
}
}
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 = get_from_config('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_rainbow_off_status_bar_button();
show_rbql_copy_to_source_button(active_doc.fileName);
show_column_info_button(); // This function finds active_doc internally, but the possible inconsistency is harmless.
if (get_from_config('enable_cursor_position_info', false)) {
keyboard_cursor_subscription = vscode.window.onDidChangeTextEditorSelection(handle_cursor_movement);
}
}
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 = null;
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_line_num !== null) {
header_lnum = header_info.header_line_num;
}
}
if (header_lnum === null) {
header_lnum = ll_rainbow_utils().get_header_line(document, comment_prefix)[0];
}
if (header_lnum === null || 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);
}
async function set_up_inlay_hint_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 pallete 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`);
}
}
}
let config = vscode.workspace.getConfiguration('editor', {languageId: 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".
// For some reason setting this setting as `configurationDefaults` in package.json doesn't have any affect, 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.
await config.update('inlayHints.maximumLength', 0, /*configurationTarget=*/false, /*overrideInLanguage=*/true);
log_wrapper.log_doc_event(`Updated inlayHints.maximumLength = 0 for "${language_id}"`);
}
if (inlay_hint_disposable == null) {
let inlay_hints_provider = new InlayHintProvider();
inlay_hint_disposable = vscode.languages.registerInlayHintsProvider(get_all_rainbow_lang_selector(), inlay_hints_provider);
}
}
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 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;
}
if (rainbow_on_status_bar_button) {
rainbow_on_status_bar_button.hide();
}
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 highligthing. Sometimes this doesn't happen automatically.
enable_dynamic_semantic_tokenization();
}
enable_rainbow_ui(active_doc);
if (get_from_config('virtual_alignment_mode', 'disabled') == 'always') {
await set_up_inlay_hint_alignment(language_id, log_wrapper);
}
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, rainbow_off_status_bar_button, copy_back_button, align_shrink_button, column_info_button, dynamic_dialect_select_button, rainbow_on_status_bar_button];
for (let i = 0; i < all_buttons.length; i++) {
if (all_buttons[i])
all_buttons[i].hide();
}
if (keyboard_cursor_subscription) {
keyboard_cursor_subscription.dispose();
keyboard_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)) {
if (rainbow_on_status_bar_button) {
rainbow_on_status_bar_button.hide();
}
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();
if (is_eligible_doc(active_doc) && extension_context.reenable_rainbow_language_infos.has(active_doc.fileName)) {
// Show "Rainbow On" button. The button will be hidden again if user clicks away by `disable_rainbow_features_if_non_csv`.
// Only show for non-rainbow docs since this mechanism can interfere with manual filetype selection UI.
log_wrapper.log_simple_event('show rainbow-on status button');
show_rainbow_on_status_bar_button();
}
}
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);
let virtual_alignment_mode = get_from_config('virtual_alignment_mode', 'disabled');
if (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(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);
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);
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_rainbow_off_status_bar_button() {
if (!rainbow_off_status_bar_button)
rainbow_off_status_bar_button = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);
rainbow_off_status_bar_button.text = 'Rainbow OFF';
rainbow_off_status_bar_button.tooltip = 'Click to restore original file type and syntax';
rainbow_off_status_bar_button.command = 'rainbow-csv.RainbowSeparatorOff';
rainbow_off_status_bar_button.show();
}
function show_rainbow_on_status_bar_button() {
// TODO consider showing the separator selection dialog on "RainbowOn" button click instead of restoring the previous dialect.
if (!rainbow_on_status_bar_button)
rainbow_on_status_bar_button = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);
rainbow_on_status_bar_button.text = 'Rainbow ON';
rainbow_on_status_bar_button.tooltip = 'Click to reenable Rainbow CSV for this file';
rainbow_on_status_bar_button.command = 'rainbow-csv.RainbowSeparatorOn';
rainbow_on_status_bar_button.show();
}
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}`;
if (!is_manual_op) {
if (extension_context.lint_results.has(lint_cache_key))
return null;
if (!get_from_config('enable_auto_csv_lint', false))
return null;
}
let [delim, policy, comment_prefix] = get_dialect(active_doc);
if (policy === null)
return null;
extension_context.lint_results.set(lint_cache_key, {is_processing: true});
ll_rainbow_utils().show_lint_status_bar_button(vscode, extension_context, file_path, language_id); // Visual feedback.
let detect_trailing_spaces = get_from_config('csv_lint_detect_trailing_spaces', false);
let [_records, _num_records_parsed, fields_info, first_defective_line, first_trailing_space_line, _comments] = fast_load_utils.parse_document_records(active_doc, delim, policy, comment_prefix, /*stop_on_warning=*/true, /*max_records_to_parse=*/-1, /*collect_records=*/false, /*preserve_quotes_and_whitespaces=*/true, detect_trailing_spaces);
let is_ok = (first_defective_line === null && fields_info.size <= 1);
let lint_result = {'is_ok': is_ok, 'first_defective_line': first_defective_line, 'fields_info': fields_info, 'first_trailing_space_line': first_trailing_space_line};
extension_context.lint_results.set(lint_cache_key, lint_result);
if (is_manual_op) {
// Need timeout here to give user enough time to notice green -> yellow -> green switch, this is a sort of visual feedback.
await sleep(500);
}
ll_rainbow_utils().show_lint_status_bar_button(vscode, extension_context, file_path, language_id); // Visual feedback.
return lint_result;
}
async function csv_lint_cmd() {
// TODO re-run on each file save with content change.
let lint_report_for_unit_tests = await csv_lint(null, /*is_manual_op=*/true);
return lint_report_for_unit_tests;
}
async function run_internal_test_cmd(integration_test_options) {
if (integration_test_options && integration_test_options.check_initialization_state) {
// This mode is to ensure that the most basic operations do not cause rainbow csv to load extra (potentially heavy) code.
// Vim uses the same approach with its plugin/autoload folder layout design.
return {initialized: global_state !== null, lazy_loaded: rainbow_utils !== null};
}
if (integration_test_options && integration_test_options.check_last_rbql_report) {
return _unit_test_last_rbql_report;
}
if (integration_test_options && integration_test_options.check_last_rbql_warnings) {
return {'warnings': _unit_test_last_warnings};
}
return null;
}
async function show_warnings(warnings) {
_unit_test_last_warnings = [];
if (!warnings || !warnings.length)
return;
var active_window = vscode.window;
if (!active_window)
return null;
for (var i = 0; i < warnings.length; i++) {
// Do not "await" warning messages because the promise gets resolved only on warning dismissal.
active_window.showWarningMessage('RBQL warning: ' + warnings[i]);
}
_unit_test_last_warnings = warnings;
}
async function handle_rbql_result_file_node(text_doc, delim, policy, warnings) {
try {
await vscode.window.showTextDocument(text_doc);
} catch (error) {
show_single_line_error('Unable to open RBQL result document');
return;
}
let language_id = map_dialect_to_language_id(delim, policy);
if (language_id && text_doc.languageId != language_id) {
// In non-web version we open a new doc without preset filetype, so we need to manually set it.
await vscode.languages.setTextDocumentLanguage(text_doc, language_id);
}
await show_warnings(warnings);
}
async function handle_rbql_result_file_web(text_doc, warnings) {
try {
await vscode.window.showTextDocument(text_doc);
} catch (error) {
show_single_line_error('Unable to open RBQL result document');
return;
}
await show_warnings(warnings);
}
function command_async_wrapper(cmd, args) {
return new Promise(function (resolve, reject) {
let stdout_data = '';
let stderr_data = '';
let process = child_process.spawn(cmd, args, {'windowsHide': true});
process.stdout.on('data', function(data) {
stdout_data += data.toString();
});
process.stderr.on('data', function(data) {
stderr_data += data.toString();
});
process.on('close', function (code) { // Consider replacing 'close' with 'exit'.
resolve({'exit_code': code, 'stdout': stdout_data, 'stderr': stderr_data});
});
process.on('error', function (err) {
reject(err);
});
});
}
function get_dst_table_name(input_path, output_delim) {
var table_name = path.basename(input_path);
var orig_extension = path.extname(table_name);
var delim_ext_map = {'\t': '.tsv', ',': '.csv'};
var dst_extension = '.txt';
if (delim_ext_map.hasOwnProperty(output_delim)) {
dst_extension = delim_ext_map[output_delim];
} else if (orig_extension.length > 1) {
dst_extension = orig_extension;
}
let result_table_name = table_name + dst_extension;
if (result_table_name == table_name) { // Just being paranoid to avoid overwriting input table accidentally when output dir configured to be the same as input.
result_table_name += '.txt';
}
return result_table_name;
}
function file_path_to_query_key(file_path) {
return (file_path && file_path.indexOf(scratch_buf_marker) != -1) ? scratch_buf_marker : file_path;
}
function get_dst_table_dir(input_table_path) {
let rbql_output_dir = get_from_config('rbql_output_dir', 'TMP');
if (rbql_output_dir == 'TMP') {
return os.tmpdir();
} else if (rbql_output_dir == 'INPUT') {
return path.dirname(input_table_path);
} else {
// Return custom directory. If the directory does not exist or isn't writable RBQL itself will report more or less clear error.
return rbql_output_dir;
}
}
async function run_command_and_parse_output(cmd, args) {
let execution_result = null;
try {
execution_result = await command_async_wrapper(cmd, args);
} catch (error) {
let error_details = error ? error.name + ': ' + error.message : '';
let error_msg = 'Something went wrong. Make sure you have python installed and added to PATH variable in your OS. Or you can use it with JavaScript instead - it should work out of the box\nDetails:\n' + error_details;
return {error_type: 'Integration', error_msg: error_msg, invocation_error: 1};
}
let json_report = execution_result.stdout;
if (!json_report || execution_result.stderr) {
let error_msg = execution_result.stderr || 'empty error';
return {error_type: 'Integration', error_msg: error_msg};