CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
sagemathinc

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/frontend/codemirror/mode/pari.js
Views: 687
1
/*
2
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
3
* License: MS-RSL – see LICENSE.md for details
4
*/
5
6
import * as CodeMirror from "codemirror";
7
8
CodeMirror.defineMode("pari", function(config, parserConfig) {
9
var indentUnit = config.indentUnit,
10
statementIndentUnit = parserConfig.statementIndentUnit || indentUnit,
11
dontAlignCalls = parserConfig.dontAlignCalls,
12
keywords = parserConfig.keywords || {},
13
builtin = parserConfig.builtin || {},
14
blockKeywords = parserConfig.blockKeywords || {},
15
atoms = parserConfig.atoms || {},
16
hooks = parserConfig.hooks || {},
17
multiLineStrings = parserConfig.multiLineStrings;
18
var isOperatorChar = /[+\-*&%=<>!?|\/]/;
19
20
var curPunc;
21
22
function tokenBase(stream, state) {
23
var ch = stream.next();
24
if (hooks[ch]) {
25
var result = hooks[ch](stream, state);
26
if (result !== false) return result;
27
}
28
if (ch == '"' || ch == "'") {
29
state.tokenize = tokenString(ch);
30
return state.tokenize(stream, state);
31
}
32
if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
33
curPunc = ch;
34
return null;
35
}
36
if (/\d/.test(ch)) {
37
stream.eatWhile(/[\w\.]/);
38
return "number";
39
}
40
if (ch == "/") {
41
if (stream.eat("*")) {
42
state.tokenize = tokenComment;
43
return tokenComment(stream, state);
44
}
45
if (stream.eat("/")) {
46
stream.skipToEnd();
47
return "comment";
48
}
49
}
50
if (ch == "\\") {
51
if (stream.eat("\\")) {
52
stream.skipToEnd();
53
return "comment";
54
}
55
}
56
if (isOperatorChar.test(ch)) {
57
stream.eatWhile(isOperatorChar);
58
return "operator";
59
}
60
stream.eatWhile(/[\w\$_]/);
61
var cur = stream.current();
62
if (keywords.propertyIsEnumerable(cur)) {
63
if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
64
return "keyword";
65
}
66
if (builtin.propertyIsEnumerable(cur)) {
67
if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
68
return "builtin";
69
}
70
if (atoms.propertyIsEnumerable(cur)) return "atom";
71
return "variable";
72
}
73
74
function tokenString(quote) {
75
return function(stream, state) {
76
var escaped = false, next, end = false;
77
while ((next = stream.next()) != null) {
78
if (next == quote && !escaped) {end = true; break;}
79
escaped = !escaped && next == "\\";
80
}
81
if (end || !(escaped || multiLineStrings))
82
state.tokenize = null;
83
return "string";
84
};
85
}
86
87
function tokenComment(stream, state) {
88
var maybeEnd = false, ch;
89
while (ch = stream.next()) {
90
if (ch == "/" && maybeEnd) {
91
state.tokenize = null;
92
break;
93
}
94
maybeEnd = (ch == "*");
95
}
96
return "comment";
97
}
98
99
function Context(indented, column, type, align, prev) {
100
this.indented = indented;
101
this.column = column;
102
this.type = type;
103
this.align = align;
104
this.prev = prev;
105
}
106
function pushContext(state, col, type) {
107
var indent = state.indented;
108
if (state.context && state.context.type == "statement")
109
indent = state.context.indented;
110
return state.context = new Context(indent, col, type, null, state.context);
111
}
112
function popContext(state) {
113
var t = state.context.type;
114
if (t == ")" || t == "]" || t == "}")
115
state.indented = state.context.indented;
116
return state.context = state.context.prev;
117
}
118
119
// Interface
120
121
return {
122
startState: function(basecolumn) {
123
return {
124
tokenize: null,
125
context: new Context((basecolumn || 0) - indentUnit, 0, "top", false),
126
indented: 0,
127
startOfLine: true
128
};
129
},
130
131
token: function(stream, state) {
132
var ctx = state.context;
133
if (stream.sol()) {
134
if (ctx.align == null) ctx.align = false;
135
state.indented = stream.indentation();
136
state.startOfLine = true;
137
}
138
if (stream.eatSpace()) return null;
139
curPunc = null;
140
var style = (state.tokenize || tokenBase)(stream, state);
141
if (style == "comment" || style == "meta") return style;
142
if (ctx.align == null) ctx.align = true;
143
144
if ((curPunc == ";" || curPunc == ":" || curPunc == ",") && ctx.type == "statement") popContext(state);
145
else if (curPunc == "{") pushContext(state, stream.column(), "}");
146
else if (curPunc == "[") pushContext(state, stream.column(), "]");
147
else if (curPunc == "(") pushContext(state, stream.column(), ")");
148
else if (curPunc == "}") {
149
while (ctx.type == "statement") ctx = popContext(state);
150
if (ctx.type == "}") ctx = popContext(state);
151
while (ctx.type == "statement") ctx = popContext(state);
152
}
153
else if (curPunc == ctx.type) popContext(state);
154
else if (((ctx.type == "}" || ctx.type == "top") && curPunc != ';') || (ctx.type == "statement" && curPunc == "newstatement"))
155
pushContext(state, stream.column(), "statement");
156
state.startOfLine = false;
157
return style;
158
},
159
160
indent: function(state, textAfter) {
161
if (state.tokenize != tokenBase && state.tokenize != null) return CodeMirror.Pass;
162
var ctx = state.context, firstChar = textAfter && textAfter.charAt(0);
163
if (ctx.type == "statement" && firstChar == "}") ctx = ctx.prev;
164
var closing = firstChar == ctx.type;
165
if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : statementIndentUnit);
166
else if (ctx.align && (!dontAlignCalls || ctx.type != ")")) return ctx.column + (closing ? 0 : 1);
167
else if (ctx.type == ")" && !closing) return ctx.indented + statementIndentUnit;
168
else return ctx.indented + (closing ? 0 : indentUnit);
169
},
170
171
electricChars: "{}",
172
blockCommentStart: "/*",
173
blockCommentEnd: "*/",
174
lineComment: "\\\\",
175
fold: "brace"
176
};
177
});
178
179
(function() {
180
function words(str) {
181
var obj = {}, words = str.split(" ");
182
for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
183
return obj;
184
}
185
var cKeywords = "Col Euler I List Mat Mod O Pi Pol Polrev Qfb Ser Set Str Strchr Strexpand Strprintf Strtex Vec Vecrev Vecsmall abs acos acosh addhelp addprimes agm alarm algdep alias allocatemem apply arg asin asinh atan atanh bernfrac bernreal bernvec besselh1 besselh2 besseli besselj besseljh besselk besseln bestappr bezout bezoutres bigomega binary binomial bitand bitneg bitnegimply bitor bittest bitxor bnfcertify bnfcompress bnfdecodemodule bnfinit bnfisintnorm bnfisnorm bnfisprincipal bnfissunit bnfisunit bnfnarrow bnfsignunit bnfsunit bnrL1 bnrclassno bnrclassnolist bnrconductor bnrconductorofchar bnrdisc bnrdisclist bnrinit bnrisconductor bnrisprincipal bnrrootnumber bnrstark break ceil centerlift charpoly chinese component concat conj conjvec content contfrac contfracpnqn core coredisc cos cosh cotan default denominator deriv derivnum diffop dilog dirdiv direuler dirmul dirzetak divisors divrem eint1 ellL1 elladd ellak ellan ellanalyticrank ellap ellbil ellchangecurve ellchangepoint ellconvertname elldivpol elleisnum elleta ellgenerators ellglobalred ellgroup ellheight ellheightmatrix ellidentify ellinit ellisoncurve ellj elllocalred elllog elllseries ellminimalmodel ellmodulareqn ellorder ellordinate ellpointtoz ellpow ellrootno ellsearch ellsigma ellsub elltaniyama elltatepairing elltors ellweilpairing ellwp ellzeta ellztopoint erfc error eta eulerphi eval exp extern externstr factor factorback factorcantor factorff factorial factorint factormod factornf factorpadic ffgen ffinit fflog fforder ffprimroot fibonacci floor for fordiv forell forprime forstep forsubgroup forvec frac galoisexport galoisfixedfield galoisgetpol galoisidentify galoisinit galoisisabelian galoisisnormal galoispermtopol galoissubcyclo galoissubfields galoissubgroups gamma gammah gcd getheap getrand getstack gettime global hilbert hyperu idealadd idealaddtoone idealappr idealchinese idealcoprime idealdiv idealfactor idealfactorback idealfrobenius idealhnf idealintersect idealinv ideallist ideallistarch ideallog idealmin idealmul idealnorm idealpow idealprimedec idealramgroups idealred idealstar idealtwoelt idealval if imag incgam incgamc input install intcirc intformal intfouriercos intfourierexp intfouriersin intfuncinit intlaplaceinv intmellininv intmellininvshort intnum intnuminit intnuminitgen intnumromb intnumstep isfundamental ispower isprime ispseudoprime issquare issquarefree kill kronecker lcm length lex lift lindep listcreate listinsert listkill listpop listput listsort lngamma local log matadjoint matalgtobasis matbasistoalg matcompanion matdet matdetint matdiagonal mateigen matfrobenius mathess mathilbert mathnf mathnfmod mathnfmodid matid matimage matimagecompl matindexrank matintersect matinverseimage matisdiagonal matker matkerint matmuldiagonal matmultodiagonal matpascal matrank matrix matrixqz matsize matsnf matsolve matsolvemod matsupplement mattranspose max min minpoly modreverse moebius my newtonpoly next nextprime nfalgtobasis nfbasis nfbasistoalg nfdetint nfdisc nfeltadd nfeltdiv nfeltdiveuc nfeltdivmodpr nfeltdivrem nfeltmod nfeltmul nfeltmulmodpr nfeltnorm nfeltpow nfeltpowmodpr nfeltreduce nfeltreducemodpr nfelttrace nfeltval nffactor nffactorback nffactormod nfgaloisapply nfgaloisconj nfhilbert nfhnf nfhnfmod nfinit nfisideal nfisincl nfisisom nfkermodpr nfmodprinit nfnewprec nfroots nfrootsof1 nfsnf nfsolvemodpr nfsubfields norm norml2 numbpart numdiv numerator numtoperm omega padicappr padicfields padicprec partitions permtonum plot plotbox plotclip plotcolor plotcopy plotcursor plotdraw ploth plothraw plothsizes plotinit plotkill plotlines plotlinetype plotmove plotpoints plotpointsize plotpointtype plotrbox plotrecth plotrecthraw plotrline plotrmove plotrpoint plotscale plotstring polchebyshev polcoeff polcompositum polcyclo poldegree poldisc poldiscreduced polgalois polhensellift polhermite polinterpolate polisirreducible pollead pollegendre polrecip polred polredabs polredbest polredord polresultant polroots polrootsff polrootsmod polrootspadic polsturm polsubcyclo polsylvestermatrix polsym poltchebi poltschirnhaus polylog polzagier precision precprime prime primepi primes print print1 printf printtex prod prodeuler prodinf psdraw psi psploth psplothraw qfbclassno qfbcompraw qfbhclassno qfbnucomp qfbnupow qfbpowraw qfbprimeform qfbred qfbsolve qfgaussred qfjacobi qflll qflllgram qfminim qfperfection qfrep qfsign quadclassunit quaddisc quadgen quadhilbert quadpoly quadray quadregulator quadunit quit random read readvec real removeprimes return rnfalgtobasis rnfbasis rnfbasistoalg rnfcharpoly rnfconductor rnfdedekind rnfdet rnfdisc rnfeltabstorel rnfeltdown rnfeltreltoabs rnfeltup rnfequation rnfhnfbasis rnfidealabstorel rnfidealdown rnfidealhnf rnfidealmul rnfidealnormabs rnfidealnormrel rnfidealreltoabs rnfidealtwoelt rnfidealup rnfinit rnfisabelian rnfisfree rnfisnorm rnfisnorminit rnfkummer rnflllgram rnfnormgroup rnfpolred rnfpolredabs rnfpseudobasis rnfsteinitz round select serconvol serlaplace serreverse setintersect setisset setminus setrand setsearch setunion shift shiftmul sigma sign simplify sin sinh sizebyte sizedigit solve sqr sqrt sqrtint sqrtn stirling subgrouplist subst substpol substvec sum sumalt sumdedekind sumdiv suminf sumnum sumnumalt sumnuminit sumpos system tan tanh taylor teichmuller theta thetanullk thue thueinit trace trap truncate type until valuation variable vecextract vecmax vecmin vecsort vector vectorsmall vectorv version warning weber whatnow while write write1 writebin writetex zeta zetak zetakinit zncoppersmith znlog znorder znprimroot znstar";
186
187
function cppHook(stream, state) {
188
if (!state.startOfLine) return false;
189
for (;;) {
190
if (stream.skipTo("\\")) {
191
stream.next();
192
if (stream.eol()) {
193
state.tokenize = cppHook;
194
break;
195
}
196
} else {
197
stream.skipToEnd();
198
state.tokenize = null;
199
break;
200
}
201
}
202
return "meta";
203
}
204
205
// C#-style strings where "" escapes a quote.
206
function tokenAtString(stream, state) {
207
var next;
208
while ((next = stream.next()) != null) {
209
if (next == '"' && !stream.eat('"')) {
210
state.tokenize = null;
211
break;
212
}
213
}
214
return "string";
215
}
216
217
function mimes(ms, mode) {
218
for (var i = 0; i < ms.length; ++i) CodeMirror.defineMIME(ms[i], mode);
219
}
220
221
mimes(["text/pari"], {
222
name: "pari",
223
keywords: words(cKeywords),
224
blockKeywords: words("catch class do else finally for if struct switch try while"),
225
atoms: words("true false null"),
226
hooks: {"#": cppHook}
227
});
228
}());
229
230