forked from bruderstein/PythonScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScintillaWrapper.cpp
More file actions
1048 lines (841 loc) · 30 KB
/
ScintillaWrapper.cpp
File metadata and controls
1048 lines (841 loc) · 30 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "stdafx.h"
#include "Scintilla.h"
#include "ScintillaCells.h"
#include "ScintillaWrapper.h"
#include "Replacer.h"
#include "Match.h"
#include "ReplacementContainer.h"
#include "NotSupportedException.h"
#include "ArgumentException.h"
#include "PythonScript/NppPythonScript.h"
#include "MutexHolder.h"
#include "GILManager.h"
#include "CallbackExecArgs.h"
#include "ScintillaCallback.h"
#include "MainThread.h"
#include "MutexHolder.h"
#include "ScintillaCallbackCounter.h"
#include "NotAllowedInCallbackException.h"
namespace NppPythonScript
{
void translateOutOfBounds(out_of_bounds_exception const& /* e */)
{
PyErr_SetString(PyExc_IndexError, "Out of Bounds");
}
ScintillaWrapper::ScintillaWrapper(const HWND handle, const HWND notepadHandle)
: PyProducerConsumer<CallbackExecArgs>(),
m_handle(handle),
m_hNotepad(notepadHandle),
m_notificationsEnabled(false),
m_callbackMutex(::CreateMutex(NULL, FALSE, NULL))
{
}
ScintillaWrapper::~ScintillaWrapper()
{
// m_handle isn't allocated here. Let's just NULL out reference to it, then.
m_handle = NULL;
}
boost::python::object deprecated_replace_function(boost::python::tuple /* args */, boost::python::dict /* kwargs */)
{
throw NppPythonScript::NotSupportedException("The pyreplace(), pymlreplace(), pysearch() and pymlsearch() functions have been deprecated.\n"
"The new replace(), rereplace(), search(), and research() functions have all the same functionality, but are faster, more reliable and have better support for unicode.");
}
std::string ScintillaWrapper::getStringFromObject(boost::python::object o)
{
std::string raw;
if (PyUnicode_Check(o.ptr()))
{
boost::python::object utf8Text = o.attr("__str__")();
raw = std::string(boost::python::extract<const char *>(utf8Text));
}
else if (PyBytes_CheckExact(o.ptr()))
{
raw.assign(PyBytes_AsString(o.ptr()), PyBytes_Size(o.ptr()));
}
else
{
boost::python::object rawString = o.attr("__str__")();
raw = std::string(boost::python::extract<const char *>(rawString), _len(rawString));
}
return raw;
}
void ScintillaWrapper::notify(SCNotification *notifyCode)
{
if (!m_notificationsEnabled)
return;
{
NppPythonScript::GILLock gilLock;
NppPythonScript::MutexHolder hold(m_callbackMutex);
std::pair<callbackT::iterator, callbackT::iterator> callbackIter
= m_callbacks.equal_range(notifyCode->nmhdr.code);
if (callbackIter.first != callbackIter.second)
{
std::shared_ptr<CallbackExecArgs> callbackExec(new CallbackExecArgs());
std::shared_ptr<CallbackExecArgs> asyncCallbackExec(new CallbackExecArgs());
boost::python::dict params;
// Create the parameters for the callback
params["code"] = notifyCode->nmhdr.code;
params["idFrom"] = notifyCode->nmhdr.idFrom;
params["hwndFrom"] = reinterpret_cast<intptr_t>(notifyCode->nmhdr.hwndFrom);
switch(notifyCode->nmhdr.code)
{
case SCN_STYLENEEDED:
params["position"] = notifyCode->position;
break;
case SCN_CHARADDED:
params["ch"] = notifyCode->ch;
break;
case SCN_SAVEPOINTREACHED:
break;
case SCN_SAVEPOINTLEFT:
break;
case SCN_MODIFYATTEMPTRO:
break;
case SCN_KEY:
params["ch"] = notifyCode->ch;
params["modifiers"] = notifyCode->modifiers;
break;
case SCN_DOUBLECLICK:
params["position"] = notifyCode->position;
params["modifiers"] = notifyCode->modifiers;
params["line"] = notifyCode->line;
break;
case SCN_UPDATEUI:
params["updated"] = notifyCode->updated;
break;
case SCN_MODIFIED:
params["position"] = notifyCode->position;
params["modificationType"] = notifyCode->modificationType;
if (notifyCode->text)
{
// notifyCode->text is not null terminated
std::string text(notifyCode->text, notifyCode->length);
params["text"] = text.c_str();
}
else
{
params["text"] = "";
}
params["length"] = notifyCode->length;
params["linesAdded"] = notifyCode->linesAdded;
params["line"] = notifyCode->line;
params["foldLevelNow"] = notifyCode->foldLevelNow;
params["foldLevelPrev"] = notifyCode->foldLevelPrev;
if (notifyCode->modificationType & SC_MOD_CHANGEANNOTATION)
{
params["annotationLinesAdded"] = notifyCode->annotationLinesAdded;
}
if (notifyCode->modificationType & SC_MOD_CONTAINER)
{
params["token"] = notifyCode->token;
}
params["token"] = notifyCode->token;
params["annotationLinesAdded"] = notifyCode->annotationLinesAdded;
break;
case SCN_MACRORECORD:
params["message"] = notifyCode->message;
params["wParam"] = notifyCode->wParam;
params["lParam"] = notifyCode->lParam;
break;
case SCN_MARGINCLICK:
params["margin"] = notifyCode->margin;
params["position"] = notifyCode->position;
params["modifiers"] = notifyCode->modifiers;
break;
case SCN_NEEDSHOWN:
params["position"] = notifyCode->position;
params["length"] = notifyCode->length;
break;
case SCN_PAINTED:
break;
case SCN_USERLISTSELECTION:
params["text"] = notifyCode->text;
params["listType"] = notifyCode->listType;
params["position"] = notifyCode->position;
break;
case SCN_URIDROPPED:
params["text"] = notifyCode->text;
break;
case SCN_DWELLSTART:
params["position"] = notifyCode->position;
params["x"] = notifyCode->x;
params["y"] = notifyCode->y;
break;
case SCN_DWELLEND:
params["position"] = notifyCode->position;
params["x"] = notifyCode->x;
params["y"] = notifyCode->y;
break;
case SCN_ZOOM:
break;
case SCN_HOTSPOTCLICK:
case SCN_HOTSPOTDOUBLECLICK:
case SCN_HOTSPOTRELEASECLICK:
params["position"] = notifyCode->position;
params["modifiers"] = notifyCode->modifiers;
break;
case SCN_INDICATORCLICK:
case SCN_INDICATORRELEASE:
params["position"] = notifyCode->position;
params["modifiers"] = notifyCode->modifiers;
break;
case SCN_CALLTIPCLICK:
params["position"] = notifyCode->position;
break;
case SCN_AUTOCSELECTION:
params["text"] = notifyCode->text;
params["position"] = notifyCode->position;
break;
case SCN_AUTOCCANCELLED:
break;
case SCN_AUTOCCHARDELETED:
break;
case SCN_FOCUSIN:
case SCN_FOCUSOUT:
break;
default:
// Unknown notification, so just fill in all the parameters.
params["position"] = notifyCode->position;
params["modificationType"] = notifyCode->modificationType;
if (notifyCode->text)
{
// notifyCode->text is not null terminated
std::string text(notifyCode->text, notifyCode->length);
params["text"] = text.c_str();
}
params["length"] = notifyCode->length;
params["linesAdded"] = notifyCode->linesAdded;
params["line"] = notifyCode->line;
params["foldLevelNow"] = notifyCode->foldLevelNow;
params["foldLevelPrev"] = notifyCode->foldLevelPrev;
params["annotationLinesAdded"] = notifyCode->annotationLinesAdded;
params["listType"] = notifyCode->listType;
params["message"] = notifyCode->message;
params["wParam"] = notifyCode->wParam;
params["lParam"] = notifyCode->lParam;
params["modifiers"] = notifyCode->modifiers;
params["token"] = notifyCode->token;
params["x"] = notifyCode->x;
params["y"] = notifyCode->y;
break;
}
bool hasSyncCallbacks = false;
bool hasAsyncCallbacks = false;
while (callbackIter.first != callbackIter.second)
{
if (callbackIter.first->second->isAsync())
{
asyncCallbackExec->addCallback(callbackIter.first->second->getCallback());
hasAsyncCallbacks = true;
}
else
{
callbackExec->addCallback(callbackIter.first->second->getCallback());
hasSyncCallbacks = true;
}
++callbackIter.first;
}
if (hasAsyncCallbacks)
{
asyncCallbackExec->setParams(params);
DEBUG_TRACE(L"Scintilla async callback\n");
produce(asyncCallbackExec);
}
if (hasSyncCallbacks)
{
callbackExec->setParams(params);
DEBUG_TRACE(L"Scintilla Sync callback\n");
runCallbacks(callbackExec);
}
}
}
}
void ScintillaWrapper::consume(std::shared_ptr<CallbackExecArgs> args)
{
NppPythonScript::GILLock gilLock;
runCallbacks(args);
// Clear the callbackExecArgs and delete all objects whilst we still have the GIL
args.reset();
}
// The GIL must be owned when calling this method
void ScintillaWrapper::runCallbacks(std::shared_ptr<CallbackExecArgs> args)
{
DEBUG_TRACE(L"Consuming scintilla callbacks (beginning callback loop)\n");
for (std::list<boost::python::object>::iterator iter = args->getCallbacks()->begin(); iter != args->getCallbacks()->end(); ++iter)
{
DEBUG_TRACE(L"Scintilla callback, got GIL, calling callback\n");
try
{
// Perform the callback with a single argument - the dictionary of parameters for the notification
boost::python::object callback(*iter);
callback(*(args->getParams()));
}
catch(...)
{
if (PyErr_Occurred())
{
DEBUG_TRACE(L"Python Error calling python callback");
PyErr_Print();
}
else
{
DEBUG_TRACE(L"Non-Python exception occurred calling python callback");
}
}
DEBUG_TRACE(L"Scintilla callback, end of callback, releasing GIL\n");
}
DEBUG_TRACE(L"Finished consuming scintilla callbacks\n");
}
bool ScintillaWrapper::addSyncCallback(boost::python::object callback, boost::python::list events)
{
return addCallbackImpl(callback, events, false);
}
bool ScintillaWrapper::addAsyncCallback(boost::python::object callback, boost::python::list events)
{
return addCallbackImpl(callback, events, true);
}
bool ScintillaWrapper::addCallbackImpl(boost::python::object callback, boost::python::list events, bool isAsync)
{
if (PyCallable_Check(callback.ptr()))
{
{
NppPythonScript::MutexHolder hold(m_callbackMutex);
size_t eventCount = _len(events);
for(idx_t i = 0; i < eventCount; ++i)
{
Py_INCREF(callback.ptr());
m_callbacks.insert(std::pair<int, boost::shared_ptr<ScintillaCallback> >(boost::python::extract<int>(events[i]),
boost::shared_ptr<ScintillaCallback>(new ScintillaCallback(callback, isAsync))));
}
m_notificationsEnabled = true;
}
startConsumer();
return true;
}
else
{
return false;
}
}
void ScintillaWrapper::clearCallbackFunction(boost::python::object callback)
{
NppPythonScript::MutexHolder hold(m_callbackMutex);
for(callbackT::iterator it = m_callbacks.begin(); it != m_callbacks.end();)
{
if (callback == it->second->getCallback())
{
it = m_callbacks.erase(it);
}
else
{
++it;
}
}
if (m_callbacks.empty())
{
m_notificationsEnabled = false;
}
}
void ScintillaWrapper::clearCallbackEvents(boost::python::list events)
{
NppPythonScript::MutexHolder hold(m_callbackMutex);
for(callbackT::iterator it = m_callbacks.begin(); it != m_callbacks.end(); )
{
if(boost::python::extract<bool>(events.contains(it->first)))
{
it = m_callbacks.erase(it);
}
else
{
++it;
}
}
if (m_callbacks.empty())
{
m_notificationsEnabled = false;
}
}
void ScintillaWrapper::clearCallback(boost::python::object callback, boost::python::list events)
{
NppPythonScript::MutexHolder hold(m_callbackMutex);
for(callbackT::iterator it = m_callbacks.begin(); it != m_callbacks.end(); )
{
if(it->second->getCallback() == callback && boost::python::extract<bool>(events.contains(it->first)))
{
it = m_callbacks.erase(it);
}
else
{
++it;
}
}
if (m_callbacks.empty())
{
m_notificationsEnabled = false;
}
}
void ScintillaWrapper::clearAllCallbacks()
{
NppPythonScript::MutexHolder hold(m_callbackMutex);
for(callbackT::iterator it = m_callbacks.begin(); it != m_callbacks.end(); )
{
it = m_callbacks.erase(it);
}
if (m_callbacks.empty())
{
m_notificationsEnabled = false;
}
}
void ScintillaWrapper::forEachLine(PyObject* function)
{
if (PyCallable_Check(function))
{
BeginUndoAction();
intptr_t lineCount = GetLineCount();
for(int line = 0; line < lineCount;)
{
boost::python::object result = boost::python::call<boost::python::object>(function, GetLine(line), line, lineCount);
if (result.is_none() || !PyLong_Check(result.ptr()))
{
++line;
}
else
{
line += PyLong_AsLong(result.ptr());
}
lineCount = GetLineCount();
}
EndUndoAction();
}
}
void ScintillaWrapper::deleteLine(int lineNumber)
{
intptr_t start = PositionFromLine(lineNumber);
intptr_t lineCount = GetLineCount();
intptr_t end;
if (lineCount > lineNumber)
{
end = PositionFromLine(lineNumber + 1);
}
else
{
end = GetLineEndPosition(lineNumber);
}
setTarget(start, end);
this->ReplaceTarget(boost::python::str(""));
}
void ScintillaWrapper::replaceLine(int lineNumber, boost::python::object newContents)
{
intptr_t start = PositionFromLine(lineNumber);
intptr_t end = GetLineEndPosition(lineNumber);
setTarget(start, end);
ReplaceTarget(newContents);
}
void ScintillaWrapper::replaceWholeLine(int lineNumber, boost::python::object newContents)
{
intptr_t start = PositionFromLine(lineNumber);
intptr_t end;
if (GetLineCount() > lineNumber)
{
end = PositionFromLine(lineNumber + 1);
}
else
{
end = GetLength();
}
setTarget(start, end);
ReplaceTarget(newContents);
}
boost::python::tuple ScintillaWrapper::getUserLineSelection()
{
intptr_t start = GetSelectionStart();
intptr_t end = GetSelectionEnd();
if (start == end)
{
start = 0;
end = GetLineCount() - 1;
}
else
{
start = LineFromPosition(start);
end = LineFromPosition(end);
}
return boost::python::make_tuple(start, end);
}
boost::python::tuple ScintillaWrapper::getUserCharSelection()
{
intptr_t start = GetSelectionStart();
intptr_t end = GetSelectionEnd();
if (start == end)
{
start = 0;
end = GetLength();
}
return boost::python::make_tuple(start, end);
}
void ScintillaWrapper::setTarget(intptr_t start, intptr_t end)
{
SetTargetStart(start);
SetTargetEnd(end);
}
void deleteReplaceEntry(NppPythonScript::ReplaceEntry* entry)
{
delete entry;
}
const char *ScintillaWrapper::getCurrentAnsiCodePageName()
{
UINT currentAcp = ::GetACP();
switch(currentAcp)
{
case 1250:
return "cp1250";
case 1251:
return "cp1251";
case 1252:
return "cp1252";
case 1253:
return "cp1253";
case 1254:
return "cp1254";
case 1255:
return "cp1255";
case 1256:
return "cp1256";
case 1257:
return "cp1257";
case 1258:
return "cp1258";
case 50220:
return "iso-2022-jp";
case 28591:
return "iso-8859-1";
case 28592:
return "iso-8859-2";
case 28593:
return "iso-8859-3";
case 28594:
return "iso-8859-4";
case 28595:
return "iso-8859-5";
case 28596:
return "iso-8859-6";
case 28597:
return "iso-8859-7";
case 28598:
return "iso-8859-8";
case 28599:
return "iso-8859-9";
case 28603:
return "iso-8859-13";
case 28605:
return "iso-8859-15";
default:
// Windows-1252 is a reasonable "english" default. If there's more standard codepages that python supports,
// we can add them in as requests come in
return "windows-1252";
}
}
std::string ScintillaWrapper::extractEncodedString(boost::python::object str, intptr_t toCodePage)
{
std::string resultStr;
int searchLength;
if (PyUnicode_Check(str.ptr()))
{
const char *codePageName = "utf-8";
if (CP_UTF8 != toCodePage)
{
codePageName = getCurrentAnsiCodePageName();
}
//TODO how to get str.attr("encode")(codePageName) working again here
//currently this is always unicode (utf16 or utf8??), the internal representation of python3
boost::python::object searchUtf8(str.attr("__str__")());
resultStr.append(boost::python::extract<const char*>(searchUtf8));
}
else
{
// It's not a unicode string, so just take the string representation of it
boost::python::object searchStringObject(str.attr("__str__")());
searchLength = boost::python::extract<int>(searchStringObject.attr("__len__")());
resultStr.append(boost::python::extract<const char*>(searchStringObject), searchLength);
}
return resultStr;
}
NppPythonScript::ReplaceEntry *ScintillaWrapper::convertWithPython(const char * /* text */, NppPythonScript::Match *match, void *state)
{
ScintillaWrapper* instance = reinterpret_cast<ScintillaWrapper*>(state);
NppPythonScript::GroupDetail *wholeGroup = match->group(0);
boost::python::str replacement(instance->m_pythonReplaceFunction(boost::ref(match)));
std::string replacementStr = boost::python::extract<const char *>(replacement);
NppPythonScript::ReplaceEntry *entry = new NppPythonScript::ReplaceEntry(wholeGroup->start(), wholeGroup->end(), replacementStr.c_str(), replacementStr.size());
return entry;
}
bool ScintillaWrapper::searchPythonHandler(const char * /* text */, NppPythonScript::Match *match, void *state)
{
ScintillaWrapper* instance = reinterpret_cast<ScintillaWrapper*>(state);
boost::python::object result = instance->m_pythonMatchHandler(boost::ref(match));
// Should not continue, if and only if the result returned was === False
if (!result.is_none() && PyBool_Check(result.ptr()) && false == boost::python::extract<bool>(result))
{
return false;
}
return true;
}
void ScintillaWrapper::replacePlain(boost::python::object searchStr, boost::python::object replaceStr)
{
replacePlainFlags(searchStr, replaceStr, NppPythonScript::python_re_flag_literal);
}
void ScintillaWrapper::replacePlainFlags(boost::python::object searchStr, boost::python::object replaceStr, int flags)
{
replacePlainFlagsStartEndMaxCount(searchStr, replaceStr, flags, -1, -1, 0);
}
void ScintillaWrapper::replacePlainFlagsStart(boost::python::object searchStr, boost::python::object replaceStr, int flags, int startPosition)
{
replacePlainFlagsStartEndMaxCount(searchStr, replaceStr, flags, startPosition, -1, 0);
}
void ScintillaWrapper::replacePlainFlagsStartEnd(boost::python::object searchStr, boost::python::object replaceStr, int flags, int startPosition, int endPosition)
{
replacePlainFlagsStartEndMaxCount(searchStr, replaceStr, flags, startPosition, endPosition, 0);
}
void ScintillaWrapper::replacePlainFlagsStartEndMaxCount(boost::python::object searchStr, boost::python::object replaceStr, int flags, int startPosition, int endPosition, int maxCount)
{
NppPythonScript::python_re_flags resultFlags = NppPythonScript::python_re_flag_literal;
// Mask off everything but ignorecase
resultFlags = (NppPythonScript::python_re_flags)(resultFlags | (flags & NppPythonScript::python_re_flag_ignorecase));
replaceImpl(searchStr, replaceStr,
maxCount,
resultFlags,
startPosition,
endPosition
);
}
void ScintillaWrapper::replaceRegex(boost::python::object searchStr, boost::python::object replaceStr)
{
replaceImpl(searchStr, replaceStr, 0, NppPythonScript::python_re_flag_normal, -1, -1);
}
void ScintillaWrapper::replaceRegexFlags(boost::python::object searchStr, boost::python::object replaceStr, int flags)
{
replaceImpl(searchStr, replaceStr, 0, (NppPythonScript::python_re_flags)flags, -1, -1);
}
void ScintillaWrapper::replaceRegexFlagsStart(boost::python::object searchStr, boost::python::object replaceStr, int flags, int start)
{
replaceImpl(searchStr, replaceStr, 0, (NppPythonScript::python_re_flags)flags, start, -1);
}
void ScintillaWrapper::replaceRegexFlagsStartEnd(boost::python::object searchStr, boost::python::object replaceStr, int flags, int start, int end)
{
replaceImpl(searchStr, replaceStr, 0, (NppPythonScript::python_re_flags)flags, start, end);
}
void ScintillaWrapper::replaceRegexFlagsStartEndMaxCount(boost::python::object searchStr, boost::python::object replaceStr, int flags, int start, int end, int count)
{
replaceImpl(searchStr, replaceStr, count, (NppPythonScript::python_re_flags)flags, start, end);
}
void ScintillaWrapper::replaceImpl(boost::python::object searchStr, boost::python::object replaceStr,
int maxCount,
NppPythonScript::python_re_flags flags,
int startPosition,
int endPosition)
{
intptr_t currentDocumentCodePage = this->GetCodePage();
std::string searchChars = extractEncodedString(searchStr, currentDocumentCodePage);
std::string replaceChars;
bool isPythonReplaceFunction = true;
if (!PyFunction_Check(replaceStr.ptr()))
{
isPythonReplaceFunction = false;
replaceChars = extractEncodedString(replaceStr, currentDocumentCodePage);
}
std::list<NppPythonScript::ReplaceEntry*> replacements;
const char *text = reinterpret_cast<const char *>(callScintilla(SCI_GETCHARACTERPOINTER));
intptr_t length = callScintilla(SCI_GETLENGTH);
if (startPosition < 0)
{
startPosition = 0;
}
if (endPosition > 0 && endPosition < length)
{
length = endPosition;
}
if (CP_UTF8 == currentDocumentCodePage)
{
NppPythonScript::Replacer<NppPythonScript::Utf8CharTraits> replacer;
if (isPythonReplaceFunction)
{
m_pythonReplaceFunction = replaceStr;
replacer.startReplace(text, length, startPosition, maxCount, searchChars.c_str(), &ScintillaWrapper::convertWithPython, reinterpret_cast<void*>(this), flags, replacements);
}
else
{
replacer.startReplace(text, length, startPosition, maxCount, searchChars.c_str(), replaceChars.c_str(), flags, replacements);
}
}
else
{
NppPythonScript::Replacer<NppPythonScript::AnsiCharTraits> replacer;
if (isPythonReplaceFunction)
{
m_pythonReplaceFunction = replaceStr;
replacer.startReplace(text, length, startPosition, maxCount, searchChars.c_str(), &ScintillaWrapper::convertWithPython, reinterpret_cast<void*>(this), flags, replacements);
}
else
{
replacer.startReplace(text, length, startPosition, maxCount, searchChars.c_str(), replaceChars.c_str(), flags, replacements);
}
}
NppPythonScript::ReplacementContainer replacementContainer(&replacements, this);
BeginUndoAction();
CommunicationInfo commInfo{};
commInfo.internalMsg = PYSCR_RUNREPLACE;
commInfo.srcModuleName = _T("PythonScript.dll");
TCHAR pluginName[] = _T("PythonScript.dll");
commInfo.info = reinterpret_cast<void*>(&replacementContainer);
GILRelease release;
::SendMessage(m_hNotepad, NPPM_MSGTOPLUGIN, reinterpret_cast<WPARAM>(pluginName), reinterpret_cast<LPARAM>(&commInfo));
EndUndoAction();
for_each(replacements.begin(), replacements.end(), deleteReplaceEntry);
}
void ScintillaWrapper::searchPlain(boost::python::object searchStr, boost::python::object matchFunction)
{
searchPlainImpl(searchStr, matchFunction, 0, 0, -1, -1);
}
void ScintillaWrapper::searchRegex(boost::python::object searchStr, boost::python::object matchFunction)
{
searchImpl(searchStr, matchFunction, 0, NppPythonScript::python_re_flag_normal, -1, -1);
}
void ScintillaWrapper::searchRegexFlags(boost::python::object searchStr, boost::python::object matchFunction, int flags)
{
searchImpl(searchStr, matchFunction, 0, (NppPythonScript::python_re_flags)flags, -1, -1);
}
void ScintillaWrapper::searchRegexFlagsStart(boost::python::object searchStr, boost::python::object matchFunction, int flags, int startPosition)
{
searchImpl(searchStr, matchFunction, 0, (NppPythonScript::python_re_flags)flags, startPosition, -1);
}
void ScintillaWrapper::searchRegexFlagsStartEnd(boost::python::object searchStr, boost::python::object matchFunction, int flags, int startPosition, int endPosition)
{
searchImpl(searchStr, matchFunction, 0, (NppPythonScript::python_re_flags)flags, startPosition, endPosition);
}
void ScintillaWrapper::searchRegexFlagsStartEndCount(boost::python::object searchStr, boost::python::object matchFunction, int flags, int startPosition, int endPosition, int maxCount)
{
searchImpl(searchStr, matchFunction, maxCount, (NppPythonScript::python_re_flags)flags, startPosition, endPosition);
}
void ScintillaWrapper::searchPlainFlags(boost::python::object searchStr, boost::python::object matchFunction, int flags)
{
searchPlainImpl(searchStr, matchFunction, 0, (NppPythonScript::python_re_flags)flags, -1, -1);
}
void ScintillaWrapper::searchPlainFlagsStart(boost::python::object searchStr, boost::python::object matchFunction, int flags, int startPosition)
{
searchPlainImpl(searchStr, matchFunction, 0, (NppPythonScript::python_re_flags)flags, startPosition, -1);
}
void ScintillaWrapper::searchPlainFlagsStartEnd(boost::python::object searchStr, boost::python::object matchFunction, int flags, int startPosition, int endPosition)
{
searchPlainImpl(searchStr, matchFunction, 0, (NppPythonScript::python_re_flags)flags, startPosition, endPosition);
}
void ScintillaWrapper::searchPlainFlagsStartEndCount(boost::python::object searchStr, boost::python::object matchFunction, int flags, int startPosition, int endPosition, int maxCount)
{
searchPlainImpl(searchStr, matchFunction, maxCount, (NppPythonScript::python_re_flags)flags, startPosition, endPosition);
}
void ScintillaWrapper::searchPlainImpl(boost::python::object searchStr, boost::python::object matchFunction, int maxCount, int flags, int startPosition, int endPosition)
{
// Include literal flag, and mask off from the user flags everything but ignorecase
NppPythonScript::python_re_flags resultFlags = (NppPythonScript::python_re_flags)
(NppPythonScript::python_re_flag_literal
| (flags & NppPythonScript::python_re_flag_ignorecase)
);
searchImpl(searchStr, matchFunction, maxCount, resultFlags, startPosition, endPosition);
}
void ScintillaWrapper::searchImpl(boost::python::object searchStr,
boost::python::object matchFunction,
int maxCount,
NppPythonScript::python_re_flags flags,
int startPosition,
int endPosition)
{
intptr_t currentDocumentCodePage = this->GetCodePage();
std::string searchChars = extractEncodedString(searchStr, currentDocumentCodePage);
if (!PyCallable_Check(matchFunction.ptr()))
{
throw NppPythonScript::ArgumentException("match parameter must be callable, i.e. either a function or a lambda expression");
}
const char *text = reinterpret_cast<const char *>(callScintilla(SCI_GETCHARACTERPOINTER));
intptr_t length = callScintilla(SCI_GETLENGTH);
if (startPosition < 0)
{
startPosition = 0;
}
if (endPosition > 0 && endPosition < length)
{
length = endPosition;
}
m_pythonMatchHandler = matchFunction;
if (CP_UTF8 == currentDocumentCodePage)
{
NppPythonScript::Replacer<NppPythonScript::Utf8CharTraits> replacer;
replacer.search(text, length, startPosition, maxCount, searchChars.c_str(), &ScintillaWrapper::searchPythonHandler, reinterpret_cast<void*>(this), flags);
}
else
{
NppPythonScript::Replacer<NppPythonScript::AnsiCharTraits> replacer;
replacer.search(text, length, startPosition, maxCount, searchChars.c_str(), &ScintillaWrapper::searchPythonHandler, reinterpret_cast<void*>(this), flags);
}
}
boost::python::str ScintillaWrapper::getWord(boost::python::object position, boost::python::object useOnlyWordChars /* = true */)
{
intptr_t pos;
if (position.is_none())
{
pos = callScintilla(SCI_GETCURRENTPOS);
}
else
{
pos = boost::python::extract<int>(position);
}
bool wordChars;
if (useOnlyWordChars.is_none())
{
wordChars = true;
}
else
{
wordChars = boost::python::extract<bool>(useOnlyWordChars);
}
intptr_t startPos = callScintilla(SCI_WORDSTARTPOSITION, pos, wordChars);