clike.js 32 KB

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