-
Notifications
You must be signed in to change notification settings - Fork 5
/
insertSnippet.m
1198 lines (1013 loc) · 44.5 KB
/
insertSnippet.m
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
function insertSnippet()
% INSERTSNIPPET is the entry point to the MATLAB Snippets App.
%
% ------------------------------------------------------------------------------
% Author: Pavel Trnka ([email protected])
% Feb 2019
% ------------------------------------------------------------------------------
%#ok<*AGROW>
windowTag = 'insertSnippetWindow';
optionsFileName = 'insertSnippetOptions.mat';
versionStr = '1.0';
% --- Temporarily enable hidden handles visibility
set(0,'ShowHiddenHandles','on');
% --- Search for the hidden App window and show it if it exists ----------------
if showHiddenWindow(windowTag)
% --- Restore hidden handles visibility
set(0,'ShowHiddenHandles','remove');
% ---
return
end
% --- Initialize "nested" variables --------------------------------------------
snippets = []; % snippets subset
canDeleteWordAtCaret = []; % indicates if the word at caret can be deleted (logical)
isTextSelected = []; % indicates if user has selected some text (logical)
wordAtCaretPosition = []; % current word at the caret postion (char)
lastValidText = []; % last valid text from the code pane
h = struct(); % ui handles
current = struct();
parsedSnippet = [];
% --- Load options -------------------------------------------------------------
opt = loadOptions(optionsFileName);
% --- Ask to add to favorites --------------------------------------------------
askToAddToFavorites();
% --- Load snippets ------------------------------------------------------------
[snippets0,fileModifiedDate] = ...
Snippet.Snippet.load( opt.jsonFileNames(opt.isJsonFileEnabled) );
% --- Create figure ------------------------------------------------------------
createFigure();
% --- Initialize and show the GUI ----------------------------------------------
initializeGUI;
% --- Restore hidden handles visibility
set(0,'ShowHiddenHandles','remove');
% ==============================================================================
function createFigure()
% Creates the main figure and all UI components. Component dimensions
% and positions are not set, this is done in the figureSizeChangedFcn
% function.
%
screenSize = get(0, 'ScreenSize');
h.Fig = figure( ...
'WindowStyle', 'modal', ...
'Position', [ 0.5*screenSize(3:4)-0.5*opt.figureSize opt.figureSize ], ...
'DockControls', 'off', ...
'MenuBar', 'none', ...
'IntegerHandle', 'off', ...
'NextPlot', 'new', ...
'NumberTitle', 'off', ...
'Name', 'Insert Snippet', ...
'Tag', windowTag, ...
'Visible', 'off', ...
'HandleVisibility', 'off', ... hide the window to gca, gcf, ...
'KeyPressFcn', @figureKeyPressFcn, ...
'DeleteFcn', @figureDeleteFcn, ...
'SizeChangedFcn', @figureSizeChangedFcn, ...
'CloseRequestFcn', @figureCloseRequestFcn );
h.EditBox = uicontrol( ...
'Style','edit', ...
'HorizontalAlignment', 'left', ...
'Tooltip','Snippet filter', ...
...'Interruptible','off', ...
'KeyPressFcn',@editBoxKeyPressFcn );
h.ListBox = uicontrol( ...
'Style','listbox', ...
'Tooltip','Snippet list', ...
'Callback', @listBoxCallback);
h.Hint = uicontrol( ...
'Style','text', ...
'Enable','inactive', ...
'HorizontalAlignment', 'left', ...
'FontSize', 10 );
updateHint('EditBox');
h.ButtonConfig = uicontrol( ...
'Style','pushbutton', ...
'TooltipString','Configuration', ...
'Callback',@buttonConfigCallback);
h.ButtonAbout = uicontrol( ...
'Style','pushbutton',...
'TooltipString','About MATLAB Snippets', ...
'Callback',@buttonAboutCallback);
h.ButtonHelp = uicontrol( ...
'Style','pushbutton',...
'TooltipString','Open documentation in the web browser.', ...
'Callback',@buttonHelpCallback);
% --- Code pane
h.CodePane = com.mathworks.widgets.SyntaxTextPane;
codeType = com.mathworks.widgets.text.mcode.MLanguage.M_MIME_TYPE;
h.CodePane.setContentType(codeType);
jScrollPane = com.mathworks.mwswing.MJScrollPane(h.CodePane);
% ---
oldWarn = warning('off','MATLAB:HandleGraphics:ObsoletedProperty:JavaFrame');
warning('off','MATLAB:ui:javaframe:PropertyToBeRemoved');
warning('off','MATLAB:ui:javacomponent:FunctionToBeRemoved');
[~,h.CodePaneContainer] = javacomponent(jScrollPane,[0 0 0 0],h.Fig);
warning(oldWarn);
% ---
% --- Add code pane to the <TAB> cycle
h.CodePane.setFocusable(true);
h.CodePane.putClientProperty('TabCycleParticipant', true);
% --- Move code pane right after edit box in the <TAB> cycle
uistack(h.ListBox,'bottom');
uistack(h.ButtonConfig,'bottom');
uistack(h.ButtonAbout,'bottom');
uistack(h.ButtonHelp,'bottom');
% --- Code pane callbacks
h.jhCodePane = handle(h.CodePane,'CallbackProperties');
set(h.jhCodePane, 'KeyPressedCallback',@codePaneKeyPressedCallback);
set(h.jhCodePane, 'KeyTypedCallback',@codePaneKeyTypedCallback); % printable characters only
set(h.jhCodePane, 'FocusGainedCallback',@codePaneFocusGainedCallback);
% --- !!!
h.CodePaneContainer.Interruptible = 'off';
% --- Unify editbox and listbox font with the CodePane
fnt = h.CodePane.getFont;
fontName = get(fnt,'Name');
fontExist = any(strcmp(listfonts,fontName));
if fontExist
h.ListBox.FontName = fontName;
h.EditBox.FontName = fontName;
end
pxFontSize = fnt.getSize;
ScreenPixelsPerInch = java.awt.Toolkit.getDefaultToolkit().getScreenResolution(); % unscaled
%ScreenPixelsPerInch = get(0,'ScreenPixelsPerInch'); % scaled
ptFontSize = pxFontSize * 72 / ScreenPixelsPerInch;
h.ListBox.FontSize = ptFontSize;
h.EditBox.FontSize = ptFontSize;
% --- Unify editbox and listbox colors with the CodePane
jbcol = h.CodePane.getBackground;
bcol = [jbcol.getRed jbcol.getGreen jbcol.getBlue]/255;
jfcol = h.CodePane.getCaretColor;
fcol = [jfcol.getRed jfcol.getGreen jfcol.getBlue]/255;
h.EditBox.BackgroundColor = bcol;
h.EditBox.ForegroundColor = fcol;
h.ListBox.BackgroundColor = bcol;
h.ListBox.ForegroundColor = fcol;
% --- Config button image
[~,~,transparency]=imread('configure_16_16.png');
bgcol = [];
bgcol(1,1,:) = h.ButtonConfig.BackgroundColor;
img = repmat(bgcol,size(transparency,1),size(transparency,2));
transparency = repmat(transparency,1,1,3);
img = uint8(img.*double(255-transparency));
h.ButtonConfig.CData = img;
% --- About button image
[A,map]=imread('about_16_16.png');
map(A(1,1)+1,:) = h.ButtonConfig.BackgroundColor;
img = ind2rgb(A,map);
h.ButtonAbout.CData = img;
% --- Help button image
img=imread('help_16_16.png');
img = replaceWhiteColor(img,250,255*0.95*h.ButtonConfig.BackgroundColor);
h.ButtonHelp.CData = img;
% --- Userdata
ud = struct( ...
'showWindowFH',@showWindow);
set(h.Fig,'Userdata',ud);
end
% ==============================================================================
function figureSizeChangedFcn(src,~)
margin = 5;
editBoxHeight = 25;
lPanelRatio = 3/8;
hintHeight = 17+3;
figSize = src.Position(3:4);
buttonSize = 16+6;
h.EditBox.Position = [
margin
figSize(2)-editBoxHeight-margin
lPanelRatio*figSize(1)-1.5*margin
editBoxHeight ]';
h.ListBox.Position = [
margin
hintHeight+2*margin
lPanelRatio*figSize(1)-1.5*margin
figSize(2)-editBoxHeight-hintHeight-4*margin
]';
hintWidth = figSize(1)-3*margin-4.00*buttonSize;
h.Hint.Position = [
margin
margin - 1
hintWidth
hintHeight
]';
h.CodePaneContainer.Position = [
lPanelRatio*figSize(1)+0.5*margin
hintHeight+2*margin
(1-lPanelRatio)*figSize(1)-1.5*margin
figSize(2)-hintHeight-3*margin
];
h.ButtonConfig.Position = [
sum(h.CodePaneContainer.Position([1 3]))-3.75*buttonSize
margin
1.25*buttonSize
buttonSize
]';
h.ButtonAbout.Position = [
sum(h.CodePaneContainer.Position([1 3]))-2.5*buttonSize
margin
1.25*buttonSize
buttonSize
]';
h.ButtonHelp.Position = [
sum(h.CodePaneContainer.Position([1 3]))-1.25*buttonSize
margin
1.25*buttonSize
buttonSize
]';
end
% ==============================================================================
function figureCloseRequestFcn(~,~)
if opt.keepWindowLoaded
h.Fig.Visible = 'off';
else
delete(h.Fig);
end
end
% ==============================================================================
function figureDeleteFcn(~,~)
% --- Store current figure size to the options
opt.figureSize = h.Fig.Position(3:4);
% --- Save options
filePath = fileparts(mfilename('fullpath'));
fullFileName = [ filePath filesep optionsFileName ];
save(fullFileName,'opt');
end
% ==============================================================================
function initializeGUI
% INITIALIZEGUI resets the GUI to the default state
%
canDeleteWordAtCaret = true;
% --- User has selected some text in the active editor -> show only
% --- snippets that include the selected text variable and vice versa.
isTextSelected = ~isempty(Snippet.Variable.selectedText);
filterByWordAtCaretPosition = true;
if opt.filterSnippetsIfTextSelected
if isTextSelected
filterByWordAtCaretPosition = false;
canDeleteWordAtCaret = false;
sel = [snippets0.usesSelectedText];
else
sel = ~[snippets0.usesSelectedText];
end
snippets = snippets0( sel );
else
snippets = snippets0;
end
% --- Test the word at the caret position for an exact match with some
% --- snippet prefix.
wordAtCaretPosition = getWordAtCaretPosition();
[isPerfectMatch, hasTabstops, noMatch] = ...
checkForPerfectPrefixMatch(wordAtCaretPosition);
if isPerfectMatch && ~hasTabstops
% --- Perfect prefix match for a snippet without tabstops
parsedSnippetText = parsedSnippet.toChar();
insertToEditor(parsedSnippetText,true);
return
end
if noMatch
% --- Try again partial match
list = {snippets.prefix};
ind = filterList(wordAtCaretPosition,list,opt.filterMode);
if isempty(ind)
% --- Do not filter by word at the caret if there is no match with snippet prefixes
filterByWordAtCaretPosition = false;
end
end
% --- Initialize the snippet filter
if filterByWordAtCaretPosition
h.EditBox.String = wordAtCaretPosition;
else
h.EditBox.String = '';
end
h.EditBox.Value = 1;
% --- Focus the edit box (it will also select the edit box text)
uicontrol(h.EditBox); % it will also make the hidden window visible
% --- Disable the edit box text selection so that the user can
% --- continue to type the snippet prefix
h.jEditBox = findjobj_fast(h.Fig,'Snippet filter');
h.jEditBox.SelectionEnd = h.jEditBox.CaretPosition;
h.jEditBox.SelectionStart = h.jEditBox.CaretPosition;
% --- Update the list box and the code pane
updateListBox();
updateCodePane();
lastValidText = [];
current = struct();
parsedSnippet = [];
if isPerfectMatch
% --- Select the perfectly matched snippet in the list
list = h.ListBox.UserData;
ilist = find(strcmp(list,wordAtCaretPosition),1);
if ~isempty(ilist)
h.ListBox.Value = ilist(1);
end
% --- Perfect match for a snippet with tabstops - switch focus to the code pane
requestFocus(h.jhCodePane);
end
end
% ==============================================================================
function askToAddToFavorites()
if opt.askToAddToFavorites
answer = questdlg('Do you want to create a shortcut on the Quick Access Toolbar so you can insert snippets by using the keyboard shortcut ALT+1? The app will be more or less useless without a keyboard shortcut.', ...
'Matlab Snippets', ...
'Yes','No','Yes');
if strcmp(answer,'Yes')
addToFavorites();
end
% --- Do not ask again
opt.askToAddToFavorites = false;
% --- Save options
filePath = fileparts(mfilename('fullpath'));
fullFileName = [ filePath filesep optionsFileName ];
save(fullFileName,'opt');
end
end
% ==============================================================================
function figureKeyPressFcn(~,keyData)
switch keyData.Key
case 'escape'
close(h.Fig);
return
end
end
% ==============================================================================
function editBoxKeyPressFcn(~,keyData)
switch keyData.Key
case 'escape'
close(h.Fig);
return
case 'uparrow'
h.ListBox.Value = max( h.ListBox.Value-1, 1 );
case 'downarrow'
h.ListBox.Value = min( h.ListBox.Value+1, length(h.ListBox.String) );
case 'pageup'
if isempty(keyData.Modifier)
nSkip = pageUpDownSkipSize();
h.ListBox.Value = max( h.ListBox.Value-nSkip, 1 );
elseif all(strcmp(keyData.Modifier,'control'))
h.ListBox.Value = 1;
end
case 'pagedown'
if isempty(keyData.Modifier)
nSkip = pageUpDownSkipSize();
h.ListBox.Value = min( h.ListBox.Value+nSkip, length(h.ListBox.String) );
elseif all(strcmp(keyData.Modifier,'control'))
h.ListBox.Value = length(h.ListBox.String);
end
case 'return'
iSnippet = getSelectedSnippetIndex();
if ~isempty(iSnippet)
parsedSnippet = Snippet.Snippet( snippets(iSnippet).body );
parsedSnippetText = parsedSnippet.toChar();
insertToEditor(parsedSnippetText);
close(h.Fig);
return
end
otherwise
updateListBox();
end
updateCodePane();
function nSkip = pageUpDownSkipSize()
itemSizePx = 1.3*h.ListBox.FontSize/72*96+2; % +/-
nSkip = round(h.ListBox.Position(4) / itemSizePx);
end
end
% ==============================================================================
function updateListBox()
% Updates a list of snippets in the list box according to the filter.
%
filter = h.jEditBox.Text; % h.EditBox.String is not updated until <ENTER>
list = {snippets.prefix};
description = {snippets.description};
lastItem = '';
if ~isempty(h.ListBox.UserData)
lastItem = h.ListBox.UserData{h.ListBox.Value};
end
[ind,pattern] = filterList(filter,list,opt.filterMode);
filteredList = list(ind);
filteredDescription = description(ind);
if isempty(ind)
h.ListBox.Value = 1;
h.ListBox.String = {'<html><i><no match></i></html>'};
h.ListBox.UserData = {};
else
listBoxValue = 1;
% --- try to keep the last item selected
ilastItem = find(strcmp(filteredList,lastItem));
if ~isempty(ilastItem)
listBoxValue = ilastItem;
end
% --- Emphasize characters matched by the filter
switch 3
case 1
prefix = '<b>';
postfix = '</b>';
case 2
prefix = '<font color="rgb(255,255,0)"><b>';
postfix = '</b></font>';
case 3
prefix = '<font color="rgb(0,200,0)"><b>';
postfix = '</b></font>';
end
filteredListTokens = ...
regexpi(filteredList,['(.*?)(' pattern ')(.*)'],'tokens');
filteredListHTML = cellfun( ...
@(c1,c2) ...
['<html>' c1{1}{1} prefix c1{1}{2} postfix c1{1}{3} ...
' <font color="rgb(135,135,135)"><i>(' c2 ')</font></i>' ...
'</html>'], ...
filteredListTokens, ...
filteredDescription, ...
'UniformOutput',false);
% ---
h.ListBox.String = filteredListHTML;
h.ListBox.UserData = filteredList;
if ~isempty(h.ListBox.String)
h.ListBox.Value = listBoxValue;
end
end
end
% ==============================================================================
function updateCodePane()
% --- Previews the currently selected snippet in the code pane
iSnippet = getSelectedSnippetIndex();
codePaneText = '';
if ~isempty(iSnippet)
switch opt.previewMode
case 'RAW'
codePaneText = snippets(iSnippet).body;
case {'PARSED','EMPHASIZE_PLACEHOLDERS'}
parsedSnippet = Snippet.Snippet( snippets(iSnippet).body );
% --- Emphasize editable tabstops
if strcmp(opt.previewMode,'EMPHASIZE_PLACEHOLDERS')
tabstopNumbers = parsedSnippet.getTabstopNumbers();
for tabstopNumber = tabstopNumbers(:)'
if tabstopNumber==0
continue
end
tabstop = parsedSnippet.getTabstopObject(tabstopNumber);
if isprop(tabstop,'value') && ~isa(tabstop,'Snippet.Element.Regexp')
if ~ischar(tabstop.value)
tabstop.value = Snippet.Element.Array( { ...
Snippet.Element.Text('`') ...
tabstop.value ...
Snippet.Element.Text('´') ...
});
elseif ischar(tabstop.value)
tabstop.value = ['`' tabstop.value '´'];
end
end
end
end
% ---
codePaneText = parsedSnippet.toChar();
otherwise
error(['Unkown snippet preview mode "' opt.previewMode '".']);
end
end
h.CodePane.setText(codePaneText);
end
% ==============================================================================
function iSnippet = getSelectedSnippetIndex()
% Returns the index of the currently selected snippet.
% Outputs:
% iSnippet ... currently selected snippet as an index in the
% "snippets" array
%
iSnippet = [];
if ~isempty(h.ListBox.UserData)
snippetPrefix = h.ListBox.UserData{h.ListBox.Value};
iSnippet = find(strcmp(snippetPrefix,{snippets.prefix}));
if isempty(iSnippet)
error(['Cannot find snippet with prefix "' sbuooetPrefix '".']);
end
if length(iSnippet)>1
warning(['There are multiple snippets with the same prefix "' snippetPrefix '".']);
iSnippet = iSnippet(1);
end
end
end
% ==============================================================================
function listBoxCallback(~,~)
uicontrol(h.EditBox);
updateHint('EditBox');
updateCodePane();
end
% ==============================================================================
function codePaneFocusGainedCallback(~,~)
% Code pane focus callback - starts snippet tabstop editing mode
iSnippet = getSelectedSnippetIndex();
if ~isempty(iSnippet)
parsedSnippet = Snippet.Snippet( snippets(iSnippet).body );
parsedSnippetText = parsedSnippet.toChar();
parsedSnippetTabstopNumbers = parsedSnippet.getTabstopNumbers();
if isempty(parsedSnippetTabstopNumbers) || isequal(parsedSnippetTabstopNumbers,0)
% --- snippet without tabstops
insertToEditor( parsedSnippetText );
close(h.Fig);
return
end
tabstopNumbers = parsedSnippetTabstopNumbers( parsedSnippetTabstopNumbers>0 );
tabstopNumber = tabstopNumbers(1);
tabstopObject = parsedSnippet.getTabstopObject(tabstopNumber);
tabstopObjectClass = class(tabstopObject);
h.CodePane.setText( parsedSnippetText );
lastValidText = parsedSnippetText;
[iStart,iEnd] = parsedSnippet.getPlaceholderPosition(tabstopNumber);
h.CodePane.setSelectionStart( iStart(1)-1 );
h.CodePane.setSelectionEnd( iEnd(1) );
current.tabstopNumber = tabstopNumber;
current.tabstopObject = tabstopObject;
current.tabstopObjectClass = tabstopObjectClass;
current.prefix = parsedSnippetText( 1 : iStart(1)-1 );
current.postfix = parsedSnippetText( iEnd(1)+1 : end );
current.lastValidCaretPosition = h.CodePane.getCaretPosition;
current.parameterValue = parsedSnippet.getPlaceholder(tabstopNumber);
updateHint('CodePane');
else
% --- no snippet selected - return focus to the edit box
uicontrol(h.EditBox);
end
end
% ==============================================================================
function codePaneKeyPressedCallback(~,keyData)
% Code pane key typed callback for all keys
if isstruct(current) && isfield(current,'tabstopObjectClass') ...
&& strcmp(current.tabstopObjectClass,'Snippet.Element.TabstopMultiChoice')
choice = [];
switch char(keyData.getKeyText(keyData.getKeyCode))
case 'Up'
choice = current.tabstopObject.getPreviousChoice();
case 'Down'
choice = current.tabstopObject.getNextChoice();
end
if ~isempty(choice)
tabstopNumber = current.tabstopNumber;
parsedSnippet.setPlaceholder(tabstopNumber,choice);
parsedSnippetText = parsedSnippet.toChar();
h.CodePane.setText( parsedSnippetText );
lastValidText = parsedSnippetText;
[iStart,iEnd] = parsedSnippet.getPlaceholderPosition(tabstopNumber);
h.CodePane.setSelectionStart( iStart(1)-1 );
h.CodePane.setSelectionEnd( iEnd(1) );
current.prefix = parsedSnippetText( 1 : iStart(1)-1 );
current.postfix = parsedSnippetText( iEnd(1)+1 : end );
current.lastValidCaretPosition = h.CodePane.getCaretPosition;
current.parameterValue = parsedSnippet.getPlaceholder(tabstopNumber);
end
end
end
% ==============================================================================
function codePaneKeyTypedCallback(~,keyData)
% Code pane key typed callback for printable characters
switch double(keyData.getKeyChar)
case 9 % TAB
h.CodePane.setText(lastValidText); % undo tab key action in the editor
parsedSnippetText = parsedSnippet.toChar();
tabstopNumbers = parsedSnippet.getTabstopNumbers();
% --- Select next tabstop number
keyModifiers = char( keyData.getKeyModifiersText(keyData.getModifiers) );
if isempty(keyModifiers)
% --- TAB
selectedTabstopNumbers = ...
tabstopNumbers( tabstopNumbers>current.tabstopNumber );
if isempty(selectedTabstopNumbers)
insertToEditor(parsedSnippetText);
close(h.Fig);
return
else
tabstopNumber = selectedTabstopNumbers(1);
end
elseif strcmpi(keyModifiers,'Shift')
% --- Shift+TAB
selectedTabstopNumbers = ...
tabstopNumbers( 0<tabstopNumbers & tabstopNumbers<current.tabstopNumber );
if isempty(selectedTabstopNumbers)
%tabstopNumber = current.tabstopNumber;
uicontrol(h.EditBox);
% --- Disable edit box text selection
drawnow;
h.jEditBox.SelectionEnd = h.jEditBox.CaretPosition;
h.jEditBox.SelectionStart = h.jEditBox.CaretPosition;
% ---
updateCodePane();
updateHint('EditBox');
return
else
tabstopNumber = selectedTabstopNumbers(end);
end
else
% --- Unkown key modifier
return
end
if ~isempty(tabstopNumber)
[iStart,iEnd] = parsedSnippet.getPlaceholderPosition(tabstopNumber);
tabstopObject = parsedSnippet.getTabstopObject(tabstopNumber);
tabstopObjectClass = class(tabstopObject);
h.CodePane.setSelectionStart(iStart(1)-1);
h.CodePane.setSelectionEnd(iEnd(1));
current.tabstopNumber = tabstopNumber;
current.tabstopObject = tabstopObject;
current.tabstopObjectClass = tabstopObjectClass;
current.prefix = parsedSnippetText( 1 : iStart(1)-1 );
current.postfix = parsedSnippetText( iEnd(1)+1 : end );
current.lastValidCaretPosition = h.CodePane.getCaretPosition;
current.parameterValue = parsedSnippet.getPlaceholder(tabstopNumber);
updateHint('CodePane');
return
end
case 10 % ENTER
keyModifiers = char( keyData.getKeyModifiersText(keyData.getModifiers) );
if isempty(keyModifiers)
% ENTER without modifiers only (Shift+ENTER can be used to separate lines)
h.CodePane.setText(lastValidText); % undo enter key action in the editor
parsedSnippetText = parsedSnippet.toChar();
insertToEditor(parsedSnippetText);
close(h.Fig);
return
end
case 27 % ESCAPE
close(h.Fig);
return
end
% --- (!) Disable edit mode for a moment so that a fast type user does not
% --- change the text while we are mirroring tabstops.
h.CodePane.setEditable(false);
% ---
text = char( h.CodePane.getText );
% --- Fix: sometimes (?) getText returns char([13 10]) instead of char(10)
text = strrep(text,char([13 10]),char(10)); %#ok<*CHARTEN>
current.prefix = strrep(current.prefix,char([13 10]),char(10));
current.postfix = strrep(current.postfix,char([13 10]),char(10));
% --- Check user input validity
parameterLength = ...
length(text) - ( length(current.prefix) + length(current.postfix) );
isValid = startsWith_(text,current.prefix) ...
&& endsWith_(text,current.postfix) ...
&& parameterLength>=0;
if strcmp(current.tabstopObjectClass,'Snippet.Element.TabstopMultiChoice')
isValid = false;
end
if isValid
% --- Update parameter(s)
parameterValue = text( ...
length(current.prefix)+1 ...
: ...
length(text)-length(current.postfix) );
parsedSnippet.setPlaceholder(current.tabstopNumber,parameterValue);
%if length(parsedSnippet.getPlaceholderPosition(current.tabstopNumber))>1
if parsedSnippet.isMirrored(current.tabstopNumber)
% --- Update text for multiple tabstops with the same number
parsedSnippetText = parsedSnippet.toChar();
caretPosition = h.CodePane.getCaretPosition;
h.CodePane.setText(parsedSnippetText);
% ---
[iStart,iEnd] = parsedSnippet.getPlaceholderPosition(current.tabstopNumber);
caretPosition = caretPosition + (iStart(1)-1) - length(current.prefix); % compensate prefix length change
current.prefix = parsedSnippetText( 1 : iStart(1)-1 );
current.postfix = parsedSnippetText( iEnd(1)+1 : end );
% ---
h.CodePane.setCaretPosition(caretPosition);
end
% ---
current.parameterValue = parameterValue;
else
% --- Return to the previous valid input
h.CodePane.setText(lastValidText);
h.CodePane.setCaretPosition(current.lastValidCaretPosition);
end
if strcmp(current.tabstopObjectClass,'Snippet.Element.TabstopMultiChoice')
[iStart,iEnd] = parsedSnippet.getPlaceholderPosition(current.tabstopNumber);
h.CodePane.setSelectionStart( iStart(1)-1 );
h.CodePane.setSelectionEnd( iEnd(1) );
end
% --- (!) Enable the edit mode
h.CodePane.setEditable(true);
% ---
lastValidText = h.CodePane.getText;
current.lastValidCaretPosition = h.CodePane.getCaretPosition;
% ---
updateHint('CodePane');
end
% ==============================================================================
function updateHint(currentFocus)
switch currentFocus
case 'EditBox'
h.Hint.String = 'Start typing to filter snippets, <UP/DOWN> select a snippet, <TAB> edit snippet tabstops, <ENTER> insert to the editor.';
case 'CodePane'
tabstopNumbers = parsedSnippet.getTabstopNumbers();
tabstopNumbers = tabstopNumbers( tabstopNumbers>0 );
tabstopNumber = current.tabstopNumber;
switch current.tabstopObjectClass
case 'Snippet.Element.TabstopMultiChoice'
str = '<UP/DOWN> select placeholder choice';
otherwise
str = 'Start typing to modify tabstop placeholder';
end
if any( tabstopNumbers > tabstopNumber )
str = [ str ...
', <TAB> next tabstop' ];
else
str = [ str ...
', <TAB> insert to the editor' ];
end
if any( tabstopNumbers < tabstopNumber )
str = [ str ...
', <Shift+TAB> previous tabstop' ];
else
str = [ str ...
', <Shift+TAB> snippet selection' ];
end
str = [ str ...
', <ENTER> insert to the editor' ];
h.Hint.String = [ str '.' ];
end
end
% ==============================================================================
function [isPerfectMatch,hasTabstops,noMatch] = checkForPerfectPrefixMatch(prefix)
isPerfectMatch = false;
hasTabstops = true;
noMatch = false;
% --- Test perfect match
prefixes = {snippets.prefix};
ind = find(strcmp(prefixes,prefix));
if length(ind)==1
isPerfectMatch = true;
% ---
parsedSnippet = Snippet.Snippet( snippets(ind).body );
tabstopNumbers = parsedSnippet.getTabstopNumbers();
if isempty( tabstopNumbers(tabstopNumbers>0) )
hasTabstops = false;
end
end
% --- Test that at least the first character matches some snippet
ind = find(strncmp(prefixes,prefix,1),1);
if isempty(ind)
noMatch = true;
end
end
% ==============================================================================
function insertToEditor(text,alwaysDeleteWordAtCaret)
if isa(text,'java.lang.String')
text = char(text);
end
if nargin<2
alwaysDeleteWordAtCaret = false;
end
% --- Indentation string
if isTextSelected
% --- Do not add extra indentation if text is selected (needed for
% --- alignment commands)
indentationStr = '';
else
% --- Use indentation from the line at caret position
lineAtCaret = getLineAtCaretPosition();
tokens = regexp(lineAtCaret,'^([ ]*)','tokens','once');
if isempty(tokens)
indentationStr = '';
else
indentationStr = tokens{1};
end
end
% --- Indent all lines except the first one
indNewLine = regexp(text,'\n');
text = regexprep(text,'\n',['$0' indentationStr]);
if canDeleteWordAtCaret
if alwaysDeleteWordAtCaret
clearWordAtCaretPosion();
else
% --- Delete word at caret position only if it matches with the
% --- begining of the selected snippet prefix and if this function
% --- is enabled
if opt.deletePartiallyMatchingWordAtCaret
iSnippet = getSelectedSnippetIndex();
if ~isempty(iSnippet)
snippetFrefix = snippets(iSnippet).prefix;
if startsWith_(snippetFrefix,wordAtCaretPosition)
clearWordAtCaretPosion();
end
end
end
end
end
activeEditor = getActiveEditor();
if ~isempty(activeEditor)
% --- Get tabstop $0 position
caretPosition = activeEditor.JavaEditor.getCaretPosition;
indCaret = parsedSnippet.getPlaceholderPosition(0);
if ~isempty(indCaret)
indCaret = indCaret(1);
% --- Shift caret postion by additional indentation
indCaret = indCaret + sum(indNewLine<indCaret) * length(indentationStr);
end
% --- Insert text to the editor
activeEditor.JavaEditor.insertTextAtCaret(text);
% --- Move the caret to the $0 tabstop
if ~isempty(indCaret)
activeEditor.JavaEditor.setCaretPosition( caretPosition + indCaret - 1 );
end
end
end
% ==============================================================================
function buttonConfigCallback(~,~)
opt_ = opt;
[opt,closeRequest] = insertSnippetOptionsDlg(opt);
if ~isequal(opt,opt_)
% --- Save options
filePath = fileparts(mfilename('fullpath'));
fullFileName = [ filePath filesep optionsFileName ];
save(fullFileName,'opt');
% --- Load snippets
[snippets0, fileModifiedDate] = ...
Snippet.Snippet.load( opt.jsonFileNames(opt.isJsonFileEnabled) );
% --- Re-initialize GUI
initializeGUI();
end
if closeRequest
close(h.Fig);
end
end
% ==============================================================================
function buttonAboutCallback(~,~)
insertSnippetAboutDlg(versionStr);
end
% ==============================================================================
function buttonHelpCallback(~,~)
web('matlabSnippets.html');
end
% ==============================================================================
function showWindow
% --- Load snippets definition file if modified
fileModifiedDate_ = {};
for ifile = 1 : length(opt.jsonFileNames)
if opt.isJsonFileEnabled(ifile)