-
Notifications
You must be signed in to change notification settings - Fork 32
/
PluginDefinition.cpp
6643 lines (5491 loc) · 238 KB
/
PluginDefinition.cpp
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
//This file is part of FingerText, a notepad++ snippet plugin.
//
//FingerText is released under MIT License.
//
//MIT license
//
//Copyright (C) 2011 by Tom Lam
//
//Permission is hereby granted, free of charge, to any person
//obtaining a copy of this software and associated documentation
//files (the "Software"), to deal in the Software without
//restriction, including without limitation the rights to use,
//copy, modify, merge, publish, distribute, sublicense, and/or
//sell copies of the Software, and to permit persons to whom the
//Software is furnished to do so, subject to the following
//conditions:
//
//The above copyright notice and this permission notice shall be
//included in all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
//EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
//OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
//NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
//HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
//WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
//DEALINGS IN THE SOFTWARE.
#include "PluginDefinition.h"
// Notepad++ API stuffs
FuncItem funcItem[MENU_LENGTH]; // The menu item data that Notepad++ needs
NppData nppData; // The data for plugin command and sending message to notepad++
HANDLE g_hModule; // the hModule from pluginInit for initializing dialogs
HWND g_customSciHandle;
WNDPROC wndProcNpp = NULL;
// Status dummies
int nppLoaded = 0; // Indicates NPP_READY has triggered
int sciFocus = 1; // Indicates the current focus is on the editor
// Sqlite3
sqlite3 *g_db; // For Sqlite3
bool g_dbOpen; // For Sqlite3
// Paths
wchar_t g_basePath[MAX_PATH];
TCHAR g_ftbPath[MAX_PATH];
TCHAR g_fttempPath[MAX_PATH];
TCHAR g_currentFocusPath[MAX_PATH];
//TCHAR g_backupPath[MAX_PATH];
TCHAR g_downloadPath[MAX_PATH];
// Config object
PluginConfig pc;
// Dialogs
DockingDlg snippetDock;
InsertionDlg insertionDlg;
SettingDlg settingDlg;
CreationDlg creationDlg;
// Need a record for all the cmdIndex that involve a dock or a shortkey
int g_snippetDockIndex;
int g_tabActivateIndex;
int g_showInsertionDlgIndex;
int g_toggleDisableIndex;
int g_selectionToSnippetIndex;
int g_importSnippetsIndex;
int g_exportSnippetsIndex;
int g_deleteAllSnippetsIndex;
int g_downloadDefaultPackageIndex;
int installDefaultPackageIndex;
int g_installDefaultPackageIndex;
int g_TriggerTextCompletionIndex;
int g_InsertHotspotIndex;
int g_insertPreviousIndex;
int g_settingsIndex;
int g_quickGuideIndex;
int g_aboutIndex;
std::string g_lastTriggerText = "";
std::string g_lastOption = "";
std::string g_lastListItem = "";
bool g_onHotSpot = false;
// For compatibility mode
HHOOK hook = NULL;
struct SnipIndex
{
std::string triggerText;
std::string scope;
std::string content;
};
std::vector<SnipIndex> g_snippetCache;
bool g_modifyResponse = true;
int g_selectionMonitor = 1;
bool g_rectSelection = false;
bool g_freezeDock = false;
bool g_enable = true;
bool g_editorView;
int g_editorLineCount;
std::string g_snippetCount = "";
bool g_fingerTextList;
int g_lastTriggerPosition = 0;
std::string g_customClipBoard = "";
std::string g_selectedText = "";
// For option hotspot
bool g_optionMode = false;
int g_optionStartPosition = 0;
int g_optionEndPosition = 0;
int g_optionCurrent = 0;
std::vector<std::string> g_optionArray;
// List of acceptable tagSigns
char *g_tagSignList[] = {"$[0[","$[![","$[1[","$[2[","$[3["};
char *g_tagTailList[] = {"]0]","]!]","]1]","]2]","]3]"};
char* g_stopCharArray;
int g_listLength = 5;
//For params insertion
std::vector<std::string> g_hotspotParams;
//support the languages supported by npp 0.5.9, excluding "user defined language" abd "search results"
const std::string langList[] = {"TXT","PHP","C","CPP","CS","OBJC","JAVA","RC",
"HTML","XML","MAKEFILE","PASCAL","BATCH","INI","NFO","",
"ASP","SQL","VB","JS","CSS","PERL","PYTHON","LUA",
"TEX","FORTRAN","BASH","FLASH","NSIS","TCL","LISP","SCHEME",
"ASM","DIFF","PROPS","PS","RUBY","SMALLTALK","VHDL","KIX",
"AU3","CAML","ADA","VERILOG","MATLAB","HASKELL","INNO","",
"CMAKE","YAML","COBOL","GUI4CLI","D","POWERSHELL","R"};
// The word char settings for scope and triggertext
const char* scopeWordChar = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_:.|";
const char* triggertextWordChar = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-^";
const char* searchWordChar = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-";
char escapeWordChar[200];
//For SETWIN
HWND g_tempWindowHandle;
wchar_t* g_tempWindowKey;
//TODO: Add icon to messageboxes
// Initialize your plugin data here. Called while plugin loading. This runs before setinfo.
void pluginInit(HANDLE hModule)
{
g_hModule = hModule; // For dialogs initialization
}
void dialogsInit()
{
snippetDock.init((HINSTANCE)g_hModule, nppData._nppHandle);
insertionDlg.init((HINSTANCE)g_hModule, nppData);
settingDlg.init((HINSTANCE)g_hModule, nppData);
creationDlg.init((HINSTANCE)g_hModule, nppData);
}
void pathInit()
{
// Get the config folder of notepad++ and append the plugin name to form the root of all config files
::SendMessage(nppData._nppHandle, NPPM_GETPLUGINSCONFIGDIR, MAX_PATH, reinterpret_cast<LPARAM>(g_basePath));
::_tcscat_s(g_basePath,TEXT("\\"));
::_tcscat_s(g_basePath,TEXT(PLUGIN_NAME));
if (!PathFileExists(g_basePath)) ::CreateDirectory(g_basePath, NULL);
// Initialize the files needed (ini and database paths are initalized in configInit and databaseInit)
::_tcscpy_s(g_fttempPath,g_basePath);
::_tcscat_s(g_fttempPath,TEXT("\\"));
::_tcscat_s(g_fttempPath,TEXT(PLUGIN_NAME));
::_tcscat_s(g_fttempPath,TEXT(".fttemp"));
if (!PathFileExists(g_fttempPath)) emptyFile(g_fttempPath);
::_tcscpy_s(g_ftbPath,g_basePath);
::_tcscat_s(g_ftbPath,TEXT("\\SnippetEditor.ftb"));
if (!PathFileExists(g_ftbPath)) emptyFile(g_ftbPath);
//::_tcscpy_s(g_backupPath,g_basePath);
//::_tcscat_s(g_backupPath,TEXT("\\SnippetsBackup.ftd"));
//if (!PathFileExists(g_backupPath)) emptyFile(g_backupPath);
::_tcscpy_s(g_downloadPath,g_basePath);
::_tcscat_s(g_downloadPath,TEXT("\\SnippetsDownloaded.ftd"));
if (!PathFileExists(g_downloadPath)) emptyFile(g_downloadPath);
}
void configInit()
{
::_tcscpy_s(pc.iniPath,g_basePath);
::_tcscat_s(pc.iniPath,TEXT("\\"));
::_tcscat_s(pc.iniPath,TEXT(PLUGIN_NAME));
::_tcscat_s(pc.iniPath,TEXT(".ini"));
if (PathFileExists(pc.iniPath) == false) emptyFile(pc.iniPath);
pc.configSetUp();
}
void dataBaseInit()
{
char* dataBasePath = new char[MAX_PATH];
char* basePath = toCharArray(g_basePath);
strcpy(dataBasePath,basePath);
strcat(dataBasePath,"\\");
strcat(dataBasePath,PLUGIN_NAME);
strcat(dataBasePath,".db3");
delete [] basePath;
bool dbError = sqlite3_open(dataBasePath, &g_db);
if (dbError)
{
g_dbOpen = false;
showMessageBox(TEXT("Cannot find or open database file in config folder"));
} else
{
g_dbOpen = true;
}
delete [] dataBasePath;
if (!g_dbOpen) return;
sqlite3_stmt *stmt;
if (SQLITE_OK == sqlite3_prepare_v2(g_db,
"CREATE TABLE snippets (tag TEXT, tagType TEXT, snippet TEXT, package TEXT)"
, -1, &stmt, NULL))
{
sqlite3_step(stmt);
}
sqlite3_finalize(stmt);
//TODO: a checking on new update can be done by calling pc.newUpdate == false
// for those who upgrade from old database
if (SQLITE_OK == sqlite3_prepare_v2(g_db,
"ALTER TABLE snippets ADD COLUMN package TEXT"
, -1, &stmt, NULL))
{
sqlite3_step(stmt);
}
sqlite3_finalize(stmt);
//alert(pc.version);
//alert(pc.versionOld);
}
// Initialization of plugin commands
void commandMenuInit()
{
ShortcutKey *shKey;
TCHAR* tabActivateText;
if (!(pc.configInt[USE_NPP_SHORTKEY]))
{
shKey = NULL;
tabActivateText = TEXT("Hotkey remapping disabled (use TAB to trigger snippet)");
} else
{
shKey = setShortCutKey(false,false,false,VK_TAB);
tabActivateText = TEXT("Trigger Snippet/Navigate to Hotspot");
}
ShortcutKey *shKey2;
shKey2 = setShortCutKey(true,false,false,VK_OEM_2);
//shKey2 = setShortCutKey(true,false,false,190);
g_tabActivateIndex = setCommand(tabActivateText, tabActivate, shKey);
setCommand();
g_snippetDockIndex = setCommand(TEXT("Toggle On/off SnippetDock"), showSnippetDock);
g_showInsertionDlgIndex = setCommand(TEXT("Show Snippet Insertion Dialog"), showInsertionDlg,shKey2);
g_toggleDisableIndex = setCommand(TEXT("Toggle On/Off FingerText"), toggleDisable);
setCommand();
g_selectionToSnippetIndex = setCommand(TEXT("Create Snippet from Selection"), doSelectionToSnippet);
g_downloadDefaultPackageIndex = setCommand(TEXT("Install Default Snippet Package"), installDefaultPackage);
g_importSnippetsIndex = setCommand(TEXT("Import Snippets from ftd file"), importSnippetsOnly);
//g_downloadDefaultPackageIndex = setCommand(TEXT("Import Default Snippet Package"), downloadDefaultPackage);
g_exportSnippetsIndex = setCommand(TEXT("Export All Snippets"), exportSnippetsOnly);
g_deleteAllSnippetsIndex = setCommand(TEXT("Delete All Snippets"), exportAndClearSnippets);
setCommand();
g_TriggerTextCompletionIndex = setCommand(TEXT("TriggerText Completion"), doTagComplete);
g_insertPreviousIndex = setCommand(TEXT("Insert Previous Snippet"), insertPrevious);
//g_InsertHotspotIndex =setCommand(TEXT("Insert a hotspot"), insertHotSpotSign);
setCommand();
g_settingsIndex = setCommand(TEXT("Settings"), showSettings);
g_quickGuideIndex = setCommand(TEXT("Quick Guide"), showHelp);
g_aboutIndex = setCommand(TEXT("About"), showAbout);
setCommand();
setCommand(TEXT("Testing"), testing);
setCommand(TEXT("Testing2"), testing2);
setCommand(TEXT("Test Settings"), showSettingDlg);
setCommand(TEXT("Test Creation"), showCreationDlg);
}
void variablesInit()
{
g_stopCharArray = new char[strlen(g_tagSignList[0])+strlen(g_tagTailList[0])+1];
strcpy(g_stopCharArray,g_tagSignList[0]);
strcat(g_stopCharArray,g_tagTailList[0]);
strcpy(escapeWordChar,searchWordChar);
if (wcslen(pc.configText[CUSTOM_ESCAPE_CHAR])>0)
{
char *customEscapeChar = toCharArray(pc.configText[CUSTOM_ESCAPE_CHAR]);
strncat(escapeWordChar,customEscapeChar,20);
delete [] customEscapeChar;
}
updateSnippetCount();
g_customSciHandle = (HWND)::SendMessage(nppData._nppHandle,NPPM_CREATESCINTILLAHANDLE,0,NULL);
}
void nppReady()
{
sciFocus = 1;
if (g_dbOpen)
{
g_enable = true;
} else
{
g_enable = false;
showMessageBox(TEXT("FingerText cannot be enabled because there is no database connection. Please restart Notepad++ and make sure that the config folder is writable."));
}
turnOffOptionMode();
if (!(pc.configInt[USE_NPP_SHORTKEY])) // For compatibility mode
{ // For compatibility mode
::EnableMenuItem((HMENU)::SendMessage(nppData._nppHandle, NPPM_GETMENUHANDLE, 0, 0), funcItem[g_tabActivateIndex]._cmdID, MF_BYCOMMAND | MF_GRAYED); // For compatibility mode
installhook(); // For compatibility mode
SendScintilla(SCI_ASSIGNCMDKEY,SCK_TAB,SCI_NULL); // For compatibility mode
} // For compatibility mode
//Temporarily disable the insertion dialog
//::EnableMenuItem((HMENU)::SendMessage(nppData._nppHandle, NPPM_GETMENUHANDLE, 0, 0), funcItem[g_showInsertionDlgIndex]._cmdID, MF_BYCOMMAND | MF_GRAYED);
updateMode();
pc.upgradeMessage();
if (pc.configInt[FORCE_MULTI_PASTE]) ::SendScintilla(SCI_SETMULTIPASTE,1,0);
if (snippetDock.isVisible()) updateDockItems(true,false,"%",true); //snippetHintUpdate();
}
void pluginShutdown() // function is triggered when NPPN_SHUTDOWN fires
{
::SendMessage(nppData._nppHandle,NPPM_DESTROYSCINTILLAHANDLE,0,(LPARAM)g_customSciHandle);
if (!(pc.configInt[USE_NPP_SHORTKEY])) removehook(); // For compatibility mode
//delete [] g_snippetCache;
if (g_dbOpen)
{
sqlite3_close(g_db); // This close the database when the plugin shutdown.
g_dbOpen = false;
}
::SetWindowLongPtr(nppData._nppHandle, GWLP_WNDPROC, (LPARAM)wndProcNpp); // Clean up subclassing
delete [] g_stopCharArray;
pc.configCleanUp();
}
// command shortcut clean up
void commandMenuCleanUp()
{
delete funcItem[g_tabActivateIndex]._pShKey;
delete funcItem[g_showInsertionDlgIndex]._pShKey;
// Don't forget to deallocate your shortcut here
}
void pluginCleanUp()
{
//TODO: think about how to save the parameters for the next session during clean up
}
// Functions for Fingertext
void shortCutRemapped()
{
if (!(pc.configInt[USE_NPP_SHORTKEY]))
{
HMENU hMenu = (HMENU)::SendMessage(nppData._nppHandle, NPPM_GETMENUHANDLE, 0, 0); // For compatibility mode
::EnableMenuItem(hMenu, funcItem[g_tabActivateIndex]._cmdID, MF_BYCOMMAND | MF_GRAYED); // For compatibility mode
}
}
void toggleDisable()
{
HMENU hMenu = (HMENU)::SendMessage(nppData._nppHandle, NPPM_GETMENUHANDLE, 0, 0); // For compatibility mode
::EnableMenuItem(hMenu, funcItem[g_tabActivateIndex]._cmdID, MF_BYCOMMAND | MF_GRAYED);
if (g_enable)
{
::EnableMenuItem(hMenu, funcItem[g_snippetDockIndex]._cmdID, MF_BYCOMMAND | MF_GRAYED);
::EnableMenuItem(hMenu, funcItem[g_tabActivateIndex]._cmdID, MF_BYCOMMAND | MF_GRAYED);
::EnableMenuItem(hMenu, funcItem[g_showInsertionDlgIndex]._cmdID, MF_BYCOMMAND | MF_GRAYED);
::EnableMenuItem(hMenu, funcItem[g_selectionToSnippetIndex]._cmdID, MF_BYCOMMAND | MF_GRAYED);
::EnableMenuItem(hMenu, funcItem[g_importSnippetsIndex]._cmdID, MF_BYCOMMAND | MF_GRAYED);
::EnableMenuItem(hMenu, funcItem[g_exportSnippetsIndex]._cmdID, MF_BYCOMMAND | MF_GRAYED);
::EnableMenuItem(hMenu, funcItem[g_deleteAllSnippetsIndex]._cmdID, MF_BYCOMMAND | MF_GRAYED);
::EnableMenuItem(hMenu, funcItem[g_TriggerTextCompletionIndex]._cmdID, MF_BYCOMMAND | MF_GRAYED);
::EnableMenuItem(hMenu, funcItem[g_InsertHotspotIndex]._cmdID, MF_BYCOMMAND | MF_GRAYED);
closeEditor();
snippetDock.display(false);
// TODO: refactor all the message boxes to a separate function
showMessageBox(TEXT("FingerText is disabled"));
//::MessageBox(nppData._nppHandle, TEXT("FingerText is disabled"), TEXT(PLUGIN_NAME), MB_OK);
g_enable = false;
} else if (!g_dbOpen)
{
showMessageBox(TEXT("FingerText cannot be enabled because there is no database connection. Please restart Notepad++ and make sure that the config folder is writable."));
} else
{
::EnableMenuItem(hMenu, funcItem[g_snippetDockIndex]._cmdID, MF_BYCOMMAND);
::EnableMenuItem(hMenu, funcItem[g_tabActivateIndex]._cmdID, MF_BYCOMMAND);
::EnableMenuItem(hMenu, funcItem[g_showInsertionDlgIndex]._cmdID, MF_BYCOMMAND);
::EnableMenuItem(hMenu, funcItem[g_selectionToSnippetIndex]._cmdID, MF_BYCOMMAND);
::EnableMenuItem(hMenu, funcItem[g_importSnippetsIndex]._cmdID, MF_BYCOMMAND);
::EnableMenuItem(hMenu, funcItem[g_exportSnippetsIndex]._cmdID, MF_BYCOMMAND);
::EnableMenuItem(hMenu, funcItem[g_deleteAllSnippetsIndex]._cmdID, MF_BYCOMMAND);
::EnableMenuItem(hMenu, funcItem[g_TriggerTextCompletionIndex]._cmdID, MF_BYCOMMAND);
::EnableMenuItem(hMenu, funcItem[g_InsertHotspotIndex]._cmdID, MF_BYCOMMAND);
showMessageBox(TEXT("FingerText is enabled"));
//::MessageBox(nppData._nppHandle, TEXT("FingerText is enabled"), TEXT(PLUGIN_NAME), MB_OK);
g_enable = true;
}
updateMode();
}
char *findTagSQLite(char *tag, const char *tagCompare)
{
//alertCharArray(tagCompare);
char *expanded = NULL;
sqlite3_stmt *stmt;
// First create the SQLite SQL statement ("prepare" it for running)
char *sqlitePrepareStatement;
sqlitePrepareStatement = "SELECT snippet FROM snippets WHERE tagType LIKE ? AND tag LIKE ? ORDER BY tag";
if (SQLITE_OK == sqlite3_prepare_v2(g_db, sqlitePrepareStatement, -1, &stmt, NULL))
{
sqlite3_bind_text(stmt, 1, tagCompare, -1, SQLITE_STATIC);
sqlite3_bind_text(stmt, 2, tag, -1, SQLITE_STATIC);
// Run the query with sqlite3_step
if(SQLITE_ROW == sqlite3_step(stmt)) // SQLITE_ROW 100 sqlite3_step() has another row ready
{
const char* expandedSQL = reinterpret_cast<const char *>(sqlite3_column_text(stmt, 0)); // The 0 here means we only take the first column returned. And it is the snippet as there is only one column
//expanded = new char[strlen(expandedSQL)*4 + 1];
expanded = new char[strlen(expandedSQL) + 1];
strcpy(expanded, expandedSQL);
}
}
// Close the SQLite statement, as we don't need it anymore
// This also has the effect of free'ing the result from sqlite3_column_text
// (i.e. in our case, expandedSQL)
sqlite3_finalize(stmt);
return expanded; //remember to delete the returned expanded after use.
}
void doSelectionToSnippet()
{
selectionToSnippet(false);
}
void selectionToSnippet(bool forceNew)
{
g_selectionMonitor--;
//pc.configInt[EDITOR_CARET_BOUND]--;
//HWND curScintilla = getCurrentScintilla();
int selectionEnd = ::SendScintilla(SCI_GETSELECTIONEND,0,0);
int selectionStart = ::SendScintilla(SCI_GETSELECTIONSTART,0,0);
bool withSelection = false;
char* selection;
if ((selectionEnd>selectionStart) && (!forceNew))
{
sciGetText(&selection,selectionStart,selectionEnd);
//selection = new char [selectionEnd - selectionStart +1];
//::SendScintilla(SCI_GETSELTEXT,0, reinterpret_cast<LPARAM>(selection));
withSelection = true;
} else
{
selection = "This is some stub text for the content of your new snippet.\r\nPlease replace the stub text with the content that you want to show when the snippet is triggered.\r\n\r\nEnjoy!\r\n";
}
//::SendMessage(curScintilla,SCI_GETSELTEXT,0, reinterpret_cast<LPARAM>(selection));
openTab(g_ftbPath);
//if (!::SendMessage(nppData._nppHandle, NPPM_SWITCHTOFILE, 0, (LPARAM)g_ftbPath))
//{
// ::SendMessage(nppData._nppHandle, NPPM_DOOPEN, 0, (LPARAM)g_ftbPath);
//}
//curScintilla = getCurrentScintilla();
//TODO: consider using YES NO CANCEL dialog in promptsavesnippet
promptSaveSnippet(TEXT("Do you wish to save the current snippet before creating a new one?"));
::SendScintilla(SCI_CONVERTEOLS,SC_EOL_LF, 0);
::SendScintilla(SCI_CLEARALL,0,0);
::SendScintilla(SCI_INSERTTEXT,::SendScintilla(SCI_GETLENGTH,0,0), (LPARAM)"------ FingerText Snippet Editor View ------\r\n");
::SendScintilla(SCI_INSERTTEXT,::SendScintilla(SCI_GETLENGTH,0,0), (LPARAM)"triggertext\r\nGLOBAL\r\n");
::SendScintilla(SCI_INSERTTEXT,::SendScintilla(SCI_GETLENGTH,0,0), (LPARAM)selection);
::SendScintilla(SCI_INSERTTEXT,::SendScintilla(SCI_GETLENGTH,0,0), (LPARAM)"[>END<]");
g_editorView = 1;
//updateDockItems(false,false);
//updateMode();
//refreshAnnotation();
::SendScintilla(SCI_GOTOLINE,1,0);
::SendScintilla(SCI_WORDRIGHTEXTEND,1,0);
if (withSelection) delete [] selection;
::SendScintilla(SCI_EMPTYUNDOBUFFER,0,0);
//pc.configInt[EDITOR_CARET_BOUND]++;
g_selectionMonitor++;
}
void closeNonSessionTabs()
{
closeTab(g_ftbPath);
closeTab(pc.iniPath);
}
void closeEditor()
{
if (::SendMessage(nppData._nppHandle, NPPM_SWITCHTOFILE, 0, (LPARAM)g_ftbPath))
::SendMessage(nppData._nppHandle, NPPM_MENUCOMMAND, 0, IDM_FILE_CLOSE);
}
void insertSnippet()
{
TCHAR* bufferWide;
snippetDock.getSelectText(bufferWide);
char* buffer = toCharArray(bufferWide);
buffer = quickStrip(buffer, ' ');
int scopeLength = ::strchr(buffer,'>') - buffer - 1;
int triggerTextLength = strlen(buffer)-scopeLength - 2;
char* tempTriggerText = new char [ triggerTextLength+1];
char* tempScope = new char[scopeLength+1];
strncpy(tempScope,buffer+1,scopeLength);
tempScope[scopeLength] = '\0';
strncpy(tempTriggerText,buffer+1+scopeLength+1,triggerTextLength);
tempTriggerText[triggerTextLength] = '\0';
delete [] buffer;
diagActivate(tempTriggerText);
::SetFocus(::getCurrentScintilla());
}
void editSnippet()
{
int topIndex = -1;
if (g_editorView) topIndex = snippetDock.getTopIndex();
TCHAR* bufferWide;
snippetDock.getSelectText(bufferWide);
char* buffer = toCharArray(bufferWide);
buffer = quickStrip(buffer, ' ');
if (strlen(buffer)==0) selectionToSnippet(true);
//if (strlen(buffer)==0)
//{
// ::showMessageBox(TEXT("No Snippet Selected"));
// delete [] buffer;
// return;
//}
//
int scopeLength = ::strchr(buffer,'>') - buffer - 1;
int triggerTextLength = strlen(buffer)-scopeLength - 2;
char* tempTriggerText = new char [ triggerTextLength+1];
char* tempScope = new char[scopeLength+1];
strncpy(tempScope,buffer+1,scopeLength);
tempScope[scopeLength] = '\0';
strncpy(tempTriggerText,buffer+1+scopeLength+1,triggerTextLength);
tempTriggerText[triggerTextLength] = '\0';
delete [] buffer;
sqlite3_stmt *stmt;
if (SQLITE_OK == sqlite3_prepare_v2(g_db, "SELECT snippet FROM snippets WHERE tagType = ? AND tag = ?", -1, &stmt, NULL))
{
// Then bind the two ? parameters in the SQLite SQL to the real parameter values
sqlite3_bind_text(stmt, 1, tempScope , -1, SQLITE_STATIC);
sqlite3_bind_text(stmt, 2, tempTriggerText, -1, SQLITE_STATIC);
// Run the query with sqlite3_step
if(SQLITE_ROW == sqlite3_step(stmt)) // SQLITE_ROW 100 sqlite3_step() has another row ready
{
const char* snippetText = reinterpret_cast<const char *>(sqlite3_column_text(stmt, 0)); // The 0 here means we only take the first column returned. And it is the snippet as there is only one column
// After loading the content, switch to the editor buffer and promput for saving if needed
openTab(g_ftbPath);
std::string allScope = "";
//if (!::SendMessage(nppData._nppHandle, NPPM_SWITCHTOFILE, 0, (LPARAM)g_ftbPath))
//{
// ::SendMessage(nppData._nppHandle, NPPM_DOOPEN, 0, (LPARAM)g_ftbPath);
//}
//HWND curScintilla = getCurrentScintilla();
promptSaveSnippet(TEXT("Do you wish to save the current snippet before editing another one?"));
::SendScintilla(SCI_CONVERTEOLS,SC_EOL_LF, 0);
sqlite3_stmt *stmt2;
if (SQLITE_OK == sqlite3_prepare_v2(g_db, "SELECT tagtype FROM snippets WHERE tag = ? AND snippet = ?", -1, &stmt2, NULL))
{
sqlite3_bind_text(stmt2, 1, tempTriggerText , -1, SQLITE_STATIC);
sqlite3_bind_text(stmt2, 2, snippetText, -1, SQLITE_STATIC);
while (SQLITE_ROW == sqlite3_step(stmt2))
{
if (allScope.length()!=0) allScope = allScope + "|";
const char* extraScope = reinterpret_cast<const char *>(sqlite3_column_text(stmt2, 0));
allScope = allScope + extraScope;
}
}
sqlite3_finalize(stmt2);
::SendScintilla(SCI_CLEARALL,0,0);
//::SendMessage(nppData._nppHandle, NPPM_MENUCOMMAND, 0, IDM_FILE_NEW);
::SendScintilla(SCI_INSERTTEXT, ::SendScintilla(SCI_GETLENGTH,0,0), (LPARAM)"------ FingerText Snippet Editor View ------\r\n");
::SendScintilla(SCI_INSERTTEXT, ::SendScintilla(SCI_GETLENGTH,0,0), (LPARAM)tempTriggerText);
::SendScintilla(SCI_INSERTTEXT, ::SendScintilla(SCI_GETLENGTH,0,0), (LPARAM)"\r\n");
::SendScintilla(SCI_INSERTTEXT, ::SendScintilla(SCI_GETLENGTH,0,0), (LPARAM)allScope.c_str());
::SendScintilla(SCI_INSERTTEXT, ::SendScintilla(SCI_GETLENGTH,0,0), (LPARAM)"\r\n");
::SendScintilla(SCI_INSERTTEXT, ::SendScintilla(SCI_GETLENGTH,0,0), (LPARAM)snippetText);
g_editorView = true;
refreshAnnotation();
}
}
sqlite3_finalize(stmt);
::SendScintilla(SCI_SETSAVEPOINT,0,0);
::SendScintilla(SCI_EMPTYUNDOBUFFER,0,0);
delete [] tempTriggerText;
delete [] tempScope;
int scrollPos = snippetDock.searchSnippetList(bufferWide);
snippetDock.selectSnippetList(scrollPos);
if (topIndex == -1)
{
snippetDock.setTopIndex(scrollPos);
} else
{
snippetDock.setTopIndex(topIndex);
}
delete [] bufferWide;
}
void deleteSnippet()
{
int topIndex = snippetDock.getTopIndex();
TCHAR* bufferWide;
snippetDock.getSelectText(bufferWide);
char* buffer = toCharArray(bufferWide);
buffer = quickStrip(buffer, ' ');
int scopeLength = ::strchr(buffer,'>') - buffer - 1;
int triggerTextLength = strlen(buffer)-scopeLength - 2;
char* tempTriggerText = new char [ triggerTextLength+1];
char* tempScope = new char[scopeLength+1];
strncpy(tempScope,buffer+1,scopeLength);
tempScope[scopeLength] = '\0';
strncpy(tempTriggerText,buffer+1+scopeLength+1,triggerTextLength);
tempTriggerText[triggerTextLength] = '\0';
delete [] buffer;
sqlite3_stmt *stmt;
if (SQLITE_OK == sqlite3_prepare_v2(g_db, "DELETE FROM snippets WHERE tagType LIKE ? AND tag LIKE ?", -1, &stmt, NULL))
{
sqlite3_bind_text(stmt, 1, tempScope, -1, SQLITE_STATIC);
sqlite3_bind_text(stmt, 2, tempTriggerText, -1, SQLITE_STATIC);
sqlite3_step(stmt);
}
sqlite3_finalize(stmt);
//TODO: can use the sqlite3 return message to show error message when the delete is not successful
updateSnippetCount();
updateDockItems(true,false,"%",true);
delete [] tempTriggerText;
delete [] tempScope;
snippetDock.setTopIndex(topIndex);
delete [] bufferWide;
}
bool getLineChecked(char **buffer, int lineNumber, TCHAR* errorText)
{
// TODO: and check for more error, say the triggertext has to be one word
bool problemSnippet = false;
::SendScintilla(SCI_GOTOLINE,lineNumber,0);
int tagPosStart = ::SendScintilla(SCI_GETCURRENTPOS,0,0);
int tagPosEnd;
if (lineNumber == 3)
{
tagPosEnd = ::SendScintilla(SCI_GETLENGTH,0,0);
} else
{
int tagPosLineEnd = ::SendScintilla(SCI_GETLINEENDPOSITION,lineNumber,0);
//char* wordChar;
//if (lineNumber==2)
//{
// wordChar = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_:.|";
//
//} else //if (lineNumber==1)
//{
// wordChar = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
//}
if (lineNumber==2)
{
::SendScintilla(SCI_SETWORDCHARS, 0, (LPARAM)scopeWordChar);
} else
{
::SendScintilla(SCI_SETWORDCHARS, 0, (LPARAM)triggertextWordChar);
}
tagPosEnd = ::SendScintilla(SCI_WORDENDPOSITION,tagPosStart,0);
::SendScintilla(SCI_SETCHARSDEFAULT, 0, 0);
//::SendMessage(curScintilla,SCI_SEARCHANCHOR,0,0);
//::SendMessage(curScintilla,SCI_SEARCHNEXT,0,(LPARAM)" ");
//tagPosEnd = ::SendMessage(curScintilla,SCI_GETCURRENTPOS,0,0);
if ((tagPosEnd>tagPosLineEnd) || (tagPosEnd-tagPosStart<=0))
{
//blank
::SendScintilla(SCI_GOTOLINE,lineNumber,0);
showMessageBox(errorText);
//::MessageBox(nppData._nppHandle, errorText, TEXT(PLUGIN_NAME), MB_OK);
problemSnippet = true;
} else if (tagPosEnd<tagPosLineEnd)
{
// multi
::SendScintilla(SCI_GOTOLINE,lineNumber,0);
showMessageBox(errorText);
//::MessageBox(nppData._nppHandle, errorText, TEXT(PLUGIN_NAME), MB_OK);
problemSnippet = true;
}
}
if (lineNumber == 3)
{
::SendScintilla(SCI_GOTOPOS,tagPosStart,0);
int spot = searchNext("[>END<]");
if (spot<0)
{
showMessageBox(TEXT("You should put an \"[>END<]\" (without quotes) at the end of your snippet content."));
//::MessageBox(nppData._nppHandle, TEXT("You should put an \"[>END<]\" (without quotes) at the end of your snippet content."), TEXT(PLUGIN_NAME), MB_OK);
problemSnippet = true;
}
}
//::SendScintilla(SCI_SETSELECTION,tagPosStart,tagPosEnd);
//*buffer = new char[tagPosEnd-tagPosStart + 1];
//::SendScintilla(SCI_GETSELTEXT, 0, reinterpret_cast<LPARAM>(*buffer));
sciGetText(&*buffer,tagPosStart,tagPosEnd);
return problemSnippet;
}
//TODO: saveSnippet() and importSnippet() need refactoring sooooooo badly..................
void saveSnippet()
{
//HWND curScintilla = getCurrentScintilla();
g_selectionMonitor--;
int docLength = ::SendScintilla(SCI_GETLENGTH,0,0);
// insert a space at the end of the doc so the ::SendMessage(curScintilla,SCI_SEARCHNEXT,0,(LPARAM)" "); will not get into error
// TODO: Make sure that it is not necessary to keep this line
//::SendMessage(curScintilla, SCI_INSERTTEXT, docLength, (LPARAM)" ");
bool problemSnippet = false;
char* tagText;
char* tagTypeText;
char* snippetText;
::SendScintilla(SCI_CONVERTEOLS,SC_EOL_LF, 0);
if (getLineChecked(&tagText,1,TEXT("TriggerText cannot be blank, and it can only contain alphanumeric characters (no spaces allowed)"))==true) problemSnippet = true;
if (getLineChecked(&tagTypeText,2,TEXT("Scope cannot be blank, and it can only contain alphanumeric characters and/or period."))==true) problemSnippet = true;
if (getLineChecked(&snippetText,3,TEXT("Snippet Content cannot be blank."))==true) problemSnippet = true;
::SendScintilla(SCI_SETSELECTION,docLength,docLength+1); //Take away the extra space added
::SendScintilla(SCI_REPLACESEL,0,(LPARAM)"");
std::vector<std::string> tagTypeTextVector = toVectorString(tagTypeText,'|');
if (!problemSnippet)
{
int i = 0;
while (i<tagTypeTextVector.size())
{
if (tagTypeTextVector[i].length()>0)
{
// checking for existing snippet
sqlite3_stmt *stmt;
if (SQLITE_OK == sqlite3_prepare_v2(g_db, "SELECT snippet FROM snippets WHERE tagType LIKE ? AND tag LIKE ?", -1, &stmt, NULL))
{
sqlite3_bind_text(stmt, 1, tagTypeTextVector[i].c_str(), -1, SQLITE_STATIC);
sqlite3_bind_text(stmt, 2, tagText, -1, SQLITE_STATIC);
if(SQLITE_ROW == sqlite3_step(stmt))
{
std::string messageString = "Snippet \"" + std::string(tagText) + "\" in scope <" + tagTypeTextVector[i] + "> aleady exists, overwrite?";
//char* message = new char[messageString.length()+1];
//strcpy(message,messageString.c_str());
wchar_t* messageWide = toWideChar((std::string)messageString);
int messageReturn = showMessageBox(messageWide,MB_YESNO);
//delete [] message;
delete [] messageWide;
//int messageReturn = ::MessageBox(nppData._nppHandle, TEXT("Snippet exists, overwrite?"), TEXT(PLUGIN_NAME), MB_YESNO);
if (messageReturn==IDNO)
{
// not overwrite
std::string messageString = "Snippet \"" + std::string(tagText) + "\" in scope <" + tagTypeTextVector[i] + "> is not saved.";
wchar_t* messageWide = toWideChar((std::string)messageString);
showMessageBox(messageWide);
delete [] messageWide;
delete [] tagText;
delete [] tagTypeText;
delete [] snippetText;
//::MessageBox(nppData._nppHandle, TEXT("The Snippet is not saved."), TEXT(PLUGIN_NAME), MB_OK);
//::SendMessage(curScintilla, SCI_GOTOPOS, 0, 0);
//::SendMessage(curScintilla, SCI_INSERTTEXT, 0, (LPARAM)" ");
::SendScintilla(SCI_SETSELECTION, 0, 1);
::SendScintilla(SCI_REPLACESEL, 0, (LPARAM)"-");
::SendScintilla(SCI_GOTOPOS, 0, 0);
sqlite3_finalize(stmt);
return;
} else
{
sqlite3_stmt *stmt2;
// delete existing entry
if (SQLITE_OK == sqlite3_prepare_v2(g_db, "DELETE FROM snippets WHERE tagType LIKE ? AND tag LIKE ?", -1, &stmt2, NULL))
{
sqlite3_bind_text(stmt2, 1, tagTypeTextVector[i].c_str(), -1, SQLITE_STATIC);
sqlite3_bind_text(stmt2, 2, tagText, -1, SQLITE_STATIC);
sqlite3_step(stmt2);
} else
{
showMessageBox(TEXT("Cannot write into database."));
//::MessageBox(nppData._nppHandle, TEXT("Cannot write into database."), TEXT(PLUGIN_NAME), MB_OK);
}
sqlite3_finalize(stmt2);
}
}
}
sqlite3_finalize(stmt);
if (SQLITE_OK == sqlite3_prepare_v2(g_db, "INSERT INTO snippets VALUES(?,?,?,?)", -1, &stmt, NULL))
{
// Then bind the two ? parameters in the SQLite SQL to the real parameter values
sqlite3_bind_text(stmt, 1, tagText, -1, SQLITE_STATIC);
sqlite3_bind_text(stmt, 2, tagTypeTextVector[i].c_str(), -1, SQLITE_STATIC);
sqlite3_bind_text(stmt, 3, snippetText, -1, SQLITE_STATIC);
sqlite3_bind_text(stmt, 4, "", -1, SQLITE_STATIC);
// Run the query with sqlite3_step
sqlite3_step(stmt); // SQLITE_ROW 100 sqlite3_step() has another row ready
std::string messageString = "Snippet \"" + std::string(tagText) + "\" in scope <" + tagTypeTextVector[i] + "> is saved.";
wchar_t* messageWide = toWideChar((std::string)messageString);
showMessageBox(messageWide);
delete [] messageWide;
//showMessageBox(TEXT("The Snippet is saved."));
//::MessageBox(nppData._nppHandle, TEXT("The Snippet is saved."), TEXT(PLUGIN_NAME), MB_OK);
}
sqlite3_finalize(stmt);
}
i++;
}
::SendScintilla(SCI_SETSAVEPOINT,0,0);
}
updateSnippetCount();
updateDockItems(true,false,"%",true);
//TODO: This is not working. The scrolling works but the snippetdock reset the scrolling after thei savesnippet() finished
wchar_t* searchItem = constructDockItems(toString(tagTypeText),toString(tagText),14);
int scrollPos = snippetDock.searchSnippetList(searchItem);
snippetDock.selectSnippetList(scrollPos);
snippetDock.setTopIndex(scrollPos);
delete [] searchItem;
delete [] tagText;
delete [] tagTypeText;
delete [] snippetText;
g_selectionMonitor++;
}
void restoreTab(int &posCurrent, int &posSelectionStart, int &posSelectionEnd)
{
// restoring the original tab action
::SendScintilla(SCI_GOTOPOS,posCurrent,0);
::SendScintilla(SCI_SETSELECTION,posSelectionStart,posSelectionEnd);
::SendScintilla(SCI_TAB,0,0);
}
//TODO: refactor searchPrevMatchedSign and searchNextMatchedTail
int searchPrevMatchedSign(char* tagSign, char* tagTail)
{
//This function works when the caret is at the beginning of tagtail
// it return the position at the beginning of the tagsign if found
int signSpot = -1;
int tailSpot = -1;
int unmatchedTail = 0;
do
{
int posCurrent = ::SendScintilla(SCI_GETCURRENTPOS,0,0);
tailSpot = searchPrev(tagTail);
::SendScintilla(SCI_GOTOPOS,posCurrent,0);
signSpot = searchPrev(tagSign);
if (signSpot == -1)
{
return -1;
}
if ((signSpot > tailSpot) && (unmatchedTail == 0))
{