You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

942 lines
36 KiB

2 months ago
  1. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  2. // Distributed under an MIT license: https://codemirror.net/5/LICENSE
  3. (function(mod) {
  4. if (typeof exports == "object" && typeof module == "object") // CommonJS
  5. mod(require("../../lib/codemirror"));
  6. else if (typeof define == "function" && define.amd) // AMD
  7. define(["../../lib/codemirror"], mod);
  8. else // Plain browser env
  9. mod(CodeMirror);
  10. })(function(CodeMirror) {
  11. "use strict";
  12. function Context(indented, column, type, info, align, prev) {
  13. this.indented = indented;
  14. this.column = column;
  15. this.type = type;
  16. this.info = info;
  17. this.align = align;
  18. this.prev = prev;
  19. }
  20. function pushContext(state, col, type, info) {
  21. var indent = state.indented;
  22. if (state.context && state.context.type == "statement" && type != "statement")
  23. indent = state.context.indented;
  24. return state.context = new Context(indent, col, type, info, null, state.context);
  25. }
  26. function popContext(state) {
  27. var t = state.context.type;
  28. if (t == ")" || t == "]" || t == "}")
  29. state.indented = state.context.indented;
  30. return state.context = state.context.prev;
  31. }
  32. function typeBefore(stream, state, pos) {
  33. if (state.prevToken == "variable" || state.prevToken == "type") return true;
  34. if (/\S(?:[^- ]>|[*\]])\s*$|\*$/.test(stream.string.slice(0, pos))) return true;
  35. if (state.typeAtEndOfLine && stream.column() == stream.indentation()) return true;
  36. }
  37. function isTopScope(context) {
  38. for (;;) {
  39. if (!context || context.type == "top") return true;
  40. if (context.type == "}" && context.prev.info != "namespace") return false;
  41. context = context.prev;
  42. }
  43. }
  44. CodeMirror.defineMode("clike", function(config, parserConfig) {
  45. var indentUnit = config.indentUnit,
  46. statementIndentUnit = parserConfig.statementIndentUnit || indentUnit,
  47. dontAlignCalls = parserConfig.dontAlignCalls,
  48. keywords = parserConfig.keywords || {},
  49. types = parserConfig.types || {},
  50. builtin = parserConfig.builtin || {},
  51. blockKeywords = parserConfig.blockKeywords || {},
  52. defKeywords = parserConfig.defKeywords || {},
  53. atoms = parserConfig.atoms || {},
  54. hooks = parserConfig.hooks || {},
  55. multiLineStrings = parserConfig.multiLineStrings,
  56. indentStatements = parserConfig.indentStatements !== false,
  57. indentSwitch = parserConfig.indentSwitch !== false,
  58. namespaceSeparator = parserConfig.namespaceSeparator,
  59. isPunctuationChar = parserConfig.isPunctuationChar || /[\[\]{}\(\),;\:\.]/,
  60. numberStart = parserConfig.numberStart || /[\d\.]/,
  61. number = parserConfig.number || /^(?:0x[a-f\d]+|0b[01]+|(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?)(u|ll?|l|f)?/i,
  62. isOperatorChar = parserConfig.isOperatorChar || /[+\-*&%=<>!?|\/]/,
  63. isIdentifierChar = parserConfig.isIdentifierChar || /[\w\$_\xa1-\uffff]/,
  64. // An optional function that takes a {string} token and returns true if it
  65. // should be treated as a builtin.
  66. isReservedIdentifier = parserConfig.isReservedIdentifier || false;
  67. var curPunc, isDefKeyword;
  68. function tokenBase(stream, state) {
  69. var ch = stream.next();
  70. if (hooks[ch]) {
  71. var result = hooks[ch](stream, state);
  72. if (result !== false) return result;
  73. }
  74. if (ch == '"' || ch == "'") {
  75. state.tokenize = tokenString(ch);
  76. return state.tokenize(stream, state);
  77. }
  78. if (numberStart.test(ch)) {
  79. stream.backUp(1)
  80. if (stream.match(number)) return "number"
  81. stream.next()
  82. }
  83. if (isPunctuationChar.test(ch)) {
  84. curPunc = ch;
  85. return null;
  86. }
  87. if (ch == "/") {
  88. if (stream.eat("*")) {
  89. state.tokenize = tokenComment;
  90. return tokenComment(stream, state);
  91. }
  92. if (stream.eat("/")) {
  93. stream.skipToEnd();
  94. return "comment";
  95. }
  96. }
  97. if (isOperatorChar.test(ch)) {
  98. while (!stream.match(/^\/[\/*]/, false) && stream.eat(isOperatorChar)) {}
  99. return "operator";
  100. }
  101. stream.eatWhile(isIdentifierChar);
  102. if (namespaceSeparator) while (stream.match(namespaceSeparator))
  103. stream.eatWhile(isIdentifierChar);
  104. var cur = stream.current();
  105. if (contains(keywords, cur)) {
  106. if (contains(blockKeywords, cur)) curPunc = "newstatement";
  107. if (contains(defKeywords, cur)) isDefKeyword = true;
  108. return "keyword";
  109. }
  110. if (contains(types, cur)) return "type";
  111. if (contains(builtin, cur)
  112. || (isReservedIdentifier && isReservedIdentifier(cur))) {
  113. if (contains(blockKeywords, cur)) curPunc = "newstatement";
  114. return "builtin";
  115. }
  116. if (contains(atoms, cur)) return "atom";
  117. return "variable";
  118. }
  119. function tokenString(quote) {
  120. return function(stream, state) {
  121. var escaped = false, next, end = false;
  122. while ((next = stream.next()) != null) {
  123. if (next == quote && !escaped) {end = true; break;}
  124. escaped = !escaped && next == "\\";
  125. }
  126. if (end || !(escaped || multiLineStrings))
  127. state.tokenize = null;
  128. return "string";
  129. };
  130. }
  131. function tokenComment(stream, state) {
  132. var maybeEnd = false, ch;
  133. while (ch = stream.next()) {
  134. if (ch == "/" && maybeEnd) {
  135. state.tokenize = null;
  136. break;
  137. }
  138. maybeEnd = (ch == "*");
  139. }
  140. return "comment";
  141. }
  142. function maybeEOL(stream, state) {
  143. if (parserConfig.typeFirstDefinitions && stream.eol() && isTopScope(state.context))
  144. state.typeAtEndOfLine = typeBefore(stream, state, stream.pos)
  145. }
  146. // Interface
  147. return {
  148. startState: function(basecolumn) {
  149. return {
  150. tokenize: null,
  151. context: new Context((basecolumn || 0) - indentUnit, 0, "top", null, false),
  152. indented: 0,
  153. startOfLine: true,
  154. prevToken: null
  155. };
  156. },
  157. token: function(stream, state) {
  158. var ctx = state.context;
  159. if (stream.sol()) {
  160. if (ctx.align == null) ctx.align = false;
  161. state.indented = stream.indentation();
  162. state.startOfLine = true;
  163. }
  164. if (stream.eatSpace()) { maybeEOL(stream, state); return null; }
  165. curPunc = isDefKeyword = null;
  166. var style = (state.tokenize || tokenBase)(stream, state);
  167. if (style == "comment" || style == "meta") return style;
  168. if (ctx.align == null) ctx.align = true;
  169. if (curPunc == ";" || curPunc == ":" || (curPunc == "," && stream.match(/^\s*(?:\/\/.*)?$/, false)))
  170. while (state.context.type == "statement") popContext(state);
  171. else if (curPunc == "{") pushContext(state, stream.column(), "}");
  172. else if (curPunc == "[") pushContext(state, stream.column(), "]");
  173. else if (curPunc == "(") pushContext(state, stream.column(), ")");
  174. else if (curPunc == "}") {
  175. while (ctx.type == "statement") ctx = popContext(state);
  176. if (ctx.type == "}") ctx = popContext(state);
  177. while (ctx.type == "statement") ctx = popContext(state);
  178. }
  179. else if (curPunc == ctx.type) popContext(state);
  180. else if (indentStatements &&
  181. (((ctx.type == "}" || ctx.type == "top") && curPunc != ";") ||
  182. (ctx.type == "statement" && curPunc == "newstatement"))) {
  183. pushContext(state, stream.column(), "statement", stream.current());
  184. }
  185. if (style == "variable" &&
  186. ((state.prevToken == "def" ||
  187. (parserConfig.typeFirstDefinitions && typeBefore(stream, state, stream.start) &&
  188. isTopScope(state.context) && stream.match(/^\s*\(/, false)))))
  189. style = "def";
  190. if (hooks.token) {
  191. var result = hooks.token(stream, state, style);
  192. if (result !== undefined) style = result;
  193. }
  194. if (style == "def" && parserConfig.styleDefs === false) style = "variable";
  195. state.startOfLine = false;
  196. state.prevToken = isDefKeyword ? "def" : style || curPunc;
  197. maybeEOL(stream, state);
  198. return style;
  199. },
  200. indent: function(state, textAfter) {
  201. if (state.tokenize != tokenBase && state.tokenize != null || state.typeAtEndOfLine && isTopScope(state.context))
  202. return CodeMirror.Pass;
  203. var ctx = state.context, firstChar = textAfter && textAfter.charAt(0);
  204. var closing = firstChar == ctx.type;
  205. if (ctx.type == "statement" && firstChar == "}") ctx = ctx.prev;
  206. if (parserConfig.dontIndentStatements)
  207. while (ctx.type == "statement" && parserConfig.dontIndentStatements.test(ctx.info))
  208. ctx = ctx.prev
  209. if (hooks.indent) {
  210. var hook = hooks.indent(state, ctx, textAfter, indentUnit);
  211. if (typeof hook == "number") return hook
  212. }
  213. var switchBlock = ctx.prev && ctx.prev.info == "switch";
  214. if (parserConfig.allmanIndentation && /[{(]/.test(firstChar)) {
  215. while (ctx.type != "top" && ctx.type != "}") ctx = ctx.prev
  216. return ctx.indented
  217. }
  218. if (ctx.type == "statement")
  219. return ctx.indented + (firstChar == "{" ? 0 : statementIndentUnit);
  220. if (ctx.align && (!dontAlignCalls || ctx.type != ")"))
  221. return ctx.column + (closing ? 0 : 1);
  222. if (ctx.type == ")" && !closing)
  223. return ctx.indented + statementIndentUnit;
  224. return ctx.indented + (closing ? 0 : indentUnit) +
  225. (!closing && switchBlock && !/^(?:case|default)\b/.test(textAfter) ? indentUnit : 0);
  226. },
  227. electricInput: indentSwitch ? /^\s*(?:case .*?:|default:|\{\}?|\})$/ : /^\s*[{}]$/,
  228. blockCommentStart: "/*",
  229. blockCommentEnd: "*/",
  230. blockCommentContinue: " * ",
  231. lineComment: "//",
  232. fold: "brace"
  233. };
  234. });
  235. function words(str) {
  236. var obj = {}, words = str.split(" ");
  237. for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
  238. return obj;
  239. }
  240. function contains(words, word) {
  241. if (typeof words === "function") {
  242. return words(word);
  243. } else {
  244. return words.propertyIsEnumerable(word);
  245. }
  246. }
  247. var cKeywords = "auto if break case register continue return default do sizeof " +
  248. "static else struct switch extern typedef union for goto while enum const " +
  249. "volatile inline restrict asm fortran";
  250. // Keywords from https://en.cppreference.com/w/cpp/keyword includes C++20.
  251. var cppKeywords = "alignas alignof and and_eq audit axiom bitand bitor catch " +
  252. "class compl concept constexpr const_cast decltype delete dynamic_cast " +
  253. "explicit export final friend import module mutable namespace new noexcept " +
  254. "not not_eq operator or or_eq override private protected public " +
  255. "reinterpret_cast requires static_assert static_cast template this " +
  256. "thread_local throw try typeid typename using virtual xor xor_eq";
  257. var objCKeywords = "bycopy byref in inout oneway out self super atomic nonatomic retain copy " +
  258. "readwrite readonly strong weak assign typeof nullable nonnull null_resettable _cmd " +
  259. "@interface @implementation @end @protocol @encode @property @synthesize @dynamic @class " +
  260. "@public @package @private @protected @required @optional @try @catch @finally @import " +
  261. "@selector @encode @defs @synchronized @autoreleasepool @compatibility_alias @available";
  262. var objCBuiltins = "FOUNDATION_EXPORT FOUNDATION_EXTERN NS_INLINE NS_FORMAT_FUNCTION " +
  263. " NS_RETURNS_RETAINEDNS_ERROR_ENUM NS_RETURNS_NOT_RETAINED NS_RETURNS_INNER_POINTER " +
  264. "NS_DESIGNATED_INITIALIZER NS_ENUM NS_OPTIONS NS_REQUIRES_NIL_TERMINATION " +
  265. "NS_ASSUME_NONNULL_BEGIN NS_ASSUME_NONNULL_END NS_SWIFT_NAME NS_REFINED_FOR_SWIFT"
  266. // Do not use this. Use the cTypes function below. This is global just to avoid
  267. // excessive calls when cTypes is being called multiple times during a parse.
  268. var basicCTypes = words("int long char short double float unsigned signed " +
  269. "void bool");
  270. // Do not use this. Use the objCTypes function below. This is global just to avoid
  271. // excessive calls when objCTypes is being called multiple times during a parse.
  272. var basicObjCTypes = words("SEL instancetype id Class Protocol BOOL");
  273. // Returns true if identifier is a "C" type.
  274. // C type is defined as those that are reserved by the compiler (basicTypes),
  275. // and those that end in _t (Reserved by POSIX for types)
  276. // http://www.gnu.org/software/libc/manual/html_node/Reserved-Names.html
  277. function cTypes(identifier) {
  278. return contains(basicCTypes, identifier) || /.+_t$/.test(identifier);
  279. }
  280. // Returns true if identifier is a "Objective C" type.
  281. function objCTypes(identifier) {
  282. return cTypes(identifier) || contains(basicObjCTypes, identifier);
  283. }
  284. var cBlockKeywords = "case do else for if switch while struct enum union";
  285. var cDefKeywords = "struct enum union";
  286. function cppHook(stream, state) {
  287. if (!state.startOfLine) return false
  288. for (var ch, next = null; ch = stream.peek();) {
  289. if (ch == "\\" && stream.match(/^.$/)) {
  290. next = cppHook
  291. break
  292. } else if (ch == "/" && stream.match(/^\/[\/\*]/, false)) {
  293. break
  294. }
  295. stream.next()
  296. }
  297. state.tokenize = next
  298. return "meta"
  299. }
  300. function pointerHook(_stream, state) {
  301. if (state.prevToken == "type") return "type";
  302. return false;
  303. }
  304. // For C and C++ (and ObjC): identifiers starting with __
  305. // or _ followed by a capital letter are reserved for the compiler.
  306. function cIsReservedIdentifier(token) {
  307. if (!token || token.length < 2) return false;
  308. if (token[0] != '_') return false;
  309. return (token[1] == '_') || (token[1] !== token[1].toLowerCase());
  310. }
  311. function cpp14Literal(stream) {
  312. stream.eatWhile(/[\w\.']/);
  313. return "number";
  314. }
  315. function cpp11StringHook(stream, state) {
  316. stream.backUp(1);
  317. // Raw strings.
  318. if (stream.match(/^(?:R|u8R|uR|UR|LR)/)) {
  319. var match = stream.match(/^"([^\s\\()]{0,16})\(/);
  320. if (!match) {
  321. return false;
  322. }
  323. state.cpp11RawStringDelim = match[1];
  324. state.tokenize = tokenRawString;
  325. return tokenRawString(stream, state);
  326. }
  327. // Unicode strings/chars.
  328. if (stream.match(/^(?:u8|u|U|L)/)) {
  329. if (stream.match(/^["']/, /* eat */ false)) {
  330. return "string";
  331. }
  332. return false;
  333. }
  334. // Ignore this hook.
  335. stream.next();
  336. return false;
  337. }
  338. function cppLooksLikeConstructor(word) {
  339. var lastTwo = /(\w+)::~?(\w+)$/.exec(word);
  340. return lastTwo && lastTwo[1] == lastTwo[2];
  341. }
  342. // C#-style strings where "" escapes a quote.
  343. function tokenAtString(stream, state) {
  344. var next;
  345. while ((next = stream.next()) != null) {
  346. if (next == '"' && !stream.eat('"')) {
  347. state.tokenize = null;
  348. break;
  349. }
  350. }
  351. return "string";
  352. }
  353. // C++11 raw string literal is <prefix>"<delim>( anything )<delim>", where
  354. // <delim> can be a string up to 16 characters long.
  355. function tokenRawString(stream, state) {
  356. // Escape characters that have special regex meanings.
  357. var delim = state.cpp11RawStringDelim.replace(/[^\w\s]/g, '\\$&');
  358. var match = stream.match(new RegExp(".*?\\)" + delim + '"'));
  359. if (match)
  360. state.tokenize = null;
  361. else
  362. stream.skipToEnd();
  363. return "string";
  364. }
  365. function def(mimes, mode) {
  366. if (typeof mimes == "string") mimes = [mimes];
  367. var words = [];
  368. function add(obj) {
  369. if (obj) for (var prop in obj) if (obj.hasOwnProperty(prop))
  370. words.push(prop);
  371. }
  372. add(mode.keywords);
  373. add(mode.types);
  374. add(mode.builtin);
  375. add(mode.atoms);
  376. if (words.length) {
  377. mode.helperType = mimes[0];
  378. CodeMirror.registerHelper("hintWords", mimes[0], words);
  379. }
  380. for (var i = 0; i < mimes.length; ++i)
  381. CodeMirror.defineMIME(mimes[i], mode);
  382. }
  383. def(["text/x-csrc", "text/x-c", "text/x-chdr"], {
  384. name: "clike",
  385. keywords: words(cKeywords),
  386. types: cTypes,
  387. blockKeywords: words(cBlockKeywords),
  388. defKeywords: words(cDefKeywords),
  389. typeFirstDefinitions: true,
  390. atoms: words("NULL true false"),
  391. isReservedIdentifier: cIsReservedIdentifier,
  392. hooks: {
  393. "#": cppHook,
  394. "*": pointerHook,
  395. },
  396. modeProps: {fold: ["brace", "include"]}
  397. });
  398. def(["text/x-c++src", "text/x-c++hdr"], {
  399. name: "clike",
  400. keywords: words(cKeywords + " " + cppKeywords),
  401. types: cTypes,
  402. blockKeywords: words(cBlockKeywords + " class try catch"),
  403. defKeywords: words(cDefKeywords + " class namespace"),
  404. typeFirstDefinitions: true,
  405. atoms: words("true false NULL nullptr"),
  406. dontIndentStatements: /^template$/,
  407. isIdentifierChar: /[\w\$_~\xa1-\uffff]/,
  408. isReservedIdentifier: cIsReservedIdentifier,
  409. hooks: {
  410. "#": cppHook,
  411. "*": pointerHook,
  412. "u": cpp11StringHook,
  413. "U": cpp11StringHook,
  414. "L": cpp11StringHook,
  415. "R": cpp11StringHook,
  416. "0": cpp14Literal,
  417. "1": cpp14Literal,
  418. "2": cpp14Literal,
  419. "3": cpp14Literal,
  420. "4": cpp14Literal,
  421. "5": cpp14Literal,
  422. "6": cpp14Literal,
  423. "7": cpp14Literal,
  424. "8": cpp14Literal,
  425. "9": cpp14Literal,
  426. token: function(stream, state, style) {
  427. if (style == "variable" && stream.peek() == "(" &&
  428. (state.prevToken == ";" || state.prevToken == null ||
  429. state.prevToken == "}") &&
  430. cppLooksLikeConstructor(stream.current()))
  431. return "def";
  432. }
  433. },
  434. namespaceSeparator: "::",
  435. modeProps: {fold: ["brace", "include"]}
  436. });
  437. def("text/x-java", {
  438. name: "clike",
  439. keywords: words("abstract assert break case catch class const continue default " +
  440. "do else enum extends final finally for goto if implements import " +
  441. "instanceof interface native new package private protected public " +
  442. "return static strictfp super switch synchronized this throw throws transient " +
  443. "try volatile while @interface"),
  444. types: words("var byte short int long float double boolean char void Boolean Byte Character Double Float " +
  445. "Integer Long Number Object Short String StringBuffer StringBuilder Void"),
  446. blockKeywords: words("catch class do else finally for if switch try while"),
  447. defKeywords: words("class interface enum @interface"),
  448. typeFirstDefinitions: true,
  449. atoms: words("true false null"),
  450. number: /^(?:0x[a-f\d_]+|0b[01_]+|(?:[\d_]+\.?\d*|\.\d+)(?:e[-+]?[\d_]+)?)(u|ll?|l|f)?/i,
  451. hooks: {
  452. "@": function(stream) {
  453. // Don't match the @interface keyword.
  454. if (stream.match('interface', false)) return false;
  455. stream.eatWhile(/[\w\$_]/);
  456. return "meta";
  457. },
  458. '"': function(stream, state) {
  459. if (!stream.match(/""$/)) return false;
  460. state.tokenize = tokenTripleString;
  461. return state.tokenize(stream, state);
  462. }
  463. },
  464. modeProps: {fold: ["brace", "import"]}
  465. });
  466. def("text/x-csharp", {
  467. name: "clike",
  468. keywords: words("abstract as async await base break case catch checked class const continue" +
  469. " default delegate do else enum event explicit extern finally fixed for" +
  470. " foreach goto if implicit in init interface internal is lock namespace new" +
  471. " operator out override params private protected public readonly record ref required return sealed" +
  472. " sizeof stackalloc static struct switch this throw try typeof unchecked" +
  473. " unsafe using virtual void volatile while add alias ascending descending dynamic from get" +
  474. " global group into join let orderby partial remove select set value var yield"),
  475. types: words("Action Boolean Byte Char DateTime DateTimeOffset Decimal Double Func" +
  476. " Guid Int16 Int32 Int64 Object SByte Single String Task TimeSpan UInt16 UInt32" +
  477. " UInt64 bool byte char decimal double short int long object" +
  478. " sbyte float string ushort uint ulong"),
  479. blockKeywords: words("catch class do else finally for foreach if struct switch try while"),
  480. defKeywords: words("class interface namespace record struct var"),
  481. typeFirstDefinitions: true,
  482. atoms: words("true false null"),
  483. hooks: {
  484. "@": function(stream, state) {
  485. if (stream.eat('"')) {
  486. state.tokenize = tokenAtString;
  487. return tokenAtString(stream, state);
  488. }
  489. stream.eatWhile(/[\w\$_]/);
  490. return "meta";
  491. }
  492. }
  493. });
  494. function tokenTripleString(stream, state) {
  495. var escaped = false;
  496. while (!stream.eol()) {
  497. if (!escaped && stream.match('"""')) {
  498. state.tokenize = null;
  499. break;
  500. }
  501. escaped = stream.next() == "\\" && !escaped;
  502. }
  503. return "string";
  504. }
  505. function tokenNestedComment(depth) {
  506. return function (stream, state) {
  507. var ch
  508. while (ch = stream.next()) {
  509. if (ch == "*" && stream.eat("/")) {
  510. if (depth == 1) {
  511. state.tokenize = null
  512. break
  513. } else {
  514. state.tokenize = tokenNestedComment(depth - 1)
  515. return state.tokenize(stream, state)
  516. }
  517. } else if (ch == "/" && stream.eat("*")) {
  518. state.tokenize = tokenNestedComment(depth + 1)
  519. return state.tokenize(stream, state)
  520. }
  521. }
  522. return "comment"
  523. }
  524. }
  525. def("text/x-scala", {
  526. name: "clike",
  527. keywords: words(
  528. /* scala */
  529. "abstract case catch class def do else extends final finally for forSome if " +
  530. "implicit import lazy match new null object override package private protected return " +
  531. "sealed super this throw trait try type val var while with yield _ " +
  532. /* package scala */
  533. "assert assume require print println printf readLine readBoolean readByte readShort " +
  534. "readChar readInt readLong readFloat readDouble"
  535. ),
  536. types: words(
  537. "AnyVal App Application Array BufferedIterator BigDecimal BigInt Char Console Either " +
  538. "Enumeration Equiv Error Exception Fractional Function IndexedSeq Int Integral Iterable " +
  539. "Iterator List Map Numeric Nil NotNull Option Ordered Ordering PartialFunction PartialOrdering " +
  540. "Product Proxy Range Responder Seq Serializable Set Specializable Stream StringBuilder " +
  541. "StringContext Symbol Throwable Traversable TraversableOnce Tuple Unit Vector " +
  542. /* package java.lang */
  543. "Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable " +
  544. "Compiler Double Exception Float Integer Long Math Number Object Package Pair Process " +
  545. "Runtime Runnable SecurityManager Short StackTraceElement StrictMath String " +
  546. "StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void"
  547. ),
  548. multiLineStrings: true,
  549. blockKeywords: words("catch class enum do else finally for forSome if match switch try while"),
  550. defKeywords: words("class enum def object package trait type val var"),
  551. atoms: words("true false null"),
  552. indentStatements: false,
  553. indentSwitch: false,
  554. isOperatorChar: /[+\-*&%=<>!?|\/#:@]/,
  555. hooks: {
  556. "@": function(stream) {
  557. stream.eatWhile(/[\w\$_]/);
  558. return "meta";
  559. },
  560. '"': function(stream, state) {
  561. if (!stream.match('""')) return false;
  562. state.tokenize = tokenTripleString;
  563. return state.tokenize(stream, state);
  564. },
  565. "'": function(stream) {
  566. if (stream.match(/^(\\[^'\s]+|[^\\'])'/)) return "string-2"
  567. stream.eatWhile(/[\w\$_\xa1-\uffff]/);
  568. return "atom";
  569. },
  570. "=": function(stream, state) {
  571. var cx = state.context
  572. if (cx.type == "}" && cx.align && stream.eat(">")) {
  573. state.context = new Context(cx.indented, cx.column, cx.type, cx.info, null, cx.prev)
  574. return "operator"
  575. } else {
  576. return false
  577. }
  578. },
  579. "/": function(stream, state) {
  580. if (!stream.eat("*")) return false
  581. state.tokenize = tokenNestedComment(1)
  582. return state.tokenize(stream, state)
  583. }
  584. },
  585. modeProps: {closeBrackets: {pairs: '()[]{}""', triples: '"'}}
  586. });
  587. function tokenKotlinString(tripleString){
  588. return function (stream, state) {
  589. var escaped = false, next, end = false;
  590. while (!stream.eol()) {
  591. if (!tripleString && !escaped && stream.match('"') ) {end = true; break;}
  592. if (tripleString && stream.match('"""')) {end = true; break;}
  593. next = stream.next();
  594. if(!escaped && next == "$" && stream.match('{'))
  595. stream.skipTo("}");
  596. escaped = !escaped && next == "\\" && !tripleString;
  597. }
  598. if (end || !tripleString)
  599. state.tokenize = null;
  600. return "string";
  601. }
  602. }
  603. def("text/x-kotlin", {
  604. name: "clike",
  605. keywords: words(
  606. /*keywords*/
  607. "package as typealias class interface this super val operator " +
  608. "var fun for is in This throw return annotation " +
  609. "break continue object if else while do try when !in !is as? " +
  610. /*soft keywords*/
  611. "file import where by get set abstract enum open inner override private public internal " +
  612. "protected catch finally out final vararg reified dynamic companion constructor init " +
  613. "sealed field property receiver param sparam lateinit data inline noinline tailrec " +
  614. "external annotation crossinline const operator infix suspend actual expect setparam value"
  615. ),
  616. types: words(
  617. /* package java.lang */
  618. "Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable " +
  619. "Compiler Double Exception Float Integer Long Math Number Object Package Pair Process " +
  620. "Runtime Runnable SecurityManager Short StackTraceElement StrictMath String " +
  621. "StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void Annotation Any BooleanArray " +
  622. "ByteArray Char CharArray DeprecationLevel DoubleArray Enum FloatArray Function Int IntArray Lazy " +
  623. "LazyThreadSafetyMode LongArray Nothing ShortArray Unit"
  624. ),
  625. intendSwitch: false,
  626. indentStatements: false,
  627. multiLineStrings: true,
  628. number: /^(?:0x[a-f\d_]+|0b[01_]+|(?:[\d_]+(\.\d+)?|\.\d+)(?:e[-+]?[\d_]+)?)(u|ll?|l|f)?/i,
  629. blockKeywords: words("catch class do else finally for if where try while enum"),
  630. defKeywords: words("class val var object interface fun"),
  631. atoms: words("true false null this"),
  632. hooks: {
  633. "@": function(stream) {
  634. stream.eatWhile(/[\w\$_]/);
  635. return "meta";
  636. },
  637. '*': function(_stream, state) {
  638. return state.prevToken == '.' ? 'variable' : 'operator';
  639. },
  640. '"': function(stream, state) {
  641. state.tokenize = tokenKotlinString(stream.match('""'));
  642. return state.tokenize(stream, state);
  643. },
  644. "/": function(stream, state) {
  645. if (!stream.eat("*")) return false;
  646. state.tokenize = tokenNestedComment(1);
  647. return state.tokenize(stream, state)
  648. },
  649. indent: function(state, ctx, textAfter, indentUnit) {
  650. var firstChar = textAfter && textAfter.charAt(0);
  651. if ((state.prevToken == "}" || state.prevToken == ")") && textAfter == "")
  652. return state.indented;
  653. if ((state.prevToken == "operator" && textAfter != "}" && state.context.type != "}") ||
  654. state.prevToken == "variable" && firstChar == "." ||
  655. (state.prevToken == "}" || state.prevToken == ")") && firstChar == ".")
  656. return indentUnit * 2 + ctx.indented;
  657. if (ctx.align && ctx.type == "}")
  658. return ctx.indented + (state.context.type == (textAfter || "").charAt(0) ? 0 : indentUnit);
  659. }
  660. },
  661. modeProps: {closeBrackets: {triples: '"'}}
  662. });
  663. def(["x-shader/x-vertex", "x-shader/x-fragment"], {
  664. name: "clike",
  665. keywords: words("sampler1D sampler2D sampler3D samplerCube " +
  666. "sampler1DShadow sampler2DShadow " +
  667. "const attribute uniform varying " +
  668. "break continue discard return " +
  669. "for while do if else struct " +
  670. "in out inout"),
  671. types: words("float int bool void " +
  672. "vec2 vec3 vec4 ivec2 ivec3 ivec4 bvec2 bvec3 bvec4 " +
  673. "mat2 mat3 mat4"),
  674. blockKeywords: words("for while do if else struct"),
  675. builtin: words("radians degrees sin cos tan asin acos atan " +
  676. "pow exp log exp2 sqrt inversesqrt " +
  677. "abs sign floor ceil fract mod min max clamp mix step smoothstep " +
  678. "length distance dot cross normalize ftransform faceforward " +
  679. "reflect refract matrixCompMult " +
  680. "lessThan lessThanEqual greaterThan greaterThanEqual " +
  681. "equal notEqual any all not " +
  682. "texture1D texture1DProj texture1DLod texture1DProjLod " +
  683. "texture2D texture2DProj texture2DLod texture2DProjLod " +
  684. "texture3D texture3DProj texture3DLod texture3DProjLod " +
  685. "textureCube textureCubeLod " +
  686. "shadow1D shadow2D shadow1DProj shadow2DProj " +
  687. "shadow1DLod shadow2DLod shadow1DProjLod shadow2DProjLod " +
  688. "dFdx dFdy fwidth " +
  689. "noise1 noise2 noise3 noise4"),
  690. atoms: words("true false " +
  691. "gl_FragColor gl_SecondaryColor gl_Normal gl_Vertex " +
  692. "gl_MultiTexCoord0 gl_MultiTexCoord1 gl_MultiTexCoord2 gl_MultiTexCoord3 " +
  693. "gl_MultiTexCoord4 gl_MultiTexCoord5 gl_MultiTexCoord6 gl_MultiTexCoord7 " +
  694. "gl_FogCoord gl_PointCoord " +
  695. "gl_Position gl_PointSize gl_ClipVertex " +
  696. "gl_FrontColor gl_BackColor gl_FrontSecondaryColor gl_BackSecondaryColor " +
  697. "gl_TexCoord gl_FogFragCoord " +
  698. "gl_FragCoord gl_FrontFacing " +
  699. "gl_FragData gl_FragDepth " +
  700. "gl_ModelViewMatrix gl_ProjectionMatrix gl_ModelViewProjectionMatrix " +
  701. "gl_TextureMatrix gl_NormalMatrix gl_ModelViewMatrixInverse " +
  702. "gl_ProjectionMatrixInverse gl_ModelViewProjectionMatrixInverse " +
  703. "gl_TextureMatrixTranspose gl_ModelViewMatrixInverseTranspose " +
  704. "gl_ProjectionMatrixInverseTranspose " +
  705. "gl_ModelViewProjectionMatrixInverseTranspose " +
  706. "gl_TextureMatrixInverseTranspose " +
  707. "gl_NormalScale gl_DepthRange gl_ClipPlane " +
  708. "gl_Point gl_FrontMaterial gl_BackMaterial gl_LightSource gl_LightModel " +
  709. "gl_FrontLightModelProduct gl_BackLightModelProduct " +
  710. "gl_TextureColor gl_EyePlaneS gl_EyePlaneT gl_EyePlaneR gl_EyePlaneQ " +
  711. "gl_FogParameters " +
  712. "gl_MaxLights gl_MaxClipPlanes gl_MaxTextureUnits gl_MaxTextureCoords " +
  713. "gl_MaxVertexAttribs gl_MaxVertexUniformComponents gl_MaxVaryingFloats " +
  714. "gl_MaxVertexTextureImageUnits gl_MaxTextureImageUnits " +
  715. "gl_MaxFragmentUniformComponents gl_MaxCombineTextureImageUnits " +
  716. "gl_MaxDrawBuffers"),
  717. indentSwitch: false,
  718. hooks: {"#": cppHook},
  719. modeProps: {fold: ["brace", "include"]}
  720. });
  721. def("text/x-nesc", {
  722. name: "clike",
  723. keywords: words(cKeywords + " as atomic async call command component components configuration event generic " +
  724. "implementation includes interface module new norace nx_struct nx_union post provides " +
  725. "signal task uses abstract extends"),
  726. types: cTypes,
  727. blockKeywords: words(cBlockKeywords),
  728. atoms: words("null true false"),
  729. hooks: {"#": cppHook},
  730. modeProps: {fold: ["brace", "include"]}
  731. });
  732. def("text/x-objectivec", {
  733. name: "clike",
  734. keywords: words(cKeywords + " " + objCKeywords),
  735. types: objCTypes,
  736. builtin: words(objCBuiltins),
  737. blockKeywords: words(cBlockKeywords + " @synthesize @try @catch @finally @autoreleasepool @synchronized"),
  738. defKeywords: words(cDefKeywords + " @interface @implementation @protocol @class"),
  739. dontIndentStatements: /^@.*$/,
  740. typeFirstDefinitions: true,
  741. atoms: words("YES NO NULL Nil nil true false nullptr"),
  742. isReservedIdentifier: cIsReservedIdentifier,
  743. hooks: {
  744. "#": cppHook,
  745. "*": pointerHook,
  746. },
  747. modeProps: {fold: ["brace", "include"]}
  748. });
  749. def("text/x-objectivec++", {
  750. name: "clike",
  751. keywords: words(cKeywords + " " + objCKeywords + " " + cppKeywords),
  752. types: objCTypes,
  753. builtin: words(objCBuiltins),
  754. blockKeywords: words(cBlockKeywords + " @synthesize @try @catch @finally @autoreleasepool @synchronized class try catch"),
  755. defKeywords: words(cDefKeywords + " @interface @implementation @protocol @class class namespace"),
  756. dontIndentStatements: /^@.*$|^template$/,
  757. typeFirstDefinitions: true,
  758. atoms: words("YES NO NULL Nil nil true false nullptr"),
  759. isReservedIdentifier: cIsReservedIdentifier,
  760. hooks: {
  761. "#": cppHook,
  762. "*": pointerHook,
  763. "u": cpp11StringHook,
  764. "U": cpp11StringHook,
  765. "L": cpp11StringHook,
  766. "R": cpp11StringHook,
  767. "0": cpp14Literal,
  768. "1": cpp14Literal,
  769. "2": cpp14Literal,
  770. "3": cpp14Literal,
  771. "4": cpp14Literal,
  772. "5": cpp14Literal,
  773. "6": cpp14Literal,
  774. "7": cpp14Literal,
  775. "8": cpp14Literal,
  776. "9": cpp14Literal,
  777. token: function(stream, state, style) {
  778. if (style == "variable" && stream.peek() == "(" &&
  779. (state.prevToken == ";" || state.prevToken == null ||
  780. state.prevToken == "}") &&
  781. cppLooksLikeConstructor(stream.current()))
  782. return "def";
  783. }
  784. },
  785. namespaceSeparator: "::",
  786. modeProps: {fold: ["brace", "include"]}
  787. });
  788. def("text/x-squirrel", {
  789. name: "clike",
  790. keywords: words("base break clone continue const default delete enum extends function in class" +
  791. " foreach local resume return this throw typeof yield constructor instanceof static"),
  792. types: cTypes,
  793. blockKeywords: words("case catch class else for foreach if switch try while"),
  794. defKeywords: words("function local class"),
  795. typeFirstDefinitions: true,
  796. atoms: words("true false null"),
  797. hooks: {"#": cppHook},
  798. modeProps: {fold: ["brace", "include"]}
  799. });
  800. // Ceylon Strings need to deal with interpolation
  801. var stringTokenizer = null;
  802. function tokenCeylonString(type) {
  803. return function(stream, state) {
  804. var escaped = false, next, end = false;
  805. while (!stream.eol()) {
  806. if (!escaped && stream.match('"') &&
  807. (type == "single" || stream.match('""'))) {
  808. end = true;
  809. break;
  810. }
  811. if (!escaped && stream.match('``')) {
  812. stringTokenizer = tokenCeylonString(type);
  813. end = true;
  814. break;
  815. }
  816. next = stream.next();
  817. escaped = type == "single" && !escaped && next == "\\";
  818. }
  819. if (end)
  820. state.tokenize = null;
  821. return "string";
  822. }
  823. }
  824. def("text/x-ceylon", {
  825. name: "clike",
  826. keywords: words("abstracts alias assembly assert assign break case catch class continue dynamic else" +
  827. " exists extends finally for function given if import in interface is let module new" +
  828. " nonempty object of out outer package return satisfies super switch then this throw" +
  829. " try value void while"),
  830. types: function(word) {
  831. // In Ceylon all identifiers that start with an uppercase are types
  832. var first = word.charAt(0);
  833. return (first === first.toUpperCase() && first !== first.toLowerCase());
  834. },
  835. blockKeywords: words("case catch class dynamic else finally for function if interface module new object switch try while"),
  836. defKeywords: words("class dynamic function interface module object package value"),
  837. builtin: words("abstract actual aliased annotation by default deprecated doc final formal late license" +
  838. " native optional sealed see serializable shared suppressWarnings tagged throws variable"),
  839. isPunctuationChar: /[\[\]{}\(\),;\:\.`]/,
  840. isOperatorChar: /[+\-*&%=<>!?|^~:\/]/,
  841. numberStart: /[\d#$]/,
  842. number: /^(?:#[\da-fA-F_]+|\$[01_]+|[\d_]+[kMGTPmunpf]?|[\d_]+\.[\d_]+(?:[eE][-+]?\d+|[kMGTPmunpf]|)|)/i,
  843. multiLineStrings: true,
  844. typeFirstDefinitions: true,
  845. atoms: words("true false null larger smaller equal empty finished"),
  846. indentSwitch: false,
  847. styleDefs: false,
  848. hooks: {
  849. "@": function(stream) {
  850. stream.eatWhile(/[\w\$_]/);
  851. return "meta";
  852. },
  853. '"': function(stream, state) {
  854. state.tokenize = tokenCeylonString(stream.match('""') ? "triple" : "single");
  855. return state.tokenize(stream, state);
  856. },
  857. '`': function(stream, state) {
  858. if (!stringTokenizer || !stream.match('`')) return false;
  859. state.tokenize = stringTokenizer;
  860. stringTokenizer = null;
  861. return state.tokenize(stream, state);
  862. },
  863. "'": function(stream) {
  864. stream.eatWhile(/[\w\$_\xa1-\uffff]/);
  865. return "atom";
  866. },
  867. token: function(_stream, state, style) {
  868. if ((style == "variable" || style == "type") &&
  869. state.prevToken == ".") {
  870. return "variable-2";
  871. }
  872. }
  873. },
  874. modeProps: {
  875. fold: ["brace", "import"],
  876. closeBrackets: {triples: '"'}
  877. }
  878. });
  879. });