markdown.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. CodeMirror.defineMode("markdown", function(cmCfg, modeCfg) {
  2. var htmlFound = CodeMirror.modes.hasOwnProperty("xml");
  3. var htmlMode = CodeMirror.getMode(cmCfg, htmlFound ? {name: "xml", htmlMode: true} : "text/plain");
  4. var aliases = {
  5. html: "htmlmixed",
  6. js: "javascript",
  7. json: "application/json",
  8. c: "text/x-csrc",
  9. "c++": "text/x-c++src",
  10. java: "text/x-java",
  11. csharp: "text/x-csharp",
  12. "c#": "text/x-csharp",
  13. scala: "text/x-scala"
  14. };
  15. var getMode = (function () {
  16. var i, modes = {}, mimes = {}, mime;
  17. var list = [];
  18. for (var m in CodeMirror.modes)
  19. if (CodeMirror.modes.propertyIsEnumerable(m)) list.push(m);
  20. for (i = 0; i < list.length; i++) {
  21. modes[list[i]] = list[i];
  22. }
  23. var mimesList = [];
  24. for (var m in CodeMirror.mimeModes)
  25. if (CodeMirror.mimeModes.propertyIsEnumerable(m))
  26. mimesList.push({mime: m, mode: CodeMirror.mimeModes[m]});
  27. for (i = 0; i < mimesList.length; i++) {
  28. mime = mimesList[i].mime;
  29. mimes[mime] = mimesList[i].mime;
  30. }
  31. for (var a in aliases) {
  32. if (aliases[a] in modes || aliases[a] in mimes)
  33. modes[a] = aliases[a];
  34. }
  35. return function (lang) {
  36. return modes[lang] ? CodeMirror.getMode(cmCfg, modes[lang]) : null;
  37. };
  38. }());
  39. // Should underscores in words open/close em/strong?
  40. if (modeCfg.underscoresBreakWords === undefined)
  41. modeCfg.underscoresBreakWords = true;
  42. // Turn on fenced code blocks? ("```" to start/end)
  43. if (modeCfg.fencedCodeBlocks === undefined) modeCfg.fencedCodeBlocks = false;
  44. // Turn on task lists? ("- [ ] " and "- [x] ")
  45. if (modeCfg.taskLists === undefined) modeCfg.taskLists = false;
  46. var codeDepth = 0;
  47. var header = 'header'
  48. , code = 'comment'
  49. , quote1 = 'atom'
  50. , quote2 = 'number'
  51. , list1 = 'variable-2'
  52. , list2 = 'variable-3'
  53. , list3 = 'keyword'
  54. , hr = 'hr'
  55. , image = 'tag'
  56. , linkinline = 'link'
  57. , linkemail = 'link'
  58. , linktext = 'link'
  59. , linkhref = 'string'
  60. , em = 'em'
  61. , strong = 'strong';
  62. var hrRE = /^([*\-=_])(?:\s*\1){2,}\s*$/
  63. , ulRE = /^[*\-+]\s+/
  64. , olRE = /^[0-9]+\.\s+/
  65. , taskListRE = /^\[(x| )\](?=\s)/ // Must follow ulRE or olRE
  66. , headerRE = /^(?:\={1,}|-{1,})$/
  67. , textRE = /^[^!\[\]*_\\<>` "'(]+/;
  68. function switchInline(stream, state, f) {
  69. state.f = state.inline = f;
  70. return f(stream, state);
  71. }
  72. function switchBlock(stream, state, f) {
  73. state.f = state.block = f;
  74. return f(stream, state);
  75. }
  76. // Blocks
  77. function blankLine(state) {
  78. // Reset linkTitle state
  79. state.linkTitle = false;
  80. // Reset EM state
  81. state.em = false;
  82. // Reset STRONG state
  83. state.strong = false;
  84. // Reset state.quote
  85. state.quote = 0;
  86. if (!htmlFound && state.f == htmlBlock) {
  87. state.f = inlineNormal;
  88. state.block = blockNormal;
  89. }
  90. // Mark this line as blank
  91. state.thisLineHasContent = false;
  92. return null;
  93. }
  94. function blockNormal(stream, state) {
  95. var prevLineIsList = (state.list !== false);
  96. if (state.list !== false && state.indentationDiff >= 0) { // Continued list
  97. if (state.indentationDiff < 4) { // Only adjust indentation if *not* a code block
  98. state.indentation -= state.indentationDiff;
  99. }
  100. state.list = null;
  101. } else if (state.list !== false && state.indentation > 0) {
  102. state.list = null;
  103. state.listDepth = Math.floor(state.indentation / 4);
  104. } else if (state.list !== false) { // No longer a list
  105. state.list = false;
  106. state.listDepth = 0;
  107. }
  108. if (state.indentationDiff >= 4) {
  109. state.indentation -= 4;
  110. stream.skipToEnd();
  111. return code;
  112. } else if (stream.eatSpace()) {
  113. return null;
  114. } else if (stream.peek() === '#' || (state.prevLineHasContent && stream.match(headerRE)) ) {
  115. state.header = true;
  116. } else if (stream.eat('>')) {
  117. state.indentation++;
  118. state.quote = 1;
  119. stream.eatSpace();
  120. while (stream.eat('>')) {
  121. stream.eatSpace();
  122. state.quote++;
  123. }
  124. } else if (stream.peek() === '[') {
  125. return switchInline(stream, state, footnoteLink);
  126. } else if (stream.match(hrRE, true)) {
  127. return hr;
  128. } else if ((!state.prevLineHasContent || prevLineIsList) && (stream.match(ulRE, true) || stream.match(olRE, true))) {
  129. state.indentation += 4;
  130. state.list = true;
  131. state.listDepth++;
  132. if (modeCfg.taskLists && stream.match(taskListRE, false)) {
  133. state.taskList = true;
  134. }
  135. } else if (modeCfg.fencedCodeBlocks && stream.match(/^```([\w+#]*)/, true)) {
  136. // try switching mode
  137. state.localMode = getMode(RegExp.$1);
  138. if (state.localMode) state.localState = state.localMode.startState();
  139. switchBlock(stream, state, local);
  140. return code;
  141. }
  142. return switchInline(stream, state, state.inline);
  143. }
  144. function htmlBlock(stream, state) {
  145. var style = htmlMode.token(stream, state.htmlState);
  146. if (htmlFound && style === 'tag' && state.htmlState.type !== 'openTag' && !state.htmlState.context) {
  147. state.f = inlineNormal;
  148. state.block = blockNormal;
  149. }
  150. if (state.md_inside && stream.current().indexOf(">")!=-1) {
  151. state.f = inlineNormal;
  152. state.block = blockNormal;
  153. state.htmlState.context = undefined;
  154. }
  155. return style;
  156. }
  157. function local(stream, state) {
  158. if (stream.sol() && stream.match(/^```/, true)) {
  159. state.localMode = state.localState = null;
  160. state.f = inlineNormal;
  161. state.block = blockNormal;
  162. return code;
  163. } else if (state.localMode) {
  164. return state.localMode.token(stream, state.localState);
  165. } else {
  166. stream.skipToEnd();
  167. return code;
  168. }
  169. }
  170. // Inline
  171. function getType(state) {
  172. var styles = [];
  173. if (state.taskOpen) { return "meta"; }
  174. if (state.taskClosed) { return "property"; }
  175. if (state.strong) { styles.push(strong); }
  176. if (state.em) { styles.push(em); }
  177. if (state.linkText) { styles.push(linktext); }
  178. if (state.code) { styles.push(code); }
  179. if (state.header) { styles.push(header); }
  180. if (state.quote) { styles.push(state.quote % 2 ? quote1 : quote2); }
  181. if (state.list !== false) {
  182. var listMod = (state.listDepth - 1) % 3;
  183. if (!listMod) {
  184. styles.push(list1);
  185. } else if (listMod === 1) {
  186. styles.push(list2);
  187. } else {
  188. styles.push(list3);
  189. }
  190. }
  191. return styles.length ? styles.join(' ') : null;
  192. }
  193. function handleText(stream, state) {
  194. if (stream.match(textRE, true)) {
  195. return getType(state);
  196. }
  197. return undefined;
  198. }
  199. function inlineNormal(stream, state) {
  200. var style = state.text(stream, state);
  201. if (typeof style !== 'undefined')
  202. return style;
  203. if (state.list) { // List marker (*, +, -, 1., etc)
  204. state.list = null;
  205. return getType(state);
  206. }
  207. if (state.taskList) {
  208. var taskOpen = stream.match(taskListRE, true)[1] !== "x";
  209. if (taskOpen) state.taskOpen = true;
  210. else state.taskClosed = true;
  211. state.taskList = false;
  212. return getType(state);
  213. }
  214. state.taskOpen = false;
  215. state.taskClosed = false;
  216. var ch = stream.next();
  217. if (ch === '\\') {
  218. stream.next();
  219. return getType(state);
  220. }
  221. // Matches link titles present on next line
  222. if (state.linkTitle) {
  223. state.linkTitle = false;
  224. var matchCh = ch;
  225. if (ch === '(') {
  226. matchCh = ')';
  227. }
  228. matchCh = (matchCh+'').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
  229. var regex = '^\\s*(?:[^' + matchCh + '\\\\]+|\\\\\\\\|\\\\.)' + matchCh;
  230. if (stream.match(new RegExp(regex), true)) {
  231. return linkhref;
  232. }
  233. }
  234. // If this block is changed, it may need to be updated in GFM mode
  235. if (ch === '`') {
  236. var t = getType(state);
  237. var before = stream.pos;
  238. stream.eatWhile('`');
  239. var difference = 1 + stream.pos - before;
  240. if (!state.code) {
  241. codeDepth = difference;
  242. state.code = true;
  243. return getType(state);
  244. } else {
  245. if (difference === codeDepth) { // Must be exact
  246. state.code = false;
  247. return t;
  248. }
  249. return getType(state);
  250. }
  251. } else if (state.code) {
  252. return getType(state);
  253. }
  254. if (ch === '!' && stream.match(/\[[^\]]*\] ?(?:\(|\[)/, false)) {
  255. stream.match(/\[[^\]]*\]/);
  256. state.inline = state.f = linkHref;
  257. return image;
  258. }
  259. if (ch === '[' && stream.match(/.*\](\(| ?\[)/, false)) {
  260. state.linkText = true;
  261. return getType(state);
  262. }
  263. if (ch === ']' && state.linkText) {
  264. var type = getType(state);
  265. state.linkText = false;
  266. state.inline = state.f = linkHref;
  267. return type;
  268. }
  269. if (ch === '<' && stream.match(/^(https?|ftps?):\/\/(?:[^\\>]|\\.)+>/, true)) {
  270. return switchInline(stream, state, inlineElement(linkinline, '>'));
  271. }
  272. if (ch === '<' && stream.match(/^[^> \\]+@(?:[^\\>]|\\.)+>/, true)) {
  273. return switchInline(stream, state, inlineElement(linkemail, '>'));
  274. }
  275. if (ch === '<' && stream.match(/^\w/, false)) {
  276. if (stream.string.indexOf(">")!=-1) {
  277. var atts = stream.string.substring(1,stream.string.indexOf(">"));
  278. if (/markdown\s*=\s*('|"){0,1}1('|"){0,1}/.test(atts)) {
  279. state.md_inside = true;
  280. }
  281. }
  282. stream.backUp(1);
  283. return switchBlock(stream, state, htmlBlock);
  284. }
  285. if (ch === '<' && stream.match(/^\/\w*?>/)) {
  286. state.md_inside = false;
  287. return "tag";
  288. }
  289. var ignoreUnderscore = false;
  290. if (!modeCfg.underscoresBreakWords) {
  291. if (ch === '_' && stream.peek() !== '_' && stream.match(/(\w)/, false)) {
  292. var prevPos = stream.pos - 2;
  293. if (prevPos >= 0) {
  294. var prevCh = stream.string.charAt(prevPos);
  295. if (prevCh !== '_' && prevCh.match(/(\w)/, false)) {
  296. ignoreUnderscore = true;
  297. }
  298. }
  299. }
  300. }
  301. var t = getType(state);
  302. if (ch === '*' || (ch === '_' && !ignoreUnderscore)) {
  303. if (state.strong === ch && stream.eat(ch)) { // Remove STRONG
  304. state.strong = false;
  305. return t;
  306. } else if (!state.strong && stream.eat(ch)) { // Add STRONG
  307. state.strong = ch;
  308. return getType(state);
  309. } else if (state.em === ch) { // Remove EM
  310. state.em = false;
  311. return t;
  312. } else if (!state.em) { // Add EM
  313. state.em = ch;
  314. return getType(state);
  315. }
  316. } else if (ch === ' ') {
  317. if (stream.eat('*') || stream.eat('_')) { // Probably surrounded by spaces
  318. if (stream.peek() === ' ') { // Surrounded by spaces, ignore
  319. return getType(state);
  320. } else { // Not surrounded by spaces, back up pointer
  321. stream.backUp(1);
  322. }
  323. }
  324. }
  325. return getType(state);
  326. }
  327. function linkHref(stream, state) {
  328. // Check if space, and return NULL if so (to avoid marking the space)
  329. if(stream.eatSpace()){
  330. return null;
  331. }
  332. var ch = stream.next();
  333. if (ch === '(' || ch === '[') {
  334. return switchInline(stream, state, inlineElement(linkhref, ch === '(' ? ')' : ']'));
  335. }
  336. return 'error';
  337. }
  338. function footnoteLink(stream, state) {
  339. if (stream.match(/^[^\]]*\]:/, true)) {
  340. state.f = footnoteUrl;
  341. return linktext;
  342. }
  343. return switchInline(stream, state, inlineNormal);
  344. }
  345. function footnoteUrl(stream, state) {
  346. // Check if space, and return NULL if so (to avoid marking the space)
  347. if(stream.eatSpace()){
  348. return null;
  349. }
  350. // Match URL
  351. stream.match(/^[^\s]+/, true);
  352. // Check for link title
  353. if (stream.peek() === undefined) { // End of line, set flag to check next line
  354. state.linkTitle = true;
  355. } else { // More content on line, check if link title
  356. stream.match(/^(?:\s+(?:"(?:[^"\\]|\\\\|\\.)+"|'(?:[^'\\]|\\\\|\\.)+'|\((?:[^)\\]|\\\\|\\.)+\)))?/, true);
  357. }
  358. state.f = state.inline = inlineNormal;
  359. return linkhref;
  360. }
  361. var savedInlineRE = [];
  362. function inlineRE(endChar) {
  363. if (!savedInlineRE[endChar]) {
  364. // Escape endChar for RegExp (taken from http://stackoverflow.com/a/494122/526741)
  365. endChar = (endChar+'').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
  366. // Match any non-endChar, escaped character, as well as the closing
  367. // endChar.
  368. savedInlineRE[endChar] = new RegExp('^(?:[^\\\\]|\\\\.)*?(' + endChar + ')');
  369. }
  370. return savedInlineRE[endChar];
  371. }
  372. function inlineElement(type, endChar, next) {
  373. next = next || inlineNormal;
  374. return function(stream, state) {
  375. stream.match(inlineRE(endChar));
  376. state.inline = state.f = next;
  377. return type;
  378. };
  379. }
  380. return {
  381. startState: function() {
  382. return {
  383. f: blockNormal,
  384. prevLineHasContent: false,
  385. thisLineHasContent: false,
  386. block: blockNormal,
  387. htmlState: CodeMirror.startState(htmlMode),
  388. indentation: 0,
  389. inline: inlineNormal,
  390. text: handleText,
  391. linkText: false,
  392. linkTitle: false,
  393. em: false,
  394. strong: false,
  395. header: false,
  396. taskList: false,
  397. list: false,
  398. listDepth: 0,
  399. quote: 0
  400. };
  401. },
  402. copyState: function(s) {
  403. return {
  404. f: s.f,
  405. prevLineHasContent: s.prevLineHasContent,
  406. thisLineHasContent: s.thisLineHasContent,
  407. block: s.block,
  408. htmlState: CodeMirror.copyState(htmlMode, s.htmlState),
  409. indentation: s.indentation,
  410. localMode: s.localMode,
  411. localState: s.localMode ? CodeMirror.copyState(s.localMode, s.localState) : null,
  412. inline: s.inline,
  413. text: s.text,
  414. linkTitle: s.linkTitle,
  415. em: s.em,
  416. strong: s.strong,
  417. header: s.header,
  418. taskList: s.taskList,
  419. list: s.list,
  420. listDepth: s.listDepth,
  421. quote: s.quote,
  422. md_inside: s.md_inside
  423. };
  424. },
  425. token: function(stream, state) {
  426. if (stream.sol()) {
  427. if (stream.match(/^\s*$/, true)) {
  428. state.prevLineHasContent = false;
  429. return blankLine(state);
  430. } else {
  431. state.prevLineHasContent = state.thisLineHasContent;
  432. state.thisLineHasContent = true;
  433. }
  434. // Reset state.header
  435. state.header = false;
  436. // Reset state.taskList
  437. state.taskList = false;
  438. // Reset state.code
  439. state.code = false;
  440. state.f = state.block;
  441. var indentation = stream.match(/^\s*/, true)[0].replace(/\t/g, ' ').length;
  442. var difference = Math.floor((indentation - state.indentation) / 4) * 4;
  443. if (difference > 4) difference = 4;
  444. var adjustedIndentation = state.indentation + difference;
  445. state.indentationDiff = adjustedIndentation - state.indentation;
  446. state.indentation = adjustedIndentation;
  447. if (indentation > 0) return null;
  448. }
  449. return state.f(stream, state);
  450. },
  451. blankLine: blankLine,
  452. getType: getType
  453. };
  454. }, "xml");
  455. CodeMirror.defineMIME("text/x-markdown", "markdown");