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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
|
#include "syntaxcheck.h"
#include "latexdocument.h"
#include "tablemanipulation.h"
/*! \class SyntaxCheck
*
* asynchrnous thread which checks latex syntax of the text lines
* It gets the linehandle via a queue, together with a ticket number.
* The ticket number is increased with every change of the text of a line, thus it can be determined of the processed handle is still unchanged and can be discarded otherwise.
* Syntaxinformation are stated via markers on the text.
* Furthermore environment information, especially tabular information are stored in "cookies" as they are needed in subsequent lines.
*
*/
/*!
* \brief contructor
* \param parent
*/
SyntaxCheck::SyntaxCheck(QObject *parent) :
SafeThread(parent), syntaxErrorFormat(-1), ltxCommands(0), newLtxCommandsAvailable(false)
{
mLinesLock.lock();
stopped = false;
mLines.clear();
mLinesLock.unlock();
verbatimFormat = 0;
//mLtxCommandLock.unlock();
}
/*!
* \brief set the errorformat for syntax errors
* \param errFormat
*/
void SyntaxCheck::setErrFormat(int errFormat)
{
syntaxErrorFormat = errFormat;
}
/*!
* \brief add line to queue
* \param dlh linehandle
* \param previous linehandle of previous line
* \param stack tokenstack at line start (for handling open arguments of previous commands)
* \param clearOverlay clear syntaxcheck overlay
*/
void SyntaxCheck::putLine(QDocumentLineHandle *dlh, StackEnvironment previous, TokenStack stack, bool clearOverlay)
{
REQUIRE(dlh);
SyntaxLine newLine;
dlh->ref(); // impede deletion of handle while in syntax check queue
dlh->lockForRead();
newLine.ticket = dlh->getCurrentTicket();
dlh->unlock();
newLine.stack = stack;
newLine.dlh = dlh;
newLine.prevEnv = previous;
newLine.clearOverlay = clearOverlay;
mLinesLock.lock();
mLines.enqueue(newLine);
mLinesLock.unlock();
//avoid reading of any results before this execution is stopped
//mResultLock.lock(); not possible under windows
mLinesAvailable.release();
}
/*!
* \brief stop processing syntax checks
*/
void SyntaxCheck::stop()
{
stopped = true;
mLinesAvailable.release();
}
/*!
* \brief actual thread loop
*/
void SyntaxCheck::run()
{
ltxCommands = new LatexParser();
forever {
//wait for enqueued lines
mLinesAvailable.acquire();
if (stopped) break;
if (newLtxCommandsAvailable) {
mLtxCommandLock.lock();
if (newLtxCommandsAvailable) {
newLtxCommandsAvailable = false;
*ltxCommands = newLtxCommands;
}
mLtxCommandLock.unlock();
}
// get Linedata
mLinesLock.lock();
SyntaxLine newLine = mLines.dequeue();
mLinesLock.unlock();
// do syntax check
newLine.dlh->lockForRead();
QString line = newLine.dlh->text();
if (newLine.dlh->hasCookie(3)) {
newLine.dlh->unlock();
newLine.dlh->lockForWrite();
newLine.dlh->removeCookie(3); //remove possible errors from unclosed envs
}
TokenList tl = newLine.dlh->getCookie(QDocumentLine::LEXER_COOKIE).value<TokenList>();
newLine.dlh->unlock();
StackEnvironment activeEnv = newLine.prevEnv;
Ranges newRanges;
checkLine(line, newRanges, activeEnv, newLine.dlh, tl, newLine.stack, newLine.ticket);
// place results
if (newLine.clearOverlay) newLine.dlh->clearOverlays(syntaxErrorFormat);
//if(newRanges.isEmpty()) continue;
newLine.dlh->lockForWrite();
if (newLine.ticket == newLine.dlh->getCurrentTicket()) { // discard results if text has been changed meanwhile
foreach (const Error &elem, newRanges)
newLine.dlh->addOverlayNoLock(QFormatRange(elem.range.first, elem.range.second, syntaxErrorFormat));
// active envs
QVariant oldEnvVar = newLine.dlh->getCookie(QDocumentLine::STACK_ENVIRONMENT_COOKIE);
StackEnvironment oldEnv;
if (oldEnvVar.isValid())
oldEnv = oldEnvVar.value<StackEnvironment>();
bool cookieChanged = !equalEnvStack(oldEnv, activeEnv);
//if excessCols has changed the subsequent lines need to be rechecked.
if (cookieChanged) {
QVariant env;
env.setValue(activeEnv);
newLine.dlh->setCookie(QDocumentLine::STACK_ENVIRONMENT_COOKIE, env);
newLine.dlh->ref(); // avoid being deleted while in queue
//qDebug() << newLine.dlh->text() << ":" << activeEnv.size();
emit checkNextLine(newLine.dlh, true, newLine.ticket);
}
}
newLine.dlh->unlock();
newLine.dlh->deref(); //if deleted, delete now
}
delete ltxCommands;
ltxCommands = 0;
}
/*!
* \brief check one line
*
* Checks one line. Context information needs to be given by newRanges,activeEnv,dlh and ticket.
* This method is obsolete as the new system relies on tokens.
* \warning obsolete method
* \param line text of line as string
* \param newRanges will return the result as ranges
* \param activeEnv environmwent context
* \param dlh linehandle
* \param ticket ticket number for current processed line
*/
void SyntaxCheck::checkLine(const QString &line, Ranges &newRanges, StackEnvironment &activeEnv, QDocumentLineHandle *dlh, int ticket)
{
// do syntax check on that line
int cols = containsEnv(*ltxCommands, "tabular", activeEnv);
LatexReader lr(*ltxCommands, line);
int status;
// check command-words
while ((status = lr.nextWord(true))) {
const QString &word = lr.word;
const int &wordstart = lr.wordStartIndex;
if (status == LatexReader::NW_COMMAND) {
if (word == "\\begin" || word == "\\end") {
QStringList options;
QList<int> starts;
ltxCommands->resolveCommandOptions(line, wordstart, options, &starts);
if (options.size() > 0) {
// adapt env stack
QString env = options.first();
if (env.startsWith("{"))
env = env.remove(0, 1);
if (env.endsWith("}"))
env.chop(1);
if (word == "\\begin") {
Environment tp;
tp.name = env;
tp.id = 1; //needs correction
tp.excessCol = 0;
tp.dlh = dlh;
tp.ticket = ticket;
if (env == "tabular" || ltxCommands->environmentAliases.values(env).contains("tabular")) {
// tabular env opened
// get cols !!!!
if (((env == "tabu") || (env == "longtabu")) && options.size() == 1) { // special treatment as the env is rather not latex standard
QString helper = line.mid(starts.first() + options.first().length());
helper = helper.trimmed();
if (helper.startsWith("to ") || helper.startsWith("spread ")) {
int i = helper.indexOf("{");
if (i > -1) {
QStringList options_zw;
ltxCommands->resolveCommandOptions(helper, i, options_zw);
if (!options_zw.isEmpty()) {
options << options_zw.first();
}
}
}
}
cols = LatexTables::getNumberOfColumns(options);
tp.id = cols;
}
activeEnv.push(tp);
} else {
if (!activeEnv.isEmpty()) {
Environment tp = activeEnv.top();
if (tp.name == env) {
activeEnv.pop();
if (tp.name == "tabular" || ltxCommands->environmentAliases.values(tp.name).contains("tabular")) {
// correct length of col error if it exists
if (!newRanges.isEmpty()) {
Error &elem = newRanges.last();
if (elem.type == ERR_tooManyCols && elem.range.first + elem.range.second > wordstart) {
elem.range.second = wordstart - elem.range.first;
}
}
// get new cols
cols = containsEnv(*ltxCommands, "tabular", activeEnv);
}
} else {
Error elem;
elem.range = QPair<int, int>(wordstart, word.length());
elem.type = ERR_closingUnopendEnv;
newRanges.append(elem);
}
} else {
Error elem;
elem.range = QPair<int, int>(wordstart, word.length());
elem.type = ERR_closingUnopendEnv;
newRanges.append(elem);
}
}
// add env-name for syntax checking to "word"
lr.word += options.first();
}
}
if (ltxCommands->possibleCommands["%definition"].contains(word)) { // don't check in command definition
QStringList options;
QList<int> starts;
ltxCommands->resolveCommandOptions(line, wordstart, options, &starts);
for (int i = 1; i < options.count() && i < 4; i++) {
QString option = options.at(i);
if (option.startsWith("[")) {
continue;
}
lr.index = starts.at(i) + option.length();
break;
}
}
if ( ltxCommands->possibleCommands["%ref"].contains(word) ||
ltxCommands->possibleCommands["%label"].contains(word) ||
ltxCommands->possibleCommands["%file"].contains(word) ||
ltxCommands->possibleCommands["%cite"].contains(word) ||
ltxCommands->possibleCommands["%bibitem"].contains(word) ||
ltxCommands->possibleCommands["%url"].contains(word)
) { //don't check syntax in reference, label or include
QStringList options;
QList<int> starts;
bool complete = ltxCommands->resolveCommandOptions(line, wordstart, options, &starts);
while (options.size() > 0) {
QString option = options.takeFirst();
int start = starts.takeFirst();
lr.index = start + option.length();
if (!option.startsWith("[")) { // handling of includegraphics should be improved !!! This impedes keyval checking
break;
}
}
if (!complete) {
lr.index = line.length(); // last option continues beyond end of line: stop all further checking for this line
break;
}
}
if (ltxCommands->mathStartCommands.contains(word) && (activeEnv.isEmpty() || activeEnv.top().name != "math")) {
Environment env;
env.name = "math";
env.origName=word;
env.id = 1; // to be changed
env.dlh = dlh;
env.ticket = ticket;
activeEnv.push(env);
continue;
}
if (ltxCommands->mathStopCommands.contains(word) && !activeEnv.isEmpty() && activeEnv.top().name == "math") {
int i=ltxCommands->mathStopCommands.indexOf(word);
QString txt=ltxCommands->mathStartCommands.value(i);
if(activeEnv.top().origName==txt){
activeEnv.pop();
}// ignore mismatching mathstop commands
continue;
}
if (ltxCommands->possibleCommands["user"].contains(word) || ltxCommands->customCommands.contains(word))
continue;
//tabular checking
if (topEnv("tabular", activeEnv) != 0) {
if (word == "&") {
activeEnv.top().excessCol++;
if (activeEnv.top().excessCol >= activeEnv.top().id) {
Error elem;
elem.range = QPair<int, int>(wordstart, word.length());
elem.type = ERR_tooManyCols;
newRanges.append(elem);
}
continue;
}
if ((word == "\\\\") || (word == "\\tabularnewline")) {
if (activeEnv.top().excessCol < (activeEnv.top().id - 1)) {
Error elem;
elem.range = QPair<int, int>(wordstart, word.length());
elem.type = ERR_tooLittleCols;
newRanges.append(elem);
}
if (activeEnv.top().excessCol >= (activeEnv.top().id)) {
Error elem;
elem.range = QPair<int, int>(wordstart, word.length());
elem.type = ERR_tooManyCols;
newRanges.append(elem);
}
activeEnv.top().excessCol = 0;
continue;
}
if (word == "\\multicolumn") {
QRegExp rxMultiColumn("\\\\multicolumn\\{(\\d+)\\}\\{.+\\}\\{.+\\}");
rxMultiColumn.setMinimal(true);
int res = rxMultiColumn.indexIn(line, wordstart);
if (res > -1) {
// multicoulmn before &
bool ok;
int c = rxMultiColumn.cap(1).toInt(&ok);
if (ok) {
activeEnv.top().excessCol += c - 1;
}
}
if (activeEnv.top().excessCol >= activeEnv.top().id) {
Error elem;
elem.range = QPair<int, int>(wordstart, word.length());
elem.type = ERR_tooManyCols;
newRanges.append(elem);
}
continue;
}
}
// ignore commands containing @
if (word.contains('@'))
continue;
if (!checkCommand(word, activeEnv)) {
Error elem;
elem.range = QPair<int, int>(wordstart, word.length());
elem.type = ERR_unrecognizedCommand;
if (ltxCommands->possibleCommands["math"].contains(word))
elem.type = ERR_MathCommandOutsideMath;
if (ltxCommands->possibleCommands["tabular"].contains(word))
elem.type = ERR_TabularCommandOutsideTab;
if (ltxCommands->possibleCommands["tabbing"].contains(word))
elem.type = ERR_TabbingCommandOutside;
newRanges.append(elem);
}
}
if (status != LatexReader::NW_COMMAND) {
// special treatment for key val checking
QString command, value;
LatexParser::ContextType ctx = ltxCommands->findContext(line, lr.wordStartIndex, command, value);
if (ctx == LatexParser::Keyval) {
// search stored keyvals
QString elem = "key%" + command;
if (elem.endsWith("#c"))
elem.clear();
if (!elem.isEmpty()) {
// check whether keys is valid
QStringList lst = ltxCommands->possibleCommands[elem].values();
QStringList::iterator iterator;
for (iterator = lst.begin(); iterator != lst.end(); ++iterator) {
int i = iterator->indexOf("#");
if (i > -1)
*iterator = iterator->left(i);
if (iterator->endsWith("=")) {
iterator->chop(1);
}
}
if (!lst.contains(word)) {
Error elem;
elem.range = QPair<int, int>(wordstart, word.length());
elem.type = ERR_unrecognizedKey;
newRanges.append(elem);
}
}
}
if (ctx == LatexParser::KeyvalValue && word.simplified() != "," && !command.endsWith("#c")) {
//figure out keyval
int i = lr.wordStartIndex;
while (i > 0 && line.at(i - 1).isLetter())
i--;
if (i > 0 && line.at(i - 1) == QChar('=')) {
int j = --i;
while (i > 0 && line.at(i - 1).isLetter())
i--;
QString key = line.mid(i, j - i);
QString elem;
foreach (elem, ltxCommands->possibleCommands.keys()) {
if (elem.startsWith("key%") && elem.mid(4) == command)
break;
elem.clear();
}
if (!elem.isEmpty()) {
// check whether keys is valid
QStringList lst = ltxCommands->possibleCommands[elem].values();
QStringList::iterator iterator;
QString options;
for (iterator = lst.begin(); iterator != lst.end(); ++iterator) {
int i = iterator->indexOf("#");
options.clear();
if (i > -1) {
options = iterator->mid(i + 1);
*iterator = iterator->left(i);
}
if (iterator->endsWith("=")) {
iterator->chop(1);
}
if (*iterator == key)
break;
}
if (iterator != lst.end() && !options.isEmpty()) {
QStringList l = options.split(",");
if (!l.contains(word)) {
Error elem;
elem.range = QPair<int, int>(wordstart, word.length());
elem.type = ERR_unrecognizedKeyValues;
newRanges.append(elem);
}
}
}
}
}
}
}
}
/*!
* \brief get error description for syntax error in line 'dlh' at column 'pos'
* \param dlh linehandle
* \param pos column
* \param previous environment stack at start of line
* \param stack tokenstack at start of line
* \return error description
*/
QString SyntaxCheck::getErrorAt(QDocumentLineHandle *dlh, int pos, StackEnvironment previous, TokenStack stack)
{
// do syntax check
QString line = dlh->text();
QStack<Environment> activeEnv = previous;
TokenList tl = dlh->getCookieLocked(QDocumentLine::LEXER_COOKIE).value<TokenList>();
Ranges newRanges;
checkLine(line, newRanges, activeEnv, dlh, tl, stack, dlh->getCurrentTicket());
// add Error for unclosed env
QVariant var = dlh->getCookieLocked(QDocumentLine::UNCLOSED_ENVIRONMENT_COOKIE);
if (var.isValid()) {
activeEnv = var.value<StackEnvironment>();
Q_ASSERT_X(activeEnv.size() == 1, "SyntaxCheck", "Cookie error");
Environment env = activeEnv.top();
QString cmd = "\\begin{" + env.name + "}";
int index = line.lastIndexOf(cmd);
if (index >= 0) {
Error elem;
elem.range = QPair<int, int>(index, cmd.length());
elem.type = ERR_EnvNotClosed;
newRanges.append(elem);
}
}
// find Error at Position
ErrorType result = ERR_none;
foreach (const Error &elem, newRanges) {
if (elem.range.second + elem.range.first < pos) continue;
if (elem.range.first > pos) break;
result = elem.type;
}
// now generate Error message
QStringList messages;
messages << tr("no error") << tr("unrecognized command") << tr("unrecognized math command") << tr("unrecognized tabular command") << tr("tabular command outside tabular env") << tr("math command outside math env") << tr("tabbing command outside tabbing env") << tr("more cols in tabular than specified") << tr("cols in tabular missing")
<< tr("\\\\ missing") << tr("closing environment which has not been opened") << tr("environment not closed") << tr("unrecognized key in key option") << tr("unrecognized value in key option");
return messages.value(int(result), tr("unknown"));
}
/*!
* \brief set latex commands which are referenced for syntax checking
* \param cmds
*/
void SyntaxCheck::setLtxCommands(const LatexParser &cmds)
{
if (stopped) return;
mLtxCommandLock.lock();
newLtxCommandsAvailable = true;
newLtxCommands = cmds;
mLtxCommandLock.unlock();
}
/*!
* \brief wait for queue to be empty. Used for self-test only.
*/
void SyntaxCheck::waitForQueueProcess()
{
while (!crashed && mLinesAvailable.available() > 0) {
wait(1);
}
}
/*!
* \brief check if queue is empty. Used for self-test only.
* \return queue is not empty
*/
bool SyntaxCheck::queuedLines()
{
return mLinesAvailable.available() > 0;
}
/*!
* \brief check if top-most environment in 'envs' is `name`
* \param name environment name which is checked
* \param envs stack of environments
* \param id check for `id` of the environment, <0 means check is disabled
* \return environment id or 0
*/
int SyntaxCheck::topEnv(const QString &name, const StackEnvironment &envs, const int id)
{
if (envs.isEmpty())
return 0;
Environment env = envs.top();
if (env.name == name) {
if (id < 0 || env.id == id)
return env.id;
}
if (id < 0 && ltxCommands->environmentAliases.contains(env.name)) {
QStringList altEnvs = ltxCommands->environmentAliases.values(env.name);
foreach (const QString &altEnv, altEnvs) {
if (altEnv == name)
return env.id;
}
}
return 0;
}
/*!
* \brief check if the environment stack contains a environment with name `name`
* \param parser reference to LatexParser. It is used to access environment aliases, e.g. equation is also a math environment
* \param name name of the checked environment
* \param envs stack of environements
* \param id if >=0 check if the env has the given id.
* \return environment id of found env otherwise 0
*/
int SyntaxCheck::containsEnv(const LatexParser &parser, const QString &name, const StackEnvironment &envs, const int id)
{
for (int i = envs.size() - 1; i > -1; --i) {
Environment env = envs.at(i);
if (env.name == name) {
if (id < 0 || env.id == id)
return env.id;
}
if (id < 0 && parser.environmentAliases.contains(env.name)) {
QStringList altEnvs = parser.environmentAliases.values(env.name);
foreach (const QString &altEnv, altEnvs) {
if (altEnv == name)
return env.id;
}
}
}
return 0;
}
/*!
* \brief check if the command is valid in the environment stack
* \param cmd name of command
* \param envs environment stack
* \return is valid
*/
bool SyntaxCheck::checkCommand(const QString &cmd, const StackEnvironment &envs)
{
for (int i = 0; i < envs.size(); ++i) {
Environment env = envs.at(i);
if (ltxCommands->possibleCommands.contains(env.name) && ltxCommands->possibleCommands.value(env.name).contains(cmd))
return true;
if (ltxCommands->environmentAliases.contains(env.name)) {
QStringList altEnvs = ltxCommands->environmentAliases.values(env.name);
foreach (const QString &altEnv, altEnvs) {
if (ltxCommands->possibleCommands.contains(altEnv) && ltxCommands->possibleCommands.value(altEnv).contains(cmd))
return true;
}
}
}
return false;
}
/*!
* \brief compare two environment stacks
* \param env1
* \param env2
* \return are equal
*/
bool SyntaxCheck::equalEnvStack(StackEnvironment env1, StackEnvironment env2)
{
if (env1.isEmpty() || env2.isEmpty())
return env1.isEmpty() && env2.isEmpty();
if (env1.size() != env2.size())
return false;
for (int i = 0; i < env1.size(); i++) {
if (env1.value(i) != env2.value(i))
return false;
}
return true;
}
/*!
* \brief mark environment start
*
* This function is used to mark unclosed environment,i.e. environments which are unclosed at the end of the text
* \param env used environment
*/
void SyntaxCheck::markUnclosedEnv(Environment env)
{
QDocumentLineHandle *dlh = env.dlh;
if (!dlh)
return;
dlh->lockForWrite();
if (dlh->getCurrentTicket() == env.ticket) {
QString line = dlh->text();
line = ltxCommands->cutComment(line);
QString cmd = "\\begin{" + env.name + "}";
int index = line.lastIndexOf(cmd);
if (index >= 0) {
Error elem;
elem.range = QPair<int, int>(index, cmd.length());
elem.type = ERR_EnvNotClosed;
dlh->addOverlayNoLock(QFormatRange(elem.range.first, elem.range.second, syntaxErrorFormat));
QVariant var_env;
StackEnvironment activeEnv;
activeEnv.append(env);
var_env.setValue(activeEnv);
dlh->setCookie(QDocumentLine::UNCLOSED_ENVIRONMENT_COOKIE, var_env); //ERR_EnvNotClosed;
}
}
dlh->unlock();
}
/*!
* \brief check if the tokenstack contains a definition-token
* \param stack tokenstack
* \return contains a definition
*/
bool SyntaxCheck::stackContainsDefinition(const TokenStack &stack) const
{
for (int i = 0; i < stack.size(); i++) {
if (stack[i].subtype == Tokens::definition)
return true;
}
return false;
}
/*!
* \brief check one line
*
* Checks one line. Context information needs to be given by newRanges,activeEnv,dlh and ticket.
* This method is obsolete as the new system relies on tokens.
* \param line text of line as string
* \param newRanges will return the result as ranges
* \param activeEnv environment context
* \param dlh linehandle
* \param tl tokenlist of line
* \param stack token stack at start of line
* \param ticket ticket number for current processed line
*/
void SyntaxCheck::checkLine(const QString &line, Ranges &newRanges, StackEnvironment &activeEnv, QDocumentLineHandle *dlh, TokenList tl, TokenStack stack, int ticket)
{
// do syntax check on that line
int cols = containsEnv(*ltxCommands, "tabular", activeEnv);
// check command-words
for (int i = 0; i < tl.length(); i++) {
Tokens tk = tl.at(i);
// ignore commands in definition arguments e.g. \newcommand{cmd}{definition}
if (stackContainsDefinition(stack)) {
Tokens top = stack.top();
if (top.dlh != tk.dlh) {
if (tk.type == Tokens::closeBrace) {
stack.pop();
} else
continue;
} else {
if (tk.start < top.start + top.length)
continue;
else
stack.pop();
}
}
if (tk.subtype == Tokens::definition && (tk.type == Tokens::braces || tk.type == Tokens::openBrace)) {
stack.push(tk);
continue;
}
if (tk.type == Tokens::punctuation || tk.type == Tokens::symbol) {
QString word = line.mid(tk.start, tk.length);
QStringList forbiddenSymbols;
forbiddenSymbols<<"^"<<"_";
if(forbiddenSymbols.contains(word) && !containsEnv(*ltxCommands, "math", activeEnv)){
Error elem;
elem.range = QPair<int, int>(tk.start, tk.length);
elem.type = ERR_MathCommandOutsideMath;
newRanges.append(elem);
}
}
if (tk.type == Tokens::commandUnknown) {
QString word = line.mid(tk.start, tk.length);
if (word.contains('@')) {
continue; //ignore commands containg @
}
if (ltxCommands->possibleCommands["user"].contains(word) || ltxCommands->customCommands.contains(word))
continue;
if (ltxCommands->mathStartCommands.contains(word) && (activeEnv.isEmpty() || activeEnv.top().name != "math")) {
Environment env;
env.name = "math";
env.origName=word;
env.id = 1; // to be changed
env.dlh = dlh;
env.ticket = ticket;
env.level = tk.level;
activeEnv.push(env);
continue;
}
if (ltxCommands->mathStopCommands.contains(word) && !activeEnv.isEmpty() && activeEnv.top().name == "math") {
int i=ltxCommands->mathStopCommands.indexOf(word);
QString txt=ltxCommands->mathStartCommands.value(i);
if(activeEnv.top().origName==txt){
activeEnv.pop();
}// ignore mismatching mathstop commands
continue;
}
if (word == "\\\\" && topEnv("tabular", activeEnv) != 0 && tk.level == activeEnv.top().level) {
if (activeEnv.top().excessCol < (activeEnv.top().id - 1)) {
Error elem;
elem.range = QPair<int, int>(tk.start, tk.length);
elem.type = ERR_tooLittleCols;
newRanges.append(elem);
}
if (activeEnv.top().excessCol >= (activeEnv.top().id)) {
Error elem;
elem.range = QPair<int, int>(tk.start, tk.length);
elem.type = ERR_tooManyCols;
newRanges.append(elem);
}
activeEnv.top().excessCol = 0;
continue;
}
if (!checkCommand(word, activeEnv)) {
Error elem;
elem.range = QPair<int, int>(tk.start, tk.length);
elem.type = ERR_unrecognizedCommand;
newRanges.append(elem);
continue;
}
}
if (tk.type == Tokens::env) {
QString env = line.mid(tk.start, tk.length);
// corresponds \end{env}
if (!activeEnv.isEmpty()) {
Environment tp = activeEnv.top();
if (tp.name == env) {
activeEnv.pop();
if (tp.name == "tabular" || ltxCommands->environmentAliases.values(tp.name).contains("tabular")) {
// correct length of col error if it exists
if (!newRanges.isEmpty()) {
Error &elem = newRanges.last();
if (elem.type == ERR_tooManyCols && elem.range.first + elem.range.second > tk.start) {
elem.range.second = tk.start - elem.range.first;
}
}
// get new cols
cols = containsEnv(*ltxCommands, "tabular", activeEnv);
}
} else {
Error elem;
elem.range = QPair<int, int>(tk.start, tk.length);
elem.type = ERR_closingUnopendEnv;
newRanges.append(elem);
}
} else {
Error elem;
elem.range = QPair<int, int>(tk.start, tk.length);
elem.type = ERR_closingUnopendEnv;
newRanges.append(elem);
}
}
if (tk.type == Tokens::beginEnv) {
QString env = line.mid(tk.start, tk.length);
// corresponds \begin{env}
Environment tp;
tp.name = env;
tp.id = 1; //needs correction
tp.excessCol = 0;
tp.dlh = dlh;
tp.ticket = ticket;
tp.level = tk.level-1; // tk is the argument, not the command, hence -1
if (env == "tabular" || ltxCommands->environmentAliases.values(env).contains("tabular")) {
// tabular env opened
// get cols !!!!
QString option;
if ((env == "tabu") || (env == "longtabu")) { // special treatment as the env is rather not latex standard
for (int k = i + 1; k < tl.length(); k++) {
Tokens elem = tl.at(k);
if (elem.level < tk.level - 1)
break;
if (elem.level >= tk.level)
continue;
if (elem.type == Tokens::braces) { // take the first mandatory argument at the correct level -> TODO: put colDef also for tabu correctly in lexer
option = line.mid(elem.start + 1, elem.length - 2); // strip {}
}
}
} else {
for (int k = i + 1; k < tl.length(); k++) {
Tokens elem = tl.at(k);
if (elem.level < tk.level - 1)
break;
if (elem.level >= tk.level)
continue;
if (elem.subtype == Tokens::colDef) {
option = line.mid(elem.start + 1, elem.length - 2); // strip {}
break;
}
}
}
QStringList res = LatexTables::splitColDef(option);
cols = res.count();
tp.id = cols;
}
activeEnv.push(tp);
}
if (tk.type == Tokens::command) {
QString word = line.mid(tk.start, tk.length);
if (word == "\\begin" || word == "\\end") {
// check complete expression e.g. \begin{something}
if (tl.length() > i + 1 && tl.at(i + 1).type == Tokens::braces) {
word = word + line.mid(tl.at(i + 1).start, tl.at(i + 1).length);
}
}
if (ltxCommands->possibleCommands["user"].contains(word) || ltxCommands->customCommands.contains(word))
continue;
if (ltxCommands->mathStartCommands.contains(word) && (activeEnv.isEmpty() || activeEnv.top().name != "math")) {
Environment env;
env.name = "math";
env.origName=word;
env.id = 1; // to be changed
env.dlh = dlh;
env.ticket = ticket;
env.level = tk.level;
activeEnv.push(env);
continue;
}
if (ltxCommands->mathStopCommands.contains(word) && !activeEnv.isEmpty() && activeEnv.top().name == "math") {
int i=ltxCommands->mathStopCommands.indexOf(word);
QString txt=ltxCommands->mathStartCommands.value(i);
if(activeEnv.top().origName==txt){
activeEnv.pop();
}// ignore mismatching mathstop commands
continue;
}
//tabular checking
if (topEnv("tabular", activeEnv) != 0) {
if (word == "&") {
activeEnv.top().excessCol++;
if (activeEnv.top().excessCol >= activeEnv.top().id) {
Error elem;
elem.range = QPair<int, int>(tk.start, tk.length);
elem.type = ERR_tooManyCols;
newRanges.append(elem);
}
continue;
}
if ((word == "\\\\") || (word == "\\tabularnewline")) {
if (activeEnv.top().excessCol < (activeEnv.top().id - 1)) {
Error elem;
elem.range = QPair<int, int>(tk.start, tk.length);
elem.type = ERR_tooLittleCols;
newRanges.append(elem);
}
if (activeEnv.top().excessCol >= (activeEnv.top().id)) {
Error elem;
elem.range = QPair<int, int>(tk.start, tk.length);
elem.type = ERR_tooManyCols;
newRanges.append(elem);
}
activeEnv.top().excessCol = 0;
continue;
}
if (word == "\\multicolumn") {
QRegExp rxMultiColumn("\\\\multicolumn\\{(\\d+)\\}\\{.+\\}\\{.+\\}");
rxMultiColumn.setMinimal(true);
int res = rxMultiColumn.indexIn(line, tk.start);
if (res > -1) {
// multicoulmn before &
bool ok;
int c = rxMultiColumn.cap(1).toInt(&ok);
if (ok) {
activeEnv.top().excessCol += c - 1;
}
}
if (activeEnv.top().excessCol >= activeEnv.top().id) {
Error elem;
elem.range = QPair<int, int>(tk.start, tk.length);
elem.type = ERR_tooManyCols;
newRanges.append(elem);
}
continue;
}
}
if (!checkCommand(word, activeEnv)) {
Error elem;
elem.range = QPair<int, int>(tk.start, tk.length);
elem.type = ERR_unrecognizedCommand;
if (ltxCommands->possibleCommands["math"].contains(word))
elem.type = ERR_MathCommandOutsideMath;
if (ltxCommands->possibleCommands["tabular"].contains(word))
elem.type = ERR_TabularCommandOutsideTab;
if (ltxCommands->possibleCommands["tabbing"].contains(word))
elem.type = ERR_TabbingCommandOutside;
newRanges.append(elem);
}
}
if (tk.type == Tokens::specialArg) {
QString value = line.mid(tk.start, tk.length);
QString special = ltxCommands->mapSpecialArgs.value(int(tk.type - Tokens::specialArg));
if (!ltxCommands->possibleCommands[special].contains(value)) {
Error elem;
elem.range = QPair<int, int>(tk.start, tk.length);
elem.type = ERR_unrecognizedKey;
newRanges.append(elem);
}
}
if (tk.type == Tokens::keyVal_key) {
// special treatment for key val checking
QString command = tk.optionalCommandName;
QString value = line.mid(tk.start, tk.length);
// search stored keyvals
QString elem;
foreach (elem, ltxCommands->possibleCommands.keys()) {
if (elem.startsWith("key%") && elem.mid(4) == command)
break;
if (elem.startsWith("key%") && elem.mid(4, command.length()) == command && elem.mid(4 + command.length(), 1) == "/" && !elem.endsWith("#c")) {
// special treatment for distinguishing \command[keyvals]{test} where argument needs to equal test (used in yathesis.cwl)
// now find mandatory argument
QString subcommand;
for (int k = i + 1; k < tl.length(); k++) {
Tokens tk_elem = tl.at(k);
if (tk_elem.level > tk.level - 1)
continue;
if (tk_elem.level < tk.level - 1)
break;
if (tk_elem.type == Tokens::braces) {
subcommand = line.mid(tk_elem.start + 1, tk_elem.length - 2);
if (elem == "key%" + command + "/" + subcommand) {
break;
} else {
subcommand.clear();
}
}
}
if (!subcommand.isEmpty())
elem = "key%" + command + "/" + subcommand;
else
elem.clear();
break;
}
elem.clear();
}
if (!elem.isEmpty()) {
QStringList lst = ltxCommands->possibleCommands[elem].values();
QStringList::iterator iterator;
QStringList toAppend;
for (iterator = lst.begin(); iterator != lst.end(); ++iterator) {
int i = iterator->indexOf("#");
if (i > -1)
*iterator = iterator->left(i);
i = iterator->indexOf("=");
if (i > -1) {
*iterator = iterator->left(i);
}
if (iterator->startsWith("%")) {
toAppend << ltxCommands->possibleCommands[*iterator].values();
}
}
lst << toAppend;
if (!lst.contains(value)) {
Error elem;
elem.range = QPair<int, int>(tk.start, tk.length);
elem.type = ERR_unrecognizedKey;
newRanges.append(elem);
}
}
}
if (tk.subtype == Tokens::keyVal_val) {
//figure out keyval
QString word = line.mid(tk.start, tk.length);
// first get command
Tokens cmd = getCommandTokenFromToken(tl, tk);
QString command = line.mid(cmd.start, cmd.length);
// figure out key
QString key;
for (int k = i - 1; k >= 0; k--) {
Tokens elem = tl.at(k);
if (elem.level == tk.level - 1) {
if (elem.type == Tokens::keyVal_key) {
key = line.mid(elem.start, elem.length);
}
break;
}
}
// find if values are defined
QString elem;
foreach (elem, ltxCommands->possibleCommands.keys()) {
if (elem.startsWith("key%") && elem.mid(4) == command)
break;
if (elem.startsWith("key%") && elem.mid(4, command.length()) == command && elem.mid(4 + command.length(), 1) == "/" && !elem.endsWith("#c")) {
// special treatment for distinguishing \command[keyvals]{test} where argument needs to equal test (used in yathesis.cwl)
// now find mandatory argument
QString subcommand;
for (int k = i + 1; k < tl.length(); k++) {
Tokens tk_elem = tl.at(k);
if (tk_elem.level > tk.level - 2)
continue;
if (tk_elem.level < tk.level - 2)
break;
if (tk_elem.type == Tokens::braces) {
subcommand = line.mid(tk_elem.start + 1, tk_elem.length - 2);
if (elem == "key%" + command + "/" + subcommand) {
break;
} else {
subcommand.clear();
}
}
}
if (!subcommand.isEmpty())
elem = "key%" + command + "/" + subcommand;
break;
}
elem.clear();
}
if (!elem.isEmpty()) {
// check whether keys is valid
QStringList lst = ltxCommands->possibleCommands[elem].values();
QStringList::iterator iterator;
QString options;
for (iterator = lst.begin(); iterator != lst.end(); ++iterator) {
int i = iterator->indexOf("#");
options.clear();
if (i > -1) {
options = iterator->mid(i + 1);
*iterator = iterator->left(i);
}
if (iterator->endsWith("=")) {
iterator->chop(1);
}
if (*iterator == key)
break;
}
if (iterator != lst.end() && !options.isEmpty()) {
QStringList l = options.split(",");
if (!l.contains(word)) {
Error elem;
elem.range = QPair<int, int>(tk.start, tk.length);
elem.type = ERR_unrecognizedKeyValues;
newRanges.append(elem);
}
}
}
}
}
}
|