本站源代码
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.

890 lines
35KB

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