-
Notifications
You must be signed in to change notification settings - Fork 351
/
Copy pathsmallUsefulFunctions.cpp
1002 lines (902 loc) · 31.2 KB
/
smallUsefulFunctions.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
#include "smallUsefulFunctions.h"
#include "qdocumentline_p.h"
#include "qdocument.h"
#include <QBuffer>
#include "latexparser/latexparser.h"
using std::map;
using std::pair;
using CharMap = map<pair<char,char>,int>;
/*
QList<QPair<QString,QString> > latexToPlainWordReplaceList =
QList<QPair<QString,QString> >()
<< QPair<QString, QString> ("\\-","") //Trennung [separation] (german-babel-package also: \")
<< QPair<QString, QString> ("\\/","") //ligatur preventing (german-package also: "|)
<< QPair<QString, QString> ("\"~","-") //- ohne Trennung (without separation)
//german-babel-package: "- (\- but also normal break), "= ( like - but also normal break), "" (umbruch ohne bindestrich)
<< QPair<QString, QString> ("\"-","")
<< QPair<QString, QString> ("\"a","\xE4")
<< QPair<QString, QString> ("\"o","\xF6")
<< QPair<QString, QString> ("\"u","\xFC")
<< QPair<QString, QString> ("\"s","\xDF")
<< QPair<QString, QString> ("\"A","\xC4")
<< QPair<QString, QString> ("\"O","\xD6")
<< QPair<QString, QString> ("\"U","\xDC")
<< QPair<QString, QString> ("\\\"{a}","\xE4")
<< QPair<QString, QString> ("\\\"{o}","\xF6")
<< QPair<QString, QString> ("\\\"{u}","\xFC")
<< QPair<QString, QString> ("\\\"{A}","\xC4")
<< QPair<QString, QString> ("\\\"{O}","\xD6")
<< QPair<QString, QString> ("\\\"{U}","\xDC")
<< QPair<QString, QString> ("\"|","")
<< QPair<QString, QString> ("\"","")
// << QPair<QString, QString> ("\"\"","") redunant
<< QPair<QString, QString> ("\\",""); // eliminating backslash which might remain from accents like \"a ...
*/
const CharMap characters {
// Umlaut
{ { '"' , 'a' } , 0xE4 },
{ { '"' , 'e' } , 0xEB },
{ { '"' , 'i' } , 0xEF },
{ { '"' , 'o' } , 0xF6 },
{ { '"' , 'u' } , 0xFC },
{ { '"' , 'A' } , 0xC4 },
{ { '"' , 'E' } , 0xCB },
{ { '"' , 'I' } , 0xCF },
{ { '"' , 'O' } , 0xD6 },
{ { '"' , 'U' } , 0xDC },
{ { '"' , 's' } , 0xDF },
// Grave
{ { '`' , 'a' } , 0xE0 },
{ { '`' , 'e' } , 0xE8 },
{ { '`' , 'i' } , 0xEC },
{ { '`' , 'o' } , 0xF2 },
{ { '`' , 'u' } , 0xF9 },
{ { '`' , 'A' } , 0xC0 },
{ { '`' , 'E' } , 0xC8 },
{ { '`' , 'I' } , 0xCC },
{ { '`' , 'O' } , 0xD2 },
{ { '`' , 'U' } , 0xD9 },
// Acute
{ { '\'' , 'a' } , 0xE1 },
{ { '\'' , 'e' } , 0xE9 },
{ { '\'' , 'i' } , 0xED },
{ { '\'' , 'o' } , 0xF3 },
{ { '\'' , 'u' } , 0xFA },
{ { '\'' , 'y' } , 0xFD },
{ { '\'' , 'A' } , 0xC1 },
{ { '\'' , 'E' } , 0xC9 },
{ { '\'' , 'I' } , 0xCD },
{ { '\'' , 'O' } , 0xD3 },
{ { '\'' , 'U' } , 0xDA },
{ { '\'' , 'Y' } , 0xDD },
// Circumflex
{ { '^' , 'a' } , 0xE2 },
{ { '^' , 'e' } , 0xEA },
{ { '^' , 'i' } , 0xEE },
{ { '^' , 'o' } , 0xF4 },
{ { '^' , 'u' } , 0xFB },
{ { '^' , 'A' } , 0xC2 },
{ { '^' , 'E' } , 0xCA },
{ { '^' , 'I' } , 0xCE },
{ { '^' , 'O' } , 0xD4 },
{ { '^' , 'U' } , 0xDB },
// Tilde
{ { '~' , 'a' } , 0xE3 },
{ { '~' , 'n' } , 0xF1 },
{ { '~' , 'o' } , 0xF5 },
{ { '~' , 'A' } , 0xC3 },
{ { '~' , 'N' } , 0xD1 },
{ { '~' , 'O' } , 0xD5 },
// Cedille
{ { 'c' , 'c' } , 0xE7 },
{ { 'c' , 'C' } , 0xC7 }
};
/*!
* \brief transformCharacter
* Transform a character from a tex encoded to utf
* e.g. "a -> ä
* \param c
* \param context
* \return tranformed character
*/
QChar transformCharacter(const QChar & character,const QChar & context){
auto transformation = characters.find({ context.toLatin1() , character.toLatin1() });
if(transformation == characters.end())
return character;
return QChar(transformation -> second);
}
QString latexToPlainWord(const QString &word)
{
/* QString result=word;
for (QList<QPair<QString,QString> >::const_iterator it=latexToPlainWordReplaceList.begin(); it!=latexToPlainWordReplaceList.end(); ++it)
result.replace(it->first,it->second);*/
QString result;
result.reserve(word.length());
for (int i = 0; i < word.length(); i++) {
if (word[i] == '\\') {
//decode all meta characters starting with a backslash (c++ syntax: don't use an actual backslash there or it creates a multi line comment)
i++;
if (i >= word.length()) break;
switch (word[i].toLatin1()) {
case '-': //Trennung [separation] (german-babel-package also: \")
case '/': //ligatur preventing (german-package also: "|)
break;
case '"':
case '\'':
case '^':
case '`':
case '~':
case 'c':
if (i + 3 < word.length()) {
if (word[i + 1] == '{' && word[i + 3] == '}') {
result.append(transformCharacter(word[i + 2], word[i]));
i += 3;
break;
}
}
if (i + 1 < word.length()) {
if (word[i + 1] == '\\' || word[i + 1] == '"')
break; //ignore "
result.append(transformCharacter(word[i + 1], word[i]));
i++;
break;
}
i--; //repeat with "
break;
default:
i--; //repeat with current char
}
} /* else if (word[i] == '"') { // replacement from german package is handled extra
//decode all meta characters starting with "
i++;
if (i>=word.length()) break;
switch (word[i].toLatin1()) {
case '~':
result.append('-'); //- ohne Trennung (without separation)
break;
case '-':
case '|': //babel package, separation
case '"': //ignore ""
break;
default:
result.append(transformCharacter(word[i], '"'));
}
}*/ else result.append(word[i]);
}
return result;
}
QString latexToPlainWordwithReplacementList(const QString &word, QMap<QString, QString> &replacementList )
{
QString result;
QString w = latexToPlainWord(word);
if (!replacementList.isEmpty()){
while (!w.isEmpty()) {
bool replaced = false;
foreach (const QString elem, replacementList.keys()) {
if (w.startsWith(elem)) {
result.append(replacementList.value(elem));
w = w.mid(elem.length());
replaced = true;
break;
}
}
if (!replaced) {
result.append(w.left(1));
w = w.mid(1);
}
}
}else{
result=w;
}
// remove leading and trailing "
if(result.startsWith("\"")){
result=result.mid(1);
}
if(result.endsWith("\"")){
result.chop(1);
}
return result;
}
QString textToLatex(const QString &text)
{
QList<QPair<QString, QString> > replaceList;
// replacements for resevered characters according to
// http://en.wikibooks.org/wiki/LaTeX/Basics#Reserved_Characters
QString result = text;
result.replace("{", "\\{");
result.replace("}", "\\}");
result.replace(QRegularExpression("\\\\(?![{}])"),"\\textbackslash{}");
replaceList.append(QPair<QString, QString> ("#", "\\#"));
replaceList.append(QPair<QString, QString> ("$", "\\$"));
replaceList.append(QPair<QString, QString> ("%", "\\%"));
replaceList.append(QPair<QString, QString> ("&", "\\&"));
replaceList.append(QPair<QString, QString> ("~", "\\~{}"));
replaceList.append(QPair<QString, QString> ("_", "\\_"));
replaceList.append(QPair<QString, QString> ("^", "\\^{}"));
for (QList<QPair<QString, QString> >::const_iterator it = replaceList.begin(); it != replaceList.end(); ++it)
result.replace(it->first, it->second);
result.replace(QRegularExpression("\"(.*?)\""), "``\\1''");
return result;
}
int startOfArg(const QString &s, int index) {
for (int i=index; i < s.length(); i++) {
if (s.at(i).isSpace()) continue;
if (s.at(i) == '{') return i;
return -1;
}
return -1;
}
/*!
* Parses a Latex string to a plain string.
* Specifically, this substitues \texorpdfstring and removes explicit hyphens.
*/
QString latexToText(QString s)
{
// substitute \texorpdfstring
int start, stop;
int texorpdfstringLength = 15;
start = s.indexOf("\\texorpdfstring");
while (start >= 0 && start < s.length()) {
// first arg
int i = startOfArg(s, start + texorpdfstringLength);
if (i < 0) { // no arguments for \\texorpdfstring
start += texorpdfstringLength;
start = s.indexOf("\\texorpdfstring", start);
continue;
}
i++;
stop = findClosingBracket(s, i);
if (stop < 0) { // missing closing bracket for first argument of \\texorpdfstring
start += texorpdfstringLength;
start = s.indexOf("\\texorpdfstring", start);
continue;
}
// second arg
i = startOfArg(s, stop + 1);
if (i < 0) { // no second arg for \\texorpdfstring
start += texorpdfstringLength;
start = s.indexOf("\\texorpdfstring", start);
continue;
}
i++;
stop = findClosingBracket(s, i);
if (stop < 0) {
start += texorpdfstringLength;
start = s.indexOf("\\texorpdfstring", start);
continue; // no second arg for \\texorpdfstring
}
s.remove(stop, 1);
s.remove(start, i - start);
start = s.indexOf("\\texorpdfstring", start);
}
// remove discretionary hyphenations
s.remove("\\-");
return s;
}
// joins all the input lines trimming whitespace. A new line is started on comments and empty lines
QStringList joinLinesExceptCommentsAndEmptyLines(const QStringList &lines){
QStringList joinedLines;
QString tmpLine;
#define FLUSH_TMPLINE() \
if(!tmpLine.isEmpty()){ \
joinedLines.append(tmpLine); \
tmpLine.clear(); \
}
foreach (const QString &l, lines) {
QString rtrimmedLine = trimRight(l);
if (rtrimmedLine.isEmpty()) { // empty line as separator
FLUSH_TMPLINE();
joinedLines.append(rtrimmedLine);
continue;
}
if (tmpLine.isEmpty()) {
tmpLine.append(rtrimmedLine);
} else {
tmpLine.append(" " + rtrimmedLine.trimmed());
}
int commentStartPos = commentStart(rtrimmedLine);
if (commentStartPos >= 0) {
FLUSH_TMPLINE();
}
}
FLUSH_TMPLINE();
#undef FLUSH_TMPLINE
return joinedLines;
}
// splits lines after maximal number of chars while keeping track of indentation and comments
QStringList splitLines(const QStringList &lines, int maxCharPerLine, const QRegularExpression &breakChars)
{
QStringList splittedLines;
int maxIndent = maxCharPerLine / 2 * 3;
foreach (QString line, lines) {
int textStart = 0;
while (textStart < line.length() && line.at(textStart).isSpace() && textStart < maxIndent) textStart++;
if (textStart >= line.length()) { // empty line
splittedLines << line;
continue;
}
int maxCharPerLineWithoutIndent = maxCharPerLine - textStart;
QString indent = line.left(textStart);
line = line.mid(textStart);
bool inComment = false;
while (line.length() > maxCharPerLineWithoutIndent) {
if (inComment) line.prepend("% ");
int breakAt = line.lastIndexOf(breakChars, maxCharPerLineWithoutIndent);
if (breakAt <= 3) breakAt = -1;
QString leftPart = line.left(breakAt);
splittedLines << indent + leftPart;
if (breakAt >= 0) {
line.remove(0, breakAt + 1);
inComment = inComment || (commentStart(leftPart) >= 0);
} else {
line.clear();
break;
}
}
if (line.length() > 0) {
if (inComment) line.prepend("% ");
splittedLines << indent + line;
}
}
return splittedLines;
}
bool localeAwareLessThan(const QString &s1, const QString &s2)
{
return QString::localeAwareCompare(s1, s2) < 0;
}
// removes whitespace from the beginning of the string
QString trimLeft(const QString &s)
{
int j;
for (j = 0; j < s.length(); j++)
if (s[j] != ' ' && s[j] != '\t' && s[j] != '\r' && s[j] != '\n') break;
return s.mid(j);
}
// removes whitespace from the end of the string
QString trimRight(const QString &s)
{
if (s.isEmpty()) return QString();
int j;
for (j = s.length() - 1; j >= 0; j--)
if (s[j] != ' ' && s[j] != '\t' && s[j] != '\r' && s[j] != '\n') break;
return s.left(j + 1);
}
bool findTokenWithArg(const QString &line, const QString &token, QString &outName, QString &outArg)
{
outName = "";
outArg = "";
int tagStart = line.indexOf(token);
int commentStart = line.indexOf(QRegularExpression("(^|[^\\\\])%")); // find start of comment (if any)
if (tagStart != -1 && (commentStart > tagStart || commentStart == -1)) {
tagStart += token.length();
int tagEnd = line.indexOf("}", tagStart);
if (tagEnd != -1) {
outName = line.mid(tagStart, tagEnd - tagStart);
int curlyOpen = line.indexOf("{", tagEnd);
int optionStart = line.indexOf("[", tagEnd);
if (optionStart < curlyOpen || (curlyOpen == -1 && optionStart != -1)) {
int optionEnd = line.indexOf("]", optionStart);
if (optionEnd != -1) outArg = line.mid(optionStart + 1, optionEnd - optionStart - 1);
else outArg = line.mid(optionStart + 1);
}
} else outName = line.mid(tagStart); //return everything after line if there is no }
return true;
}
return false;
}
/*! returns the command at pos (including \) in outCmd. pos may be anywhere in the command name (including \) but
* not in command options. Return value is the index of the first char after the command (or pos if there was no command
* \warning obsolete with lexer-based token system
*/
// TODO: currently does not work for command '\\'
int getCommand(const QString &line, QString &outCmd, int pos)
{
int start = pos;
while (line.at(start) != '\\') { // find beginning
if (!isCommandChar(line.at(start)) || start == 0) return pos; // no command
start--;
}
int i = pos + 1;
for (; i < line.length(); i++)
if (!isCommandChar(line.at(i))) break;
outCmd = line.mid(start, i - start);
return i;
}
/*! returns command option list. pos has to be at the beginning of the first bracket
* posBehind returns the position after the last bracket, you may pass the same variable as in pos
* \warning obsolete with lexer-based token system
*/
QList<CommandArgument> getCommandOptions(const QString &line, int pos, int *posBehind)
{
static QMap<QChar, QChar> cbs;
if (cbs.isEmpty()) {
cbs[QChar('{')] = QChar('}');
cbs[QChar('[')] = QChar(']');
}
QList<CommandArgument> options;
int start = pos;
if (posBehind) *posBehind = start;
if (pos >= line.length()) return options;
QChar oc = line[start];
if (!cbs.contains(oc)) return options;
for (int num = 1;; num++) {
int end = findClosingBracket(line, start, oc, cbs[oc]);
if (end < 0) break; // open without close
CommandArgument arg;
arg.isOptional = (oc == '[');
arg.number = num;
arg.value = line.mid(start + 1, end - start - 1);
options.append(arg);
start = end + 1;
if (posBehind) *posBehind = start;
if (start >= line.length() || !cbs.contains(line[start])) break; // close on last char or last option reached
else oc = line[start];
}
return options;
}
/* returns the item at pos in a colon separated list of options (empty on colon
* e.g. getParamItem("{one, two, three}", 7) returns "two"
* \warning obsolete with lexer-based token system
*/
QString getParamItem(const QString &line, int pos, bool stopAtWhiteSpace)
{
REQUIRE_RET(pos <= line.length(), QString());
int start;
int curlCount = 0;
int squareCount = 0;
QString openDelim(",{[");
if (stopAtWhiteSpace) openDelim += " \t\n\r";
for (start = pos; start > 0; start--) {
QChar c = line.at(start - 1);
if (c == '}' && openDelim.contains('{')) curlCount++;
if (c == '{') {
if (curlCount-- <= 0) break;
else continue;
}
if (c == ']' && openDelim.contains('[')) squareCount++;
if (c == '[') {
if (squareCount-- <= 0) break;
else continue;
}
if (openDelim.contains(c)) break;
}
int end = pos;
QString closeDelim(",]}");
if (stopAtWhiteSpace) closeDelim += " \t\n\r";
curlCount = 0;
squareCount = 0;
for (end = pos; end < line.length(); end++) {
QChar c = line.at(end);
if (c == '{' && closeDelim.contains('}')) curlCount++;
if (c == '}') {
if (curlCount-- <= 0) break;
else continue;
}
if (c == '[' && closeDelim.contains(']')) squareCount++;
if (c == ']') {
if (squareCount-- <= 0) break;
else continue;
}
if (closeDelim.contains(c)) break;
}
return line.mid(start, end - start);
}
QRegularExpression generateRegularExpression(const QString &text, const bool isCase, const bool isWord, const bool isRegExp)
{
QRegularExpression::PatternOption po = isCase ? QRegularExpression::NoPatternOption : QRegularExpression::CaseInsensitiveOption;
QRegularExpression m_regexp;
if ( isRegExp ) {
m_regexp = QRegularExpression(text, po);
} else if ( isWord ) {
//todo: screw this? it prevents searching of "world!" and similar things
//(qtextdocument just checks the surrounding character when searching for whole words, this would also allow wholewords|regexp search)
m_regexp = QRegularExpression(
QString("\\b%1\\b").arg(QRegularExpression::escape(text)),
po
);
} else {
m_regexp = QRegularExpression(QRegularExpression::escape(text), po);
}
return m_regexp;
}
QStringList regularExpressionFindAllMatches(const QString &searchIn, const QRegularExpression ®exp, int cap)
{
QRegularExpressionMatch match = regexp.match(searchIn);
int offset=match.capturedStart();
QStringList res;
while (offset > -1) {
res << match.captured(cap);
match = regexp.match(searchIn,offset+match.capturedLength());
offset = match.capturedStart();
}
return res;
}
/*!
* a multi-match equivalent of QString::indexOf(QString)
*/
QList<int> indicesOf(const QString &line, const QString &word, Qt::CaseSensitivity cs)
{
QList<int> columns;
int col = 0;
while (col < line.length() - 1) {
col = line.indexOf(word, col, cs);
if (col < 0) break;
columns.append(col);
col++;
}
return columns;
}
/*!
* a multi-match equivalent of QString::indexOf(QRegularExpression)
*/
QList<int> indicesOf(const QString &line, const QRegularExpression &rx)
{
QList<int> columns;
int col = 0;
// exact match
while (col < line.length() - 1) {
col = line.indexOf(rx, col);
if (col < 0) break;
columns.append(col);
col++;
}
return columns;
}
void addEnvironmentToDom(QDomDocument &doc, const QString &EnvironName, const QString &EnvironMode, bool completeParentheses)
{
QDomElement root = doc.documentElement();
QDomElement tag = doc.createElement("context");
tag.setAttribute("id", EnvironMode == "numbers" ? "mathMyEnv" : "myVerb");
tag.setAttribute("format", EnvironMode);
if (EnvironMode != "comment") tag.setAttribute("transparency", "true");
QDomElement child1 = doc.createElement("start");
child1.setAttribute("parenthesis", QString("my%1:open%2").arg(EnvironName).arg(completeParentheses ? "" : "@nocomplete"));
child1.setAttribute("fold", "true");
child1.setAttribute("format", "extra-keyword");
child1.setAttribute("parenthesisWeight", "30");
QDomText dtxt = doc.createTextNode(QString("\\\\begin{%1}").arg(EnvironName));
child1.appendChild(dtxt);
QDomElement child2 = doc.createElement("stop");
child2.setAttribute("parenthesis", QString("my%1:close%2").arg(EnvironName).arg(completeParentheses ? "" : "@nocomplete"));
child2.setAttribute("fold", "true");
child2.setAttribute("format", "extra-keyword");
child2.setAttribute("parenthesisWeight", "30");
QDomText dtxt2 = doc.createTextNode(QString("\\\\end{%1}").arg(EnvironName));
child2.appendChild(dtxt2);
tag.appendChild(child1);
tag.appendChild(child2);
if (EnvironMode == "numbers") {
QDomElement child3 = doc.createElement("word");
child3.setAttribute("id", "keywords/single");
child3.setAttribute("format", "math-keyword");
child3.appendChild(doc.createTextNode("\\\\[a-zA-Z]+"));
tag.appendChild(child3);
}
//insert before the first context with the same format, so that transparency is actually used
QDomNode insertAt;
for (int i = 0; i < root.childNodes().size(); i++)
if (root.childNodes().item(i).attributes().namedItem("format").nodeValue() == EnvironMode) {
insertAt = root.childNodes().item(i);
break;
}
root.insertBefore(tag, insertAt);
}
/*! adds entries for structure commands to the Dom of a QNFA file
* commands are taken from possibleCommands["%structure0"] to possibleCommands["%structureN"]
*/
void addStructureCommandsToDom(QDomDocument &doc , const QHash<QString, QSet<QString> > &possibleCommands)
{
QDomElement root = doc.documentElement();
QDomNode parent;
for (int i = root.childNodes().size() - 1; i >= 0; i--) {
if (root.childNodes().item(i).attributes().namedItem("id").nodeValue() == "keywords/structure") {
parent = root.childNodes().item(i);
break;
}
}
if (parent.isNull()) {
return;
}
while (!parent.firstChild().isNull()) {
parent.removeChild(parent.firstChild());
}
for (int level = 0; level <= LatexParser::MAX_STRUCTURE_LEVEL; level++) {
foreach (const QString &cmd, possibleCommands[QString("%structure%1").arg(level)]) {
QDomElement child = doc.createElement("word");
QString name = cmd;
name.remove('\\');
child.setAttribute("parenthesis", QString("structure%1:boundary@nomatch").arg(level));
child.setAttribute("parenthesisWeight", QString("%1").arg(8 - level));
child.setAttribute("fold", "true");
name = cmd;
name.replace('\\', "\\\\"); // words are regexps, so we have to escape the slash
QDomText dtxt = doc.createTextNode(name);
child.appendChild(dtxt);
parent.appendChild(child);
}
}
}
/*!
* \brief convert a list of integer in one string with a textual representation of said integers
*
* The numbers are given as text, separated by commas
* \param ints list of integer
* \return string containg a textual list of integers
*/
QString intListToStr(const QList<int> &ints)
{
QString s = "";
foreach (int i, ints) {
s.append(QString::number(i) + ',');
}
if (s.length() > 0)
s.remove(s.length() - 1, 1); // remove last ','
return s;
}
QList<int> strToIntList(const QString &s)
{
QList<int> ints;
bool ok;
foreach (const QString &si, s.split(',')) {
int i = si.toInt(&ok);
if (ok) ints << i;
}
return ints;
}
QString enquoteStr(const QString &s)
{
QString res = s;
res.replace('"', "\\\"");
res.prepend('"');
res.append('"');
return res;
}
QString dequoteStr(const QString &s)
{
QString res = s;
if (res.endsWith('"') && !res.endsWith("\\\""))
res.remove(res.length() - 1, 1);
if (res.startsWith('"'))
res.remove(0, 1);
res.replace("\\\"", "\"");
return res;
}
/** add a quotation around the string if it does not already have one. **/
QString quotePath(const QString &s)
{
if (s.startsWith('"') || !s.contains(' ')) return QString(s);
return QString("\"%1\"").arg(s);
}
/** if the string is surrounded by qoutes, remove these **/
QString removeQuote(const QString &s)
{
if (s.length() >= 2 && s.startsWith('"') && s.endsWith('"')) {
return s.mid(1, s.length() - 2);
}
return s;
}
QString removePathDelim(const QString &s)
{
// we use the explicit chars intentionally and not QDir::separator()
// because it shall also work for / on windows (many paths are internally
// represented with / as delimiter
if (s.endsWith('/') || s.endsWith('\\')) {
return s.left(s.length() - 1);
}
return s;
}
QString removeAccents(const QString &s) {
QString diacriticLetters = QString::fromUtf8("ŠŒŽšœžŸ¥µÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿ");
QStringList noDiacriticLetters = QStringList() << "S"<<"OE"<<"Z"<<"s"<<"oe"<<"z"<<"Y"<<"Y"<<"u"<<"A"<<"A"<<"A"<<"A"<<"A"<<"A"<<"AE"<<"C"<<"E"<<"E"<<"E"<<"E"<<"I"<<"I"<<"I"<<"I"<<"D"<<"N"<<"O"<<"O"<<"O"<<"O"<<"O"<<"O"<<"U"<<"U"<<"U"<<"U"<<"Y"<<"s"<<"a"<<"a"<<"a"<<"a"<<"a"<<"a"<<"ae"<<"c"<<"e"<<"e"<<"e"<<"e"<<"i"<<"i"<<"i"<<"i"<<"o"<<"n"<<"o"<<"o"<<"o"<<"o"<<"o"<<"o"<<"u"<<"u"<<"u"<<"u"<<"y"<<"y";
QString output = "";
for (int i = 0; i < s.length(); i++) {
QChar c = s[i];
int dIndex = diacriticLetters.indexOf(c);
if (dIndex < 0) {
output.append(c);
} else {
QString replacement = noDiacriticLetters[dIndex];
output.append(replacement);
}
}
return output;
}
QString makeLatexLabel(const QString &s) {
QString sNorm = removeAccents(s).normalized(QString::NormalizationForm_KD).toLower();
sNorm.replace(' ', '-');
sNorm.remove(QRegularExpression("[^a-z0-9\\-]"));
return sNorm;
}
/*! Splits a command string into the command an arguments.
* This respects quoted arguments. Output redirection operators are separate tokens
*/
QStringList tokenizeCommandLine(const QString &commandLine) {
QStringList result;
QString currentToken = "";
currentToken.reserve(30);
bool inQuote = false;
bool escape= false;
#define FLUSH(value) \
if(!(value).isEmpty()) \
result << (value); \
\
(value) = "";
foreach (const QChar &c, commandLine) {
if (c.isSpace()) {
if (inQuote) {
currentToken.append(c);
} else {
FLUSH(currentToken)
}
} else if (c == '\\') {
escape = !escape;
currentToken.append(c);
continue;
} else if (c == '"') {
if (!escape) inQuote = !inQuote;
currentToken.append(c);
} else if (c == '>') {
if (inQuote) {
currentToken.append(c);
} else if (currentToken == "2"){
currentToken.append(c);
FLUSH(currentToken)
} else {
FLUSH(currentToken)
currentToken = c;
FLUSH(currentToken)
}
} else {
currentToken.append(c);
}
escape = false;
}
FLUSH(currentToken)
#undef FLUSH
return result;
}
QStringList extractOutputRedirection(const QStringList &commandArgs, QString &stdOut, QString &stdErr) {
QStringList extracted;
bool extracted_finished = false;
for (int i=0; i<commandArgs.length(); i++) {
if (commandArgs[i] == ">" && i < commandArgs.length()-1) {
stdOut = commandArgs[i+1];
i += 1;
extracted_finished = true;
} else if (commandArgs[i].startsWith(">")) {
stdOut = commandArgs[i].mid(1);
extracted_finished = true;
} else if (commandArgs[i] == "2>" && i < commandArgs.length()-1) {
stdErr = commandArgs[i+1];
i += 1;
extracted_finished = true;
} else if (commandArgs[i].startsWith("2>")) {
stdErr = commandArgs[i].mid(2);
extracted_finished = true;
} else {
if (!extracted_finished)
extracted << commandArgs[i];
}
}
return extracted;
}
uint joinUnicodeSurrogate(const QChar &highSurrogate, const QChar &lowSurrogate)
{
uint uhigh = highSurrogate.unicode();
uint ulow = lowSurrogate.unicode();
uint code = 0x10000;
code += (uhigh & 0x03FF) << 10;
code += (ulow & 0x03FF);
return code;
}
QString getImageAsText(const QPixmap &AImage, const int w)
{
QByteArray ba;
QBuffer buffer(&ba);
buffer.open(QIODevice::WriteOnly);
AImage.save(&buffer, "PNG");
QString text = w < 0 ? QString("<img src=\"data:image/png;base64,%1\">").arg(QString(buffer.data().toBase64())) : QString("<img src=\"data:image/png;base64,%1\" width=%2 >").arg(QString(buffer.data().toBase64())).arg(w);
return text;
}
/*!
* Shows a tooltip at the given position (pos = top left corner).
* If the tooltip does not fit on the screen, it's attempted to position it to the left including
* a possible relatedWidgetWidth offset (pos - relatedWidgetWidth = top right corner).
* If there is not enough space as well the text is shown in the position (left/right) of maxium
* available space and the text lines are shortend to fit the available space.
*/
void showTooltipLimited(QPoint pos, QString text, int relatedWidgetWidth)
{
text.replace("\t", " "); //if there are tabs at the position in the string, qt crashes. (13707)
QRect screen = UtilsUi::getAvailableGeometryAt(pos);
// estimate width of coming tooltip
// rather dirty code
bool textWillWarp = Qt::mightBeRichText(text);
QLabel lLabel(nullptr, Qt::ToolTip);
lLabel.setFont(QToolTip::font());
lLabel.setMargin(1 + lLabel.style()->pixelMetric(QStyle::PM_ToolTipLabelFrameWidth, nullptr, &lLabel));
lLabel.setFrameStyle(QFrame::StyledPanel);
lLabel.setAlignment(Qt::AlignLeft);
lLabel.setIndent(1);
lLabel.setWordWrap(textWillWarp);
lLabel.ensurePolished();
lLabel.setText(text);
lLabel.adjustSize();
int textWidthInPixels = lLabel.width() + 10; // +10 good guess
if (pos.x() - screen.x() + textWidthInPixels <= screen.width()) {
// tooltip fits at the requested position
QToolTip::showText(pos, text);
} else {
// try positioning the tooltip left of the releated widget
QPoint posLeft(pos.x() - textWidthInPixels - relatedWidgetWidth, pos.y());
if (posLeft.x() >= screen.x()) {
QToolTip::showText(posLeft, text);
} else {
// text does not fit to the left
// choose the position left/right with the maximum available space
int availableWidthLeft = (pos.x() - screen.x()) - relatedWidgetWidth;
int availableWidthRight = screen.width() - (pos.x() - screen.x());
int availableWidth = qMax(availableWidthLeft, availableWidthRight);
bool positionLeft = availableWidthLeft > availableWidthRight;
if (!textWillWarp) {
// shorten text lines to fit textwidth (only feasible if the tooltip does not wrap)
QStringList lines = text.split("\n");
int maxLength = 0;
QString maxLine;
foreach (const QString line, lines) {
if (line.length() > maxLength) {
maxLength = line.length();
maxLine = line;
}
}
int averageWidth = lLabel.fontMetrics().averageCharWidth();
if(averageWidth>1){
maxLength = qMin(maxLength, availableWidth / averageWidth);
}
while (textWidthInPixels > availableWidth && maxLength > 10) {
maxLength -= 2;
for (int i = 0; i < lines.count(); i++) {
lines[i] = lines[i].left(maxLength);
}
lLabel.setText(lines.join("\n"));
lLabel.adjustSize();
textWidthInPixels = lLabel.width() + 10;
}
text = lines.join("\n");
}
if (positionLeft) {
posLeft.setX(pos.x() - textWidthInPixels - relatedWidgetWidth);
QToolTip::showText(posLeft, text);
} else {
QToolTip::showText(pos, text);
}
}
}
}
QString truncateLines(const QString &s, int maxLines)
{
int lineCount = 0;
for (int i = 0; i < s.length(); i++) {
if (s[i] == '\n') lineCount++;
if (lineCount >= maxLines) {
return s.left(i + 1) + "...";
}
}
return s;
}
/*
* Utility function for most recent strings, e.g. for filenames
* The item is inserted at the front and removed if present in the rest of the list.
* The list will not get longer than maxLength.
* Returns true if the list contents changed (i.e. item was not already in first place)
*/
bool addMostRecent(const QString &item, QStringList &mostRecentList, int maxLength)
{
int p = mostRecentList.indexOf(item);
bool changed = (p != 0);
if (!changed) return changed;
if (p > 0) mostRecentList.removeAt(p);
mostRecentList.prepend(item);
if (mostRecentList.count() > maxLength) mostRecentList.removeLast();
return changed;