File: LexLaTeX.cxx

package info (click to toggle)
scite 4.4.5-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 12,928 kB
  • sloc: cpp: 145,539; ansic: 19,277; python: 6,120; makefile: 806; perl: 200; sh: 184; sql: 160; objc: 18; ruby: 6; tcl: 6; php: 4
file content (559 lines) | stat: -rw-r--r-- 16,102 bytes parent folder | download
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
// Scintilla source code edit control
/** @file LexLaTeX.cxx
 ** Lexer for LaTeX2e.
  **/
// Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.

// Modified by G. HU in 2013. Added folding, syntax highting inside math environments, and changed some minor behaviors.

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <assert.h>
#include <ctype.h>
#include <vector>

#include "ILexer.h"
#include "Scintilla.h"
#include "SciLexer.h"

#include "PropSetSimple.h"
#include "WordList.h"
#include "LexAccessor.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "CharacterSet.h"
#include "LexerModule.h"
#include "DefaultLexer.h"
#include "LexerBase.h"

using namespace Scintilla;

using namespace std;

struct latexFoldSave {
	latexFoldSave() : structLev(0) {
		for (int i = 0; i < 8; ++i) openBegins[i] = 0;
	}
	latexFoldSave(const latexFoldSave &save) : structLev(save.structLev) {
		for (int i = 0; i < 8; ++i) openBegins[i] = save.openBegins[i];
	}
	latexFoldSave &operator=(const latexFoldSave &save) {
		if (this != &save) {
			structLev = save.structLev;
			for (int i = 0; i < 8; ++i) openBegins[i] = save.openBegins[i];
		}
		return *this;
	}
	int openBegins[8];
	Sci_Position structLev;
};

class LexerLaTeX : public LexerBase {
private:
	vector<int> modes;
	void setMode(Sci_Position line, int mode) {
		if (line >= static_cast<Sci_Position>(modes.size())) modes.resize(line + 1, 0);
		modes[line] = mode;
	}
	int getMode(Sci_Position line) {
		if (line >= 0 && line < static_cast<Sci_Position>(modes.size())) return modes[line];
		return 0;
	}
	void truncModes(Sci_Position numLines) {
		if (static_cast<Sci_Position>(modes.size()) > numLines * 2 + 256)
			modes.resize(numLines + 128);
	}

	vector<latexFoldSave> saves;
	void setSave(Sci_Position line, const latexFoldSave &save) {
		if (line >= static_cast<Sci_Position>(saves.size())) saves.resize(line + 1);
		saves[line] = save;
	}
	void getSave(Sci_Position line, latexFoldSave &save) {
		if (line >= 0 && line < static_cast<Sci_Position>(saves.size())) save = saves[line];
		else {
			save.structLev = 0;
			for (int i = 0; i < 8; ++i) save.openBegins[i] = 0;
		}
	}
	void truncSaves(Sci_Position numLines) {
		if (static_cast<Sci_Position>(saves.size()) > numLines * 2 + 256)
			saves.resize(numLines + 128);
	}
public:
	static ILexer5 *LexerFactoryLaTeX() {
		return new LexerLaTeX();
	}
	void SCI_METHOD Lex(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) override;
	void SCI_METHOD Fold(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) override;

	// ILexer5 methods
	const char * SCI_METHOD GetName() override {
		return "latex";
	}
	int SCI_METHOD  GetIdentifier() override {
		return SCLEX_LATEX;
	}
};

static bool latexIsSpecial(int ch) {
	return (ch == '#') || (ch == '$') || (ch == '%') || (ch == '&') || (ch == '_') ||
		   (ch == '{') || (ch == '}') || (ch == ' ');
}

static bool latexIsBlank(int ch) {
	return (ch == ' ') || (ch == '\t');
}

static bool latexIsBlankAndNL(int ch) {
	return (ch == ' ') || (ch == '\t') || (ch == '\r') || (ch == '\n');
}

static bool latexIsLetter(int ch) {
	return IsASCII(ch) && isalpha(ch);
}

static bool latexIsTagValid(Sci_Position &i, Sci_Position l, Accessor &styler) {
	while (i < l) {
		if (styler.SafeGetCharAt(i) == '{') {
			while (i < l) {
				i++;
				if (styler.SafeGetCharAt(i) == '}') {
					return true;
				}	else if (!latexIsLetter(styler.SafeGetCharAt(i)) &&
                   styler.SafeGetCharAt(i)!='*') {
					return false;
				}
			}
		} else if (!latexIsBlank(styler.SafeGetCharAt(i))) {
			return false;
		}
		i++;
	}
	return false;
}

static bool latexNextNotBlankIs(Sci_Position i, Accessor &styler, char needle) {
  char ch;
	while (i < styler.Length()) {
    ch = styler.SafeGetCharAt(i);
		if (!latexIsBlankAndNL(ch) && ch != '*') {
      if (ch == needle)
        return true;
      else
        return false;
		}
		i++;
	}
	return false;
}

static bool latexLastWordIs(Sci_Position start, Accessor &styler, const char *needle) {
	Sci_PositionU i = 0;
	Sci_PositionU l = static_cast<Sci_PositionU>(strlen(needle));
	Sci_Position ini = start-l+1;
	char s[32];

	while (i < l && i < 31) {
		s[i] = styler.SafeGetCharAt(ini + i);
		i++;
	}
	s[i] = '\0';

	return (strcmp(s, needle) == 0);
}

static bool latexLastWordIsMathEnv(Sci_Position pos, Accessor &styler) {
	Sci_Position i, j;
	char s[32];
	const char *mathEnvs[] = { "align", "alignat", "flalign", "gather",
		"multiline", "displaymath", "eqnarray", "equation" };
	if (styler.SafeGetCharAt(pos) != '}') return false;
	for (i = pos - 1; i >= 0; --i) {
		if (styler.SafeGetCharAt(i) == '{') break;
		if (pos - i >= 20) return false;
	}
	if (i < 0 || i == pos - 1) return false;
	++i;
	for (j = 0; i + j < pos; ++j)
		s[j] = styler.SafeGetCharAt(i + j);
	s[j] = '\0';
	if (j == 0) return false;
	if (s[j - 1] == '*') s[--j] = '\0';
	for (i = 0; i < static_cast<int>(sizeof(mathEnvs) / sizeof(const char *)); ++i)
		if (strcmp(s, mathEnvs[i]) == 0) return true;
	return false;
}

static inline void latexStateReset(int &mode, int &state) {
	switch (mode) {
	case 1:     state = SCE_L_MATH; break;
	case 2:     state = SCE_L_MATH2; break;
	default:    state = SCE_L_DEFAULT; break;
	}
}

// There are cases not handled correctly, like $abcd\textrm{what is $x+y$}z+w$.
// But I think it's already good enough.
void SCI_METHOD LexerLaTeX::Lex(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) {
	// startPos is assumed to be the first character of a line
	Accessor styler(pAccess, &props);
	styler.StartAt(startPos);
	int mode = getMode(styler.GetLine(startPos) - 1);
	int state = initStyle;
	if (state == SCE_L_ERROR || state == SCE_L_SHORTCMD || state == SCE_L_SPECIAL)   // should not happen
		latexStateReset(mode, state);

	char chNext = styler.SafeGetCharAt(startPos);
	char chVerbatimDelim = '\0';
	styler.StartSegment(startPos);
	Sci_Position lengthDoc = startPos + length;

	for (Sci_Position i = startPos; i < lengthDoc; i++) {
		char ch = chNext;
		chNext = styler.SafeGetCharAt(i + 1);

		if (styler.IsLeadByte(ch)) {
			i++;
			chNext = styler.SafeGetCharAt(i + 1);
			continue;
		}

		if (ch == '\r' || ch == '\n')
			setMode(styler.GetLine(i), mode);

		switch (state) {
		case SCE_L_DEFAULT :
			switch (ch) {
			case '\\' :
				styler.ColourTo(i - 1, state);
				if (latexIsLetter(chNext)) {
					state = SCE_L_COMMAND;
				} else if (latexIsSpecial(chNext)) {
					styler.ColourTo(i + 1, SCE_L_SPECIAL);
					i++;
					chNext = styler.SafeGetCharAt(i + 1);
				} else if (chNext == '\r' || chNext == '\n') {
					styler.ColourTo(i, SCE_L_ERROR);
				} else if (IsASCII(chNext)) {
					styler.ColourTo(i + 1, SCE_L_SHORTCMD);
					if (chNext == '(') {
						mode = 1;
						state = SCE_L_MATH;
					} else if (chNext == '[') {
						mode = 2;
						state = SCE_L_MATH2;
					}
					i++;
					chNext = styler.SafeGetCharAt(i + 1);
				}
				break;
			case '$' :
				styler.ColourTo(i - 1, state);
				if (chNext == '$') {
					styler.ColourTo(i + 1, SCE_L_SHORTCMD);
					mode = 2;
					state = SCE_L_MATH2;
					i++;
					chNext = styler.SafeGetCharAt(i + 1);
				} else {
					styler.ColourTo(i, SCE_L_SHORTCMD);
					mode = 1;
					state = SCE_L_MATH;
				}
				break;
			case '%' :
				styler.ColourTo(i - 1, state);
				state = SCE_L_COMMENT;
				break;
			}
			break;
		// These 3 will never be reached.
		case SCE_L_ERROR:
		case SCE_L_SPECIAL:
		case SCE_L_SHORTCMD:
			break;
		case SCE_L_COMMAND :
			if (!latexIsLetter(chNext)) {
				styler.ColourTo(i, state);
				if (latexNextNotBlankIs(i + 1, styler, '[' )) {
					state = SCE_L_CMDOPT;
				} else if (latexLastWordIs(i, styler, "\\begin")) {
					state = SCE_L_TAG;
				} else if (latexLastWordIs(i, styler, "\\end")) {
					state = SCE_L_TAG2;
				} else if (latexLastWordIs(i, styler, "\\verb") && chNext != '*' && chNext != ' ') {
					chVerbatimDelim = chNext;
					state = SCE_L_VERBATIM;
				} else {
					latexStateReset(mode, state);
				}
			}
			break;
		case SCE_L_CMDOPT :
			if (ch == ']') {
				styler.ColourTo(i, state);
				latexStateReset(mode, state);
			}
			break;
		case SCE_L_TAG :
			if (latexIsTagValid(i, lengthDoc, styler)) {
				styler.ColourTo(i, state);
				latexStateReset(mode, state);
				if (latexLastWordIs(i, styler, "{verbatim}")) {
					state = SCE_L_VERBATIM;
				} else if (latexLastWordIs(i, styler, "{lstlisting}")) {
					state = SCE_L_VERBATIM;
				} else if (latexLastWordIs(i, styler, "{comment}")) {
					state = SCE_L_COMMENT2;
				} else if (latexLastWordIs(i, styler, "{math}") && mode == 0) {
					mode = 1;
					state = SCE_L_MATH;
				} else if (latexLastWordIsMathEnv(i, styler) && mode == 0) {
					mode = 2;
					state = SCE_L_MATH2;
				}
			} else {
				styler.ColourTo(i, SCE_L_ERROR);
				latexStateReset(mode, state);
				ch = styler.SafeGetCharAt(i);
				if (ch == '\r' || ch == '\n') setMode(styler.GetLine(i), mode);
			}
			chNext = styler.SafeGetCharAt(i+1);
			break;
		case SCE_L_TAG2 :
			if (latexIsTagValid(i, lengthDoc, styler)) {
				styler.ColourTo(i, state);
				latexStateReset(mode, state);
			} else {
				styler.ColourTo(i, SCE_L_ERROR);
				latexStateReset(mode, state);
				ch = styler.SafeGetCharAt(i);
				if (ch == '\r' || ch == '\n') setMode(styler.GetLine(i), mode);
			}
			chNext = styler.SafeGetCharAt(i+1);
			break;
		case SCE_L_MATH :
			switch (ch) {
			case '\\' :
				styler.ColourTo(i - 1, state);
				if (latexIsLetter(chNext)) {
					Sci_Position match = i + 3;
					if (latexLastWordIs(match, styler, "\\end")) {
						match++;
						if (latexIsTagValid(match, lengthDoc, styler)) {
							if (latexLastWordIs(match, styler, "{math}"))
								mode = 0;
						}
					}
					state = SCE_L_COMMAND;
				} else if (latexIsSpecial(chNext)) {
					styler.ColourTo(i + 1, SCE_L_SPECIAL);
					i++;
					chNext = styler.SafeGetCharAt(i + 1);
				} else if (chNext == '\r' || chNext == '\n') {
					styler.ColourTo(i, SCE_L_ERROR);
				} else if (IsASCII(chNext)) {
					if (chNext == ')') {
						mode = 0;
						state = SCE_L_DEFAULT;
					}
					styler.ColourTo(i + 1, SCE_L_SHORTCMD);
					i++;
					chNext = styler.SafeGetCharAt(i + 1);
				}
				break;
			case '$' :
				styler.ColourTo(i - 1, state);
				styler.ColourTo(i, SCE_L_SHORTCMD);
				mode = 0;
				state = SCE_L_DEFAULT;
				break;
			case '%' :
				styler.ColourTo(i - 1, state);
				state = SCE_L_COMMENT;
				break;
			}
			break;
		case SCE_L_MATH2 :
			switch (ch) {
			case '\\' :
				styler.ColourTo(i - 1, state);
				if (latexIsLetter(chNext)) {
					Sci_Position match = i + 3;
					if (latexLastWordIs(match, styler, "\\end")) {
						match++;
						if (latexIsTagValid(match, lengthDoc, styler)) {
							if (latexLastWordIsMathEnv(match, styler))
								mode = 0;
						}
					}
					state = SCE_L_COMMAND;
				} else if (latexIsSpecial(chNext)) {
					styler.ColourTo(i + 1, SCE_L_SPECIAL);
					i++;
					chNext = styler.SafeGetCharAt(i + 1);
				} else if (chNext == '\r' || chNext == '\n') {
					styler.ColourTo(i, SCE_L_ERROR);
				} else if (IsASCII(chNext)) {
					if (chNext == ']') {
						mode = 0;
						state = SCE_L_DEFAULT;
					}
					styler.ColourTo(i + 1, SCE_L_SHORTCMD);
					i++;
					chNext = styler.SafeGetCharAt(i + 1);
				}
				break;
			case '$' :
				styler.ColourTo(i - 1, state);
				if (chNext == '$') {
					styler.ColourTo(i + 1, SCE_L_SHORTCMD);
					i++;
					chNext = styler.SafeGetCharAt(i + 1);
					mode = 0;
					state = SCE_L_DEFAULT;
				} else { // This may not be an error, e.g. \begin{equation}\text{$a$}\end{equation}
					styler.ColourTo(i, SCE_L_SHORTCMD);
				}
				break;
			case '%' :
				styler.ColourTo(i - 1, state);
				state = SCE_L_COMMENT;
				break;
			}
			break;
		case SCE_L_COMMENT :
			if (ch == '\r' || ch == '\n') {
				styler.ColourTo(i - 1, state);
				latexStateReset(mode, state);
			}
			break;
		case SCE_L_COMMENT2 :
			if (ch == '\\') {
				Sci_Position match = i + 3;
				if (latexLastWordIs(match, styler, "\\end")) {
					match++;
					if (latexIsTagValid(match, lengthDoc, styler)) {
						if (latexLastWordIs(match, styler, "{comment}")) {
							styler.ColourTo(i - 1, state);
							state = SCE_L_COMMAND;
						}
					}
				}
			}
			break;
		case SCE_L_VERBATIM :
			if (ch == '\\') {
				Sci_Position match = i + 3;
				if (latexLastWordIs(match, styler, "\\end")) {
					match++;
					if (latexIsTagValid(match, lengthDoc, styler)) {
						if (latexLastWordIs(match, styler, "{verbatim}")) {
							styler.ColourTo(i - 1, state);
							state = SCE_L_COMMAND;
						} else if (latexLastWordIs(match, styler, "{lstlisting}")) {
							styler.ColourTo(i - 1, state);
							state = SCE_L_COMMAND;
						}
					}
				}
			} else if (chNext == chVerbatimDelim) {
				styler.ColourTo(i + 1, state);
				latexStateReset(mode, state);
				chVerbatimDelim = '\0';
				i++;
				chNext = styler.SafeGetCharAt(i + 1);
			} else if (chVerbatimDelim != '\0' && (ch == '\n' || ch == '\r')) {
				styler.ColourTo(i, SCE_L_ERROR);
				latexStateReset(mode, state);
				chVerbatimDelim = '\0';
			}
			break;
		}
	}
	if (lengthDoc == styler.Length()) truncModes(styler.GetLine(lengthDoc - 1));
	styler.ColourTo(lengthDoc - 1, state);
	styler.Flush();
}

static int latexFoldSaveToInt(const latexFoldSave &save) {
	int sum = 0;
	for (int i = 0; i <= save.structLev; ++i)
		sum += save.openBegins[i];
	return ((sum + save.structLev + SC_FOLDLEVELBASE) & SC_FOLDLEVELNUMBERMASK);
}

// Change folding state while processing a line
// Return the level before the first relevant command
void SCI_METHOD LexerLaTeX::Fold(Sci_PositionU startPos, Sci_Position length, int, IDocument *pAccess) {
	const char *structWords[7] = {"part", "chapter", "section", "subsection",
		"subsubsection", "paragraph", "subparagraph"};
	Accessor styler(pAccess, &props);
	Sci_PositionU endPos = startPos + length;
	Sci_Position curLine = styler.GetLine(startPos);
	latexFoldSave save;
	getSave(curLine - 1, save);
	do {
		char ch, buf[16];
		Sci_Position i, j;
		int lev = -1;
		bool needFold = false;
		for (i = static_cast<Sci_Position>(startPos); i < static_cast<Sci_Position>(endPos); ++i) {
			ch = styler.SafeGetCharAt(i);
			if (ch == '\r' || ch == '\n') break;
			if (ch != '\\' || styler.StyleAt(i) != SCE_L_COMMAND) continue;
			for (j = 0; j < 15 && i + 1 < static_cast<Sci_Position>(endPos); ++j, ++i) {
				buf[j] = styler.SafeGetCharAt(i + 1);
				if (!latexIsLetter(buf[j])) break;
			}
			buf[j] = '\0';
			if (strcmp(buf, "begin") == 0) {
				if (lev < 0) lev = latexFoldSaveToInt(save);
				++save.openBegins[save.structLev];
				needFold = true;
			}
			else if (strcmp(buf, "end") == 0) {
				while (save.structLev > 0 && save.openBegins[save.structLev] == 0)
					--save.structLev;
				if (lev < 0) lev = latexFoldSaveToInt(save);
				if (save.openBegins[save.structLev] > 0) --save.openBegins[save.structLev];
			}
			else {
				for (j = 0; j < 7; ++j)
					if (strcmp(buf, structWords[j]) == 0) break;
				if (j >= 7) continue;
				save.structLev = j;   // level before the command
				for (j = save.structLev + 1; j < 8; ++j) {
					save.openBegins[save.structLev] += save.openBegins[j];
					save.openBegins[j] = 0;
				}
				if (lev < 0) lev = latexFoldSaveToInt(save);
				++save.structLev;   // level after the command
				needFold = true;
			}
		}
		if (lev < 0) lev = latexFoldSaveToInt(save);
		if (needFold) lev |= SC_FOLDLEVELHEADERFLAG;
		styler.SetLevel(curLine, lev);
		setSave(curLine, save);
		++curLine;
		startPos = styler.LineStart(curLine);
		if (static_cast<Sci_Position>(startPos) == styler.Length()) {
			lev = latexFoldSaveToInt(save);
			styler.SetLevel(curLine, lev);
			setSave(curLine, save);
			truncSaves(curLine);
		}
	} while (startPos < endPos);
	styler.Flush();
}

static const char *const emptyWordListDesc[] = {
	0
};

LexerModule lmLatex(SCLEX_LATEX, LexerLaTeX::LexerFactoryLaTeX, "latex", emptyWordListDesc);