-
Notifications
You must be signed in to change notification settings - Fork 351
/
Copy pathlatexeditorview.cpp
3572 lines (3261 loc) · 129 KB
/
latexeditorview.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
/***************************************************************************
* copyright : (C) 2008 by Benito van der Zander *
* http://www.xm1math.net/texmaker/ *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "latexeditorview.h"
#include "latexeditorview_config.h"
#include "filedialog.h"
#include "latexcompleter.h"
#include "latexdocument.h"
#include "smallUsefulFunctions.h"
#include "spellerutility.h"
#include "tablemanipulation.h"
#include "qdocumentline.h"
#include "qdocumentline_p.h"
#include "qdocumentcommand.h"
#include "qlinemarksinfocenter.h"
#include "qformatfactory.h"
#include "qlanguagedefinition.h"
#include "qnfadefinition.h"
#include "qnfa.h"
#include "qcodeedit.h"
#include "qeditor.h"
#include "qeditorinputbinding.h"
#include "qlinemarkpanel.h"
#include "qlinenumberpanel.h"
#include "qfoldpanel.h"
#include "qgotolinepanel.h"
#include "qlinechangepanel.h"
#include "qstatuspanel.h"
#include "qsearchreplacepanel.h"
#include "latexrepository.h"
#include "latexparser/latexparsing.h"
#include "latexcompleter_config.h"
#include "scriptengine.h"
#include "diffoperations.h"
#include "help.h"
#include "bidiextender.h"
#include <random>
//------------------------------Default Input Binding--------------------------------
/*!
* \brief default keyboard binding for normal operation
*/
class DefaultInputBinding: public QEditorInputBinding
{
// Q_OBJECT not possible because inputbinding is no qobject
public:
DefaultInputBinding(): completerConfig(nullptr), editorViewConfig(nullptr), contextMenu(nullptr), isDoubleClick(false) {}
virtual QString id() const
{
return "TXS::DefaultInputBinding";
}
virtual QString name() const
{
return "TXS::DefaultInputBinding";
}
virtual bool keyPressEvent(QKeyEvent *event, QEditor *editor);
virtual void postKeyPressEvent(QKeyEvent *event, QEditor *editor);
virtual bool keyReleaseEvent(QKeyEvent *event, QEditor *editor);
virtual bool mousePressEvent(QMouseEvent *event, QEditor *editor);
virtual bool mouseReleaseEvent(QMouseEvent *event, QEditor *editor);
virtual bool mouseDoubleClickEvent(QMouseEvent *event, QEditor *editor);
virtual bool mouseMoveEvent(QMouseEvent *event, QEditor *editor);
virtual bool contextMenuEvent(QContextMenuEvent *event, QEditor *editor);
private:
bool runMacros(QKeyEvent *event, QEditor *editor);
bool autoInsertLRM(QKeyEvent *event, QEditor *editor);
void checkLinkOverlay(QPoint mousePos, Qt::KeyboardModifiers modifiers, QEditor *editor);
friend class LatexEditorView;
const LatexCompleterConfig *completerConfig;
const LatexEditorViewConfig *editorViewConfig;
QList<QAction *> baseActions;
QMenu *contextMenu;
QString lastSpellCheckedWord;
QPoint lastMousePressLeft;
bool isDoubleClick; // event sequence of a double click: press, release, double click, release - this is true on the second release
Qt::KeyboardModifiers modifiersWhenPressed;
int contextMenu_row=-1;
int contextMenu_col=-1;
};
static const QString LRMStr = QChar(LRM);
bool DefaultInputBinding::runMacros(QKeyEvent *event, QEditor *editor)
{
Q_ASSERT(completerConfig);
QLanguageDefinition *language = editor->document() ? editor->document()->languageDefinition() : nullptr;
QDocumentLine line = editor->cursor().selectionStart().line();
int column = editor->cursor().selectionStart().columnNumber();
QString prev = line.text().mid(0, column) + event->text();
if(event->text().isEmpty() && event->key()==Qt::Key_Tab){
// workaround for #2866 (tab as trigger in macro on osx)
prev+="\t";
}
const LatexDocument *doc = qobject_cast<LatexDocument *>(editor->document());
StackEnvironment env;
foreach (const Macro &m, completerConfig->userMacros) {
if (!m.isActiveForTrigger(Macro::ST_REGEX)) continue;
if (!m.isActiveForLanguage(language)) continue;
if(m.hasFormatTriggers()){
// check formats at column from overlays
QList<int> formats=m.getFormatExcludeTriggers();
if(!formats.isEmpty()){
QFormatRange fr = line.getOverlayAt(column, formats);
if(fr.isValid()){
continue;
}
}
formats=m.getFormatTriggers();
if(!formats.isEmpty()){
QFormatRange fr = line.getOverlayAt(column, formats);
if(!fr.isValid()){
continue;
}
}
}
QStringList envTriggers = m.getTriggerInEnvs();
if(!envTriggers.isEmpty()){
if(env.isEmpty()){
doc->getEnv(editor->cursor().lineNumber(),env);
}
// use topEnv as trigger env
const QStringList ignoreEnv = {"document","normal"};
bool inMath=false;
bool passed=false;
if(!env.isEmpty() && !ignoreEnv.contains(env.top().name)){
QString envName=env.top().name;
QStringList envAliases = doc->lp->environmentAliases.values(envName);
bool aliasFound=std::any_of(envAliases.cbegin(),envAliases.cend(),[&envTriggers](const QString &alias){
return envTriggers.contains(alias);
});
if(envTriggers.contains(envName)|| aliasFound){
passed=true;
if(envName=="math"){
// continued math mode from previous line
passed=false;
inMath=true;
}
}
}
// special treatment for math env as that be be toggled with special symbols
if(!passed && envTriggers.contains("math")){
QVector<QParenthesis>parenthesis=line.parentheses();
for(int i=0;i<parenthesis.size();++i){
QParenthesis &p=parenthesis[i];
if(p.id==61){
if(p.offset<column){
inMath=(p.role & QParenthesis::Open)>0;
}
if(p.offset>=column){
break;
}
}
}
if(!inMath){
continue; // skip further trigger checks
}else{
passed=true;
}
}
if(!passed)
continue; // skip further trigger checks, no valid env found
}
const QRegularExpression &r = m.triggerRegex;
QRegularExpressionMatch match=r.match(prev);
if (match.hasMatch()) {
// force last match which basically is right-most match, see #2448
while(true){
int offset=match.capturedStart()+1;
QRegularExpressionMatch test=r.match(prev,offset);
if(test.hasMatch()){
match=test;
}else{
break;
}
}
QDocumentCursor c = editor->cursor();
bool block = false;
int realMatchLen = match.capturedLength();
//if (m.triggerLookBehind) realMatchLen -= match.captured(1).length();
if (c.hasSelection() || realMatchLen > 1)
block = true;
if (block) editor->document()->beginMacro();
if (c.hasSelection()) {
editor->cutBuffer = c.selectedText();
c.removeSelectedText();
}
if (match.capturedLength() > 1) {
c.movePosition(realMatchLen - 1, QDocumentCursor::PreviousCharacter, QDocumentCursor::KeepAnchor);
c.removeSelectedText();
editor->setCursor(c);
}
LatexEditorView *view = editor->property("latexEditor").value<LatexEditorView *>();
REQUIRE_RET(view, true);
emit view->execMacro(m, MacroExecContext(Macro::ST_REGEX, match.capturedTexts()));
if (block) editor->document()->endMacro();
editor->cutBuffer.clear();
editor->emitCursorPositionChanged(); //prevent rogue parenthesis highlightations
/* if (editor->languageDefinition())
editor->languageDefinition()->clearMatches(editor->document());
*/
return true;
}
}
return false;
}
bool DefaultInputBinding::autoInsertLRM(QKeyEvent *event, QEditor *editor)
{
const QString &text = event->text();
if (editorViewConfig->autoInsertLRM && text.length() == 1 && editor->cursor().isRTL()) {
if (text.at(0) == '}') {
bool autoOverride = editor->isAutoOverrideText("}");
bool previousIsLRM = editor->cursor().previousChar().unicode() == LRM;
bool block = previousIsLRM || autoOverride;
if (block) editor->document()->beginMacro();
if (previousIsLRM) editor->cursor().deletePreviousChar(); //todo mirrors
if (autoOverride) {
editor->write("}"); //separated, so autooverride works
editor->write(LRMStr);
} else editor->write("}" + LRMStr);
if (block) editor->document()->endMacro();
return true;
}
}
return false;
}
void DefaultInputBinding::checkLinkOverlay(QPoint mousePos, Qt::KeyboardModifiers modifiers, QEditor *editor)
{
if (modifiers == Qt::ControlModifier) {
LatexEditorView *edView = qobject_cast<LatexEditorView *>(editor->parentWidget());
QDocumentCursor cursor = editor->cursorForPosition(mousePos);
edView->checkForLinkOverlay(cursor);
} else {
// reached for example when Ctrl+Shift is pressed
LatexEditorView *edView = qobject_cast<LatexEditorView *>(editor->parentWidget()); //a qobject is necessary to retrieve events
edView->removeLinkOverlay();
}
}
bool DefaultInputBinding::keyPressEvent(QKeyEvent *event, QEditor *editor)
{
if (LatexEditorView::completer && LatexEditorView::completer->acceptTriggerString(event->text())
&& (editor->currentPlaceHolder() < 0 || editor->currentPlaceHolder() >= editor->placeHolderCount() || editor->getPlaceHolder(editor->currentPlaceHolder()).mirrors.isEmpty() || editor->getPlaceHolder(editor->currentPlaceHolder()).affector != BracketInvertAffector::instance())
&& !editor->flag(QEditor::Overwrite)) {
//update completer if necessary
editor->emitNeedUpdatedCompleter();
bool autoOverriden = editor->isAutoOverrideText(event->text());
if (editorViewConfig->autoInsertLRM && event->text() == "\\" && editor->cursor().isRTL())
editor->write(LRMStr + event->text());
else
editor->write(event->text());
if (autoOverriden) LatexEditorView::completer->complete(editor, LatexCompleter::CF_OVERRIDEN_BACKSLASH);
else {
EnumsTokenType::TokenType ctx = Parsing::getCompleterContext(editor->cursor().line().handle(), editor->cursor().columnNumber());
if(ctx==EnumsTokenType::def) return true;
// check for environment
const LatexDocument *doc = qobject_cast<LatexDocument *>(editor->document());
StackEnvironment env;
doc->getEnv(editor->cursor().lineNumber(),env);
// use topEnv as completion filter for commands
const QStringList ignoreEnv = {"document","normal"};
if(!env.isEmpty() && !ignoreEnv.contains(env.top().name)){
QString envName=env.top().name;
QStringList envAliases = doc->lp->environmentAliases.values(envName);
if(!envAliases.isEmpty()){
envName=envAliases.first();
}
LatexEditorView::completer->setFilter(envName);
}
LatexCompleter::CompletionFlags flags= ctx==EnumsTokenType::width ? LatexCompleter::CF_FORCE_LENGTH : LatexCompleter::CompletionFlag(0) ;
LatexEditorView::completer->complete(editor, flags);
}
return true;
}
if (!event->text().isEmpty() || event->key()==Qt::Key_Tab) {
if (!editor->flag(QEditor::Overwrite) && runMacros(event, editor))
return true;
if (autoInsertLRM(event, editor))
return true;
} else {
if (event->key() == Qt::Key_Control) {
editor->setMouseTracking(true);
QPoint mousePos(editor->mapToFrame(editor->mapFromGlobal(QCursor::pos())));
checkLinkOverlay(mousePos, event->modifiers(), editor);
}
}
if (LatexEditorView::hideTooltipWhenLeavingLine != -1 && editor->cursor().lineNumber() != LatexEditorView::hideTooltipWhenLeavingLine) {
LatexEditorView::hideTooltipWhenLeavingLine = -1;
QToolTip::hideText();
}
return false;
}
void DefaultInputBinding::postKeyPressEvent(QKeyEvent *event, QEditor *editor)
{
QString txt=event->text();
if(txt.length()!=1)
return;
QChar c=txt.at(0);
if ( c== ',' || c.isLetter()) {
LatexEditorView *view = editor->property("latexEditor").value<LatexEditorView *>();
Q_ASSERT(view);
if (completerConfig && completerConfig->enabled)
view->mayNeedToOpenCompleter(c!=',');
}
}
bool DefaultInputBinding::keyReleaseEvent(QKeyEvent *event, QEditor *editor)
{
if (event->key() == Qt::Key_Control) {
editor->setMouseTracking(false);
LatexEditorView *edView = qobject_cast<LatexEditorView *>(editor->parentWidget()); //a qobject is necessary to retrieve events
edView->removeLinkOverlay();
}
return false;
}
bool DefaultInputBinding::mousePressEvent(QMouseEvent *event, QEditor *editor)
{
LatexEditorView *edView = nullptr;
switch (event->button()) {
case Qt::XButton1:
edView = qobject_cast<LatexEditorView *>(editor->parentWidget());
emit edView->mouseBackPressed();
return true;
case Qt::XButton2:
edView = qobject_cast<LatexEditorView *>(editor->parentWidget());
emit edView->mouseForwardPressed();
return true;
case Qt::LeftButton:
edView = qobject_cast<LatexEditorView *>(editor->parentWidget());
emit edView->cursorChangeByMouse();
lastMousePressLeft = event->pos();
modifiersWhenPressed = event->modifiers();
return false;
default:
return false;
}
}
bool DefaultInputBinding::mouseReleaseEvent(QMouseEvent *event, QEditor *editor)
{
if (isDoubleClick) {
isDoubleClick = false;
return false;
}
isDoubleClick = false;
if (event->modifiers() == Qt::ControlModifier && modifiersWhenPressed == event->modifiers() && event->button() == Qt::LeftButton) {
// Ctrl+LeftClick
int distanceSqr = (event->pos().x() - lastMousePressLeft.x()) * (event->pos().x() - lastMousePressLeft.x()) + (event->pos().y() - lastMousePressLeft.y()) * (event->pos().y() - lastMousePressLeft.y());
if (distanceSqr > 4) // allow the user to accidentially move the mouse a bit
return false;
LatexEditorView *edView = qobject_cast<LatexEditorView *>(editor->parentWidget()); //a qobject is necessary to retrieve events
if (!edView) return false;
QDocumentCursor cursor = editor->cursorForPosition(editor->mapToContents(event->pos()));
if (edView->hasLinkOverlay()) {
LinkOverlay lo = edView->getLinkOverlay();
switch (lo.type) {
case LinkOverlay::RefOverlay:
emit edView->gotoDefinition(cursor);
return true;
case LinkOverlay::FileOverlay:
emit edView->openFile(lo.m_link.isEmpty() ? lo.text() : lo.m_link);
return true;
case LinkOverlay::UrlOverlay:
if (!QDesktopServices::openUrl(lo.text())) {
UtilsUi::txsWarning(LatexEditorView::tr("Could not open url:") + "\n" + lo.text());
}
return true;
case LinkOverlay::UsepackageOverlay:
edView->openPackageDocumentation(lo.text());
return true;
case LinkOverlay::BibFileOverlay:
emit edView->openFile(lo.text(), "bib");
return true;
case LinkOverlay::CiteOverlay:
emit edView->gotoDefinition(cursor);
return true;
case LinkOverlay::CommandOverlay:
emit edView->gotoDefinition(cursor);
return true;
case LinkOverlay::EnvOverlay:
emit edView->gotoDefinition(cursor);
return true;
case LinkOverlay::Invalid:
break;
}
}
if (!editor->languageDefinition()) return false;
if (editor->languageDefinition()->language() != "(La)TeX")
return false;
emit edView->syncPDFRequested(cursor);
return true;
}
return false;
}
bool DefaultInputBinding::mouseDoubleClickEvent(QMouseEvent *event, QEditor *editor)
{
Q_UNUSED(event)
Q_UNUSED(editor)
isDoubleClick = true;
return false;
}
bool DefaultInputBinding::contextMenuEvent(QContextMenuEvent *event, QEditor *editor)
{
if (!contextMenu) contextMenu = new QMenu(nullptr);
contextMenu->clear();
contextMenu->setProperty("isSpellingPopulated", QVariant()); // delete information on spelling
QDocumentCursor cursor;
if (event->reason() == QContextMenuEvent::Mouse) cursor = editor->cursorForPosition(editor->mapToContents(event->pos()));
else cursor = editor->cursor();
LatexEditorView *edView = qobject_cast<LatexEditorView *>(editor->parentWidget()); //a qobject is necessary to retrieve events
REQUIRE_RET(edView, false);
// check for context menu on preview picture
QRect pictRect = cursor.line().getCookie(QDocumentLine::PICTURE_COOKIE_DRAWING_POS).toRect();
if (pictRect.isValid()) {
QPoint posInDocCoordinates(event->pos().x() + edView->editor->horizontalOffset(), event->pos().y() + edView->editor->verticalOffset());
if (pictRect.contains(posInDocCoordinates)) {
// get removePreviewAction
// ok, this is not an ideal way of doing it because (i) it has to be in the baseActions (at least we Q_ASSERT this) and (ii) the iteration over the baseActions
// Alternatives: 1) include configmanager and use ConfigManager->getInstance()->getManagedAction() - Disadvantage: additional dependency
// 2) explicitly pass it to the editorView (like the base actions, but separate) - Disadvantage: code overhead
// 3) Improve the concept of base actions:
// LatexEditorView::addContextAction(QAction); called when creating the editorView
// LatexEditorView::getContextAction(QString); used here to populate the menu
bool removePreviewActionFound = false;
foreach (QAction *act, baseActions) {
if (act->objectName().endsWith("removePreviewLatex")) {
// inline preview context menu supplies the calling point in doc coordinates as data
contextMenu_row = editor->document()->indexOf(editor->lineAtPosition(posInDocCoordinates));
// slight performance penalty for use of lineNumber(), which is not stictly necessary because
// we convert it back to a QDocumentLine, but easier to handle together with the other cases
contextMenu->addAction(act);
removePreviewActionFound = true;
break;
}
}
Q_ASSERT(removePreviewActionFound);
QVariant vPixmap = cursor.line().getCookie(QDocumentLine::PICTURE_COOKIE);
if (vPixmap.isValid()) {
(contextMenu->addAction(LatexEditorView::tr("Copy Image"), edView, SLOT(copyImageFromAction())))->setData(vPixmap);
(contextMenu->addAction(LatexEditorView::tr("Save Image As..."), edView, SLOT(saveImageFromAction())))->setData(vPixmap);
}
contextMenu->exec(event->globalPos());
// reset context menu position
contextMenu_row=-1;
contextMenu_col=-1;
return true;
}
}
// normal context menu
bool validPosition = cursor.isValid() && cursor.line().isValid();
//LatexParser::ContextType context = LatexParser::Unknown;
QString ctxCommand;
if (validPosition) {
QFormatRange fr;
//spell checking
if (edView->speller) {
int pos;
if (cursor.hasSelection()) pos = (cursor.columnNumber() + cursor.anchorColumnNumber()) / 2;
else pos = cursor.columnNumber();
foreach (const int f, edView->grammarFormats) {
fr = cursor.line().getOverlayAt(pos, f);
if (fr.length > 0 && fr.format == f) {
QVariant var = cursor.line().getCookie(QDocumentLine::GRAMMAR_ERROR_COOKIE);
if (var.isValid()) {
edView->wordSelection=QDocumentCursor(editor->document(), cursor.lineNumber(), fr.offset);
edView->wordSelection.movePosition(fr.length, QDocumentCursor::NextCharacter, QDocumentCursor::KeepAnchor);
//editor->setCursor(wordSelection);
const QList<GrammarError> &errors = var.value<QList<GrammarError> >();
for (int i = 0; i < errors.size(); i++)
if (errors[i].offset <= cursor.columnNumber() && errors[i].offset + errors[i].length >= cursor.columnNumber()) {
edView->addReplaceActions(contextMenu, errors[i].corrections, true);
break;
}
}
}
}
fr = cursor.line().getOverlayAt(pos, SpellerUtility::spellcheckErrorFormat);
if (fr.length > 0 && fr.format == SpellerUtility::spellcheckErrorFormat) {
QString word = cursor.line().text().mid(fr.offset, fr.length);
if (!(editor->cursor().hasSelection() && editor->cursor().selectedText().length() > 0) || editor->cursor().selectedText() == word
|| editor->cursor().selectedText() == lastSpellCheckedWord) {
lastSpellCheckedWord = word;
word = latexToPlainWord(word);
edView->wordSelection=QDocumentCursor(editor->document(), cursor.lineNumber(), fr.offset);
edView->wordSelection.movePosition(fr.length, QDocumentCursor::NextCharacter, QDocumentCursor::KeepAnchor);
//editor->setCursor(wordSelection);
if ((editorViewConfig->contextMenuSpellcheckingEntryLocation == 0) ^ (event->modifiers() & editorViewConfig->contextMenuKeyboardModifiers)) {
edView->addSpellingActions(contextMenu, lastSpellCheckedWord, false);
contextMenu->addSeparator();
} else {
QMenu *spellingMenu = contextMenu->addMenu(LatexEditorView::tr("Spelling"));
spellingMenu->setProperty("word", lastSpellCheckedWord);
edView->connect(spellingMenu, SIGNAL(aboutToShow()), edView, SLOT(populateSpellingMenu()));
}
}
}
}
//citation checking
int f = edView->citationMissingFormat;
if (cursor.hasSelection()) fr = cursor.line().getOverlayAt((cursor.columnNumber() + cursor.anchorColumnNumber()) / 2, f);
else fr = cursor.line().getOverlayAt(cursor.columnNumber(), f);
if (fr.length > 0 && fr.format == f) {
QString word = cursor.line().text().mid(fr.offset, fr.length);
//editor->setCursor(editor->document()->cursor(cursor.lineNumber(), fr.offset, cursor.lineNumber(), fr.offset + fr.length)); // no need to select word as it is not changed anyway, see also #1034
QAction *act = new QAction(LatexEditorView::tr("New BibTeX Entry %1").arg(word), contextMenu);
edView->connect(act, SIGNAL(triggered()), edView, SLOT(requestCitation()));
contextMenu->addAction(act);
contextMenu->addSeparator();
}
//check input/include
//find context of cursor
QDocumentLineHandle *dlh = cursor.line().handle();
TokenList tl = dlh->getCookieLocked(QDocumentLine::LEXER_COOKIE).value<TokenList>();
int i = Parsing::getTokenAtCol(tl, cursor.columnNumber());
Token tk;
if (i >= 0)
tk = tl.at(i);
if (tk.type == Token::file) {
Token cmdTk=Parsing::getCommandTokenFromToken(tl,tk);
QString fn=tk.getText();
if(cmdTk.dlh && cmdTk.getText()=="\\subimport"){
int i=tl.indexOf(cmdTk);
TokenList tl2=tl.mid(i); // in case of several cmds in one line
QString path=Parsing::getArg(tl,Token::definition);
if(!path.endsWith("/")){
path+="/";
}
fn=path+fn;
}
QAction *act = new QAction(LatexEditorView::tr("Open %1").arg(tk.getText()), contextMenu);
act->setData(fn);
edView->connect(act, SIGNAL(triggered()), edView, SLOT(openExternalFile()));
contextMenu->addAction(act);
}
// bibliography command
if (tk.type == Token::bibfile) {
QAction *act = new QAction(LatexEditorView::tr("Open Bibliography"), contextMenu);
QString bibFile;
bibFile = tk.getText() + ".bib";
act->setData(bibFile);
edView->connect(act, SIGNAL(triggered()), edView, SLOT(openExternalFile()));
contextMenu->addAction(act);
}
//package help
if (tk.type == Token::package || tk.type == Token::documentclass) {
QAction *act = new QAction(LatexEditorView::tr("Open package documentation"), contextMenu);
QString packageName = tk.getText();
act->setText(act->text().append(QString(" (%1)").arg(packageName)));
act->setData(packageName);
edView->connect(act, SIGNAL(triggered()), edView, SLOT(openPackageDocumentation()));
contextMenu->addAction(act);
}
// help for any "known" command
if (tk.type == Token::command) {
ctxCommand = tk.getText();
QString command = ctxCommand;
if (ctxCommand == "\\begin" || ctxCommand == "\\end")
command = ctxCommand + "{" + Parsing::getArg(tl.mid(i + 1), dlh, 0, ArgumentList::Mandatory) + "}";
QString package = edView->document->parent->findPackageByCommand(command);
package.chop(4);
if (!package.isEmpty()) {
QAction *act = new QAction(LatexEditorView::tr("Open package documentation"), contextMenu);
act->setText(act->text().append(QString(" (%1)").arg(package)));
act->setData(package + "#" + command);
edView->connect(act, SIGNAL(triggered()), edView, SLOT(openPackageDocumentation()));
contextMenu->addAction(act);
}
}
// help for "known" environments
if (tk.type == Token::beginEnv || tk.type == Token::env) {
QString command = "\\begin{" + tk.getText() + "}";
QString package = edView->document->parent->findPackageByCommand(command);
package.chop(4);
if (!package.isEmpty()) {
QAction *act = new QAction(LatexEditorView::tr("Open package documentation"), contextMenu);
act->setText(act->text().append(QString(" (%1)").arg(package)));
act->setData(package + "#" + command);
edView->connect(act, SIGNAL(triggered()), edView, SLOT(openPackageDocumentation()));
contextMenu->addAction(act);
}
}
if (/* tk.type==Tokens::bibRef || TODO: bibliography references not yet handled by token system */ tk.type == Token::labelRef) {
QAction *act = new QAction(LatexEditorView::tr("Go to Definition"), contextMenu);
act->setData(QVariant().fromValue<QDocumentCursor>(cursor));
edView->connect(act, SIGNAL(triggered()), edView, SLOT(emitGotoDefinitionFromAction()));
contextMenu->addAction(act);
}
if (tk.type == Token::label || tk.type == Token::labelRef || tk.type == Token::labelRefList) {
QAction *act = new QAction(LatexEditorView::tr("Find Usages"), contextMenu);
act->setData(tk.getText());
act->setProperty("doc", QVariant::fromValue<LatexDocument *>(edView->document));
edView->connect(act, SIGNAL(triggered()), edView, SLOT(emitFindLabelUsagesFromAction()));
contextMenu->addAction(act);
}
if (tk.type == Token::word) {
QAction *act = new QAction(LatexEditorView::tr("Thesaurus..."), contextMenu);
act->setData(QPoint(cursor.anchorLineNumber(), cursor.anchorColumnNumber()));
edView->connect(act, SIGNAL(triggered()), edView, SLOT(triggeredThesaurus()));
contextMenu->addAction(act);
}
//resolve differences
if (edView) {
QList<int> fids;
fids << edView->deleteFormat << edView->insertFormat << edView->replaceFormat;
foreach (int fid, fids) {
if (cursor.hasSelection()) fr = cursor.line().getOverlayAt((cursor.columnNumber() + cursor.anchorColumnNumber()) / 2, fid);
else fr = cursor.line().getOverlayAt(cursor.columnNumber(), fid);
if (fr.length > 0 ) {
QVariant var = cursor.line().getCookie(QDocumentLine::DIFF_LIST_COOCKIE);
if (var.isValid()) {
DiffList diffList = var.value<DiffList>();
//QString word=cursor.line().text().mid(fr.offset,fr.length);
DiffOp op;
op.start = -1;
foreach (op, diffList) {
if (op.start <= cursor.columnNumber() && op.start + op.length >= cursor.columnNumber()) {
break;
}
op.start = -1;
}
if (op.start >= 0) {
QAction *act = new QAction(LatexEditorView::tr("use yours"), contextMenu);
act->setData(QPoint(cursor.lineNumber(), cursor.columnNumber()));
edView->connect(act, SIGNAL(triggered()), edView, SLOT(emitChangeDiff()));
contextMenu->addAction(act);
act = new QAction(LatexEditorView::tr("use other's"), contextMenu);
act->setData(QPoint(-cursor.lineNumber() - 1, cursor.columnNumber()));
edView->connect(act, SIGNAL(triggered()), edView, SLOT(emitChangeDiff()));
contextMenu->addAction(act);
break;
}
}
}
}
}
contextMenu->addSeparator();
}
contextMenu->addActions(baseActions);
// set context menu position
contextMenu_row=cursor.anchorLineNumber();
contextMenu_col=cursor.anchorColumnNumber();
if (validPosition) {
contextMenu->addSeparator();
QAction *act = new QAction(LatexEditorView::tr("Go to PDF"), contextMenu);
act->setData(QVariant().fromValue<QDocumentCursor>(cursor));
edView->connect(act, SIGNAL(triggered()), edView, SLOT(emitSyncPDFFromAction()));
contextMenu->addAction(act);
}
if (event->reason() == QContextMenuEvent::Mouse) contextMenu->exec(event->globalPos());
else {
QPointF curPoint = editor->cursor().documentPosition();
curPoint.ry() += editor->document()->getLineSpacing();
contextMenu->exec(editor->mapToGlobal(editor->mapFromContents(curPoint.toPoint())));
}
// reset position of context menu
contextMenu_row=-1;
contextMenu_col=-1;
event->accept();
return true;
}
bool DefaultInputBinding::mouseMoveEvent(QMouseEvent *event, QEditor *editor)
{
checkLinkOverlay(editor->mapToContents(event->pos()), event->modifiers(), editor);
return false;
}
DefaultInputBinding *defaultInputBinding = new DefaultInputBinding();
//----------------------------------LatexEditorView-----------------------------------
LatexCompleter *LatexEditorView::completer = nullptr;
int LatexEditorView::hideTooltipWhenLeavingLine = -1;
//Q_DECLARE_METATYPE(LatexEditorView *)
LatexEditorView::LatexEditorView(QWidget *parent, LatexEditorViewConfig *aconfig, LatexDocument *doc) : QWidget(parent), document(nullptr), latexPackageList(nullptr), spellerManager(nullptr), speller(nullptr), useDefaultSpeller(true), curChangePos(-1), config(aconfig), bibReader(nullptr), help(nullptr)
{
Q_ASSERT(config);
QVBoxLayout *mainlay = new QVBoxLayout(this);
mainlay->setSpacing(0);
#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
mainlay->setMargin(0);
#else
mainlay->setContentsMargins(0,0,0,0);
#endif
codeeditor = new QCodeEdit(false, this, doc);
editor = codeeditor->editor();
document = doc;
editor->setProperty("latexEditor", QVariant::fromValue<LatexEditorView *>(this));
lineMarkPanel = new QLineMarkPanel;
lineMarkPanel->setCursor(Qt::PointingHandCursor);
lineMarkPanelAction = codeeditor->addPanel(lineMarkPanel, QCodeEdit::West, false);
lineNumberPanel = new QLineNumberPanel;
lineNumberPanelAction = codeeditor->addPanel(lineNumberPanel, QCodeEdit::West, false);
QFoldPanel *foldPanel = new QFoldPanel;
lineFoldPanelAction = codeeditor->addPanel(foldPanel, QCodeEdit::West, false);
lineChangePanelAction = codeeditor->addPanel(new QLineChangePanel, QCodeEdit::West, false);
statusPanel = new QStatusPanel;
statusPanel->setFont(QApplication::font());
statusPanelAction = codeeditor->addPanel(statusPanel, QCodeEdit::South, false);
gotoLinePanel = new QGotoLinePanel;
gotoLinePanel->setFont(QApplication::font());
gotoLinePanelAction = codeeditor->addPanel(gotoLinePanel, QCodeEdit::South, false);
searchReplacePanel = new QSearchReplacePanel;
searchReplacePanel->setFont(QApplication::font());
searchReplacePanelAction = codeeditor->addPanel(searchReplacePanel, QCodeEdit::South, false);
searchReplacePanel->hide();
connect(searchReplacePanel, SIGNAL(showExtendedSearch()), this, SIGNAL(showExtendedSearch()));
connect(lineMarkPanel, SIGNAL(lineClicked(int)), this, SLOT(lineMarkClicked(int)));
connect(lineMarkPanel, SIGNAL(toolTipRequested(int,int)), this, SLOT(lineMarkToolTip(int,int)));
connect(lineMarkPanel, SIGNAL(contextMenuRequested(int,QPoint)), this, SLOT(lineMarkContextMenuRequested(int,QPoint)));
connect(foldPanel, SIGNAL(contextMenuRequested(int,QPoint)), this, SLOT(foldContextMenuRequested(int,QPoint)));
connect(editor, SIGNAL(hovered(QPoint)), this, SLOT(mouseHovered(QPoint)));
//connect(editor->document(),SIGNAL(contentsChange(int, int)),this,SLOT(documentContentChanged(int, int)));
connect(editor->document(), SIGNAL(lineDeleted(QDocumentLineHandle*,int)), this, SLOT(lineDeleted(QDocumentLineHandle*,int)));
connect(doc, SIGNAL(spellingDictChanged(QString)), this, SLOT(changeSpellingDict(QString)));
connect(doc, SIGNAL(bookmarkRemoved(QDocumentLineHandle*)), this, SIGNAL(bookmarkRemoved(QDocumentLineHandle*)));
connect(doc, SIGNAL(bookmarkAdded(QDocumentLineHandle*,int)), this, SIGNAL(bookmarkAdded(QDocumentLineHandle*,int)));
//editor->setFlag(QEditor::CursorJumpPastWrap,false);
editor->disableAccentHack(config->hackDisableAccentWorkaround);
editor->setInputBinding(defaultInputBinding);
defaultInputBinding->completerConfig = completer->getConfig();
defaultInputBinding->editorViewConfig = config;
Q_ASSERT(defaultInputBinding->completerConfig);
editor->document()->setLineEndingDirect(QDocument::Local);
mainlay->addWidget(editor);
setFocusProxy(editor);
//containedLabels.setPattern("(\\\\label)\\{(.+)\\}");
//containedReferences.setPattern("(\\\\ref|\\\\pageref)\\{(.+)\\}");
updateSettings();
lp = LatexParser::getInstance();
}
LatexEditorView::~LatexEditorView()
{
delete searchReplacePanel; // to force deletion of m_search before document. Otherwise crashes can come up (linux)
delete codeeditor; //explicit call destructor of codeeditor (although it has a parent, it is no qobject itself, but passed it to editor)
if (bibReader) {
bibReader->quit();
bibReader->wait();
}
}
void LatexEditorView::updateReplacementList(const QSharedPointer<LatexParser> cmds, bool forceUpdate)
{
QMap<QString, QString> replacementList;
bool differenceExists = false;
foreach (QString elem, cmds->possibleCommands["%replace"]) {
int i = elem.indexOf(" ");
if (i > 0) {
replacementList.insert(elem.left(i), elem.mid(i + 1));
if (mReplacementList.value(elem.left(i)) != elem.mid(i + 1))
differenceExists = true;
}
}
if (differenceExists || replacementList.count() != mReplacementList.count() || forceUpdate) {
mReplacementList = replacementList;
document->setReplacementList(mReplacementList);
reCheckSyntax(0); //force complete spellcheck
}
}
/*!
* \brief Helper class to update the palete of editor/codeeditor
* QCodeeditor does not use inheritance from a widget, so any palette automatism is disabled
* To counteract this deficiency, codeeditors children (panels) are updated explicitely
*
* It would probably be better to adapt qcodeeditor to an inheritance based model, but that may take effort and time
* \param pal new palette
*/
void LatexEditorView::updatePalette(const QPalette &pal)
{
editor->setPalette(pal);
for(QPanel *p:codeeditor->panels()){
p->setPalette(pal);
}
editor->horizontalScrollBar()->setPalette(pal);
editor->verticalScrollBar()->setPalette(pal);
}
/*!
* \brief force an redraw/update on all sidepanels like numberlines, foldlines, etc.
*/
void LatexEditorView::updatePanels()
{
for(QPanel *p:codeeditor->panels()){
p->update();
}
}
void LatexEditorView::paste()
{
if (completer->isVisible()) {
const QMimeData *d = QApplication::clipboard()->mimeData();
if ( d ) {
QString txt;
if ( d->hasFormat("text/plain") )
txt = d->text();
else if ( d->hasFormat("text/html") )
txt = d->html();
if (txt.contains("\n"))
txt.clear();
if (txt.isEmpty()) {
completer->close();
editor->paste();
} else {
completer->insertText(txt);
}
}
} else {
editor->paste();
}
}
void LatexEditorView::insertSnippet(QString text)
{
CodeSnippet(text).insert(editor);
}
void LatexEditorView::deleteLines(bool toStart, bool toEnd)
{
QList<QDocumentCursor> cursors = editor->cursors();
if (cursors.empty()) return;
document->beginMacro();
for (int i=0;i<cursors.size();i++)
cursors[i].removeSelectedText();
int cursorLine = cursors[0].lineNumber();
QMultiMap< int, QDocumentCursor* > map = getSelectedLines(cursors);
QList<int> lines = map.uniqueKeys();
QList<QDocumentCursor> newMirrors;
for (int i=lines.size()-1;i>=0;i--) {
QList<QDocumentCursor*> cursors = map.values(lines[i]);
REQUIRE(cursors.size());
if (toStart && toEnd) cursors[0]->eraseLine();
else {
int len = document->line(lines[i]).length();
int column = toStart ? 0 : len;
foreach (QDocumentCursor* c, cursors)
if (toStart) column = qMax(c->columnNumber(), column);
else column = qMin(c->columnNumber(), column);
QDocumentCursor c = document->cursor(lines[i], column, lines[i], toStart ? 0 : len);
c.removeSelectedText();
if (!toStart || !toEnd){
if (lines[i] == cursorLine) editor->setCursor(c);
else newMirrors << c;
}
}
}
document->endMacro();
editor->setCursor(cursors[0]);
if (!toStart || !toEnd)
for (int i=0;i<newMirrors.size();i++)
editor->addCursorMirror(newMirrors[i]); //one cursor / line
}
/*!
* \brief cut lines
* Cut lines are copied into clipboard. To do so sensibly, cursors are sorted by line number first.
*/
void LatexEditorView::cutLines()
{
QDocumentCursor cur = editor->cursor();
if(cur.hasSelection()){
editor->cut();
return;
}
QList<QDocumentCursor> cursors = editor->cursors();
if (cursors.empty()) return;
// sort cursors by start linenumber
std::sort(cursors.begin(),cursors.end());
document->beginMacro();
QString clipboard;
int lastEndLine=-1;
QList<int> skipCursors;
for (int i=0;i<cursors.size();i++){
int begincolumn,beginline,endcolumn,endline;
cursors[i].boundaries(beginline,begincolumn,endline,endcolumn);
if(lastEndLine>=0){
if(beginline<=lastEndLine){ // second cursor in same line
beginline=lastEndLine+1; // force start to next line
if(endline<beginline){
skipCursors<<i;
continue; // skip cursor if endline is before beginline, i.e. cursor intersected previous extended cursor
}
}
}
cursors[i].select(beginline,0,endline,-1);
lastEndLine=endline;
clipboard+=cursors[i].selectedText()+"\n";
}
// delete lines later to not mess cursor positions
for (int i=0;i<cursors.size();i++){
if(skipCursors.contains(i)) continue;
cursors[i].eraseLine();
}
document->endMacro();
QApplication::clipboard()->setText(clipboard);
editor->setCursor(cursors[0]);
}
void LatexEditorView::moveLines(int delta)
{
REQUIRE(delta == -1 || delta == +1);
QList<QDocumentCursor> cursors = editor->cursors();
for (int i=0;i<cursors.length();i++)
cursors[i].setAutoUpdated(false);
QList<QPair<int, int> > blocks = getSelectedLineBlocks();
document->beginMacro();
int i = delta < 0 ? blocks.size() - 1 : 0;
QVector<bool>skipMove(cursors.length(),false);
while (i >= 0 && i < blocks.size()) {
//edit
if ((delta < 0 && blocks[i].first==0)||(delta > 0 && blocks[i].second==(document->lineCount()-1))) {
skipMove[i]=true;
i += delta;
continue;
}
bool skipCursorUp=blocks[i].second==(document->lineCount()-1);
QDocumentCursor edit = document->cursor(blocks[i].first, 0, blocks[i].second);
QString text = edit.selectedText();
edit.removeSelectedText();
edit.eraseLine();
if (delta < 0) {