ReformMarkdownTableInterceptor.js 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. import { BasicInterceptor } from 'crowi-pluginkit';
  2. import * as codemirror from 'codemirror';
  3. import markdownTable from 'markdown-table';
  4. /**
  5. * The interceptor that reform markdown table
  6. */
  7. export default class ReformMarkdownTableInterceptor extends BasicInterceptor {
  8. constructor() {
  9. super();
  10. // https://github.com/markdown-it/markdown-it/blob/d29f421927e93e88daf75f22089a3e732e195bd2/lib/rules_block/table.js#L83
  11. // https://regex101.com/r/7BN2fR/7
  12. this.tableAlignmentLineRE = /^[-:|][-:|\s]*$/;
  13. this.linePartOfTableRE = /^\|[^\r\n]*|[^\r\n]*\|$|([^\|\r\n]+\|[^\|\r\n]*)+/; // own idea
  14. this.getBot = this.getBot.bind(this);
  15. this.getEot = this.getEot.bind(this);
  16. this.getBol = this.getBol.bind(this);
  17. this.getStrFromBot = this.getStrFromBot.bind(this);
  18. this.getStrToEot = this.getStrToEot.bind(this);
  19. this.getStrFromBol = this.getStrFromBol.bind(this);
  20. this.parseFromTableStringToJSON = this.parseFromTableStringToJSON.bind(this);
  21. }
  22. /**
  23. * @inheritdoc
  24. */
  25. isInterceptWhen(contextName) {
  26. return (
  27. contextName === 'preHandleEnter'
  28. );
  29. }
  30. /**
  31. * return boolean value whether processable parallel
  32. */
  33. isProcessableParallel() {
  34. return false;
  35. }
  36. /**
  37. * @inheritdoc
  38. */
  39. process(contextName, ...args) {
  40. console.log(performance.now() + ': ReformMarkdownTableInterceptor.process is started');
  41. const orgContext = args[0];
  42. const editor = orgContext.editor;
  43. // get strings from BOL(beginning of line) to current position
  44. const strFromBol = this.getStrFromBol(editor);
  45. if (this.linePartOfTableRE.test(strFromBol)) {
  46. const context = Object.assign(args[0]); // clone
  47. const editor = context.editor;
  48. console.log('MarkdownTableHelper.process');
  49. // get lines all of table from current position to beginning of table
  50. const strTableLines = this.getStrFromBot(editor);
  51. console.log('strTableLines: ' + strTableLines);
  52. const table = this.parseFromTableStringToJSON(editor, this.getBot(editor), editor.getCursor());
  53. console.log('table: ' + JSON.stringify(table));
  54. const strTableLinesFormated = table;
  55. console.log('strTableLinesFormated: ' + strTableLinesFormated);
  56. // replace the lines to strFormatedTableLines
  57. editor.getDoc().replaceRange(strTableLinesFormated, this.getBot(editor), editor.getCursor());
  58. codemirror.commands.newlineAndIndent(editor);
  59. // report to manager that handling was done
  60. context.handlers.push(this.className);
  61. }
  62. console.log(performance.now() + ': ReformMarkdownTableInterceptor.process is finished');
  63. // resolve
  64. // return Promise.resolve(context);
  65. return Promise.resolve(orgContext);
  66. }
  67. /**
  68. * return the postion of the BOT(beginning of table)
  69. * (It is assumed that current line is a part of table)
  70. */
  71. getBot(editor) {
  72. const firstLine = editor.getDoc().firstLine();
  73. const curPos = editor.getCursor();
  74. let line = curPos.line - 1;
  75. for (; line >= firstLine; line--) {
  76. const strLine = editor.getDoc().getLine(line);
  77. if (!this.linePartOfTableRE.test(strLine)) {
  78. break;
  79. }
  80. }
  81. const botLine = Math.max(firstLine, line + 1);
  82. return { line: botLine, ch: 0 };
  83. }
  84. /**
  85. * return the postion of the EOT(end of table)
  86. * (It is assumed that current line is a part of table)
  87. */
  88. getEot(editor) {
  89. const lastLine = editor.getDoc().lastLine();
  90. const curPos = editor.getCursor();
  91. let line = curPos.line + 1;
  92. for (; line <= lastLine; line++) {
  93. const strLine = editor.getDoc().getLine(line);
  94. if (!this.linePartOfTableRE.test(strLine)) {
  95. break;
  96. }
  97. }
  98. const eotLine = Math.min(line - 1, lastLine);
  99. const lineLength = editor.getDoc().getLine(eotLine).length;
  100. return { line: eotLine, ch: lineLength };
  101. }
  102. /**
  103. * return the postion of the BOL(beginning of line)
  104. */
  105. getBol(editor) {
  106. const curPos = editor.getCursor();
  107. return { line: curPos.line, ch: 0 };
  108. }
  109. /**
  110. * return strings from BOT(beginning of table) to current position
  111. */
  112. getStrFromBot(editor) {
  113. const curPos = editor.getCursor();
  114. return editor.getDoc().getRange(this.getBot(editor), curPos);
  115. }
  116. /**
  117. * return strings from current position to EOT(end of table)
  118. */
  119. getStrToEot(editor) {
  120. const curPos = editor.getCursor();
  121. return editor.getDoc().getRange(curPos, this.getEot(editor));
  122. }
  123. /**
  124. * return strings from BOL(beginning of line) to current position
  125. */
  126. getStrFromBol(editor) {
  127. const curPos = editor.getCursor();
  128. return editor.getDoc().getRange(this.getBol(editor), curPos);
  129. }
  130. /**
  131. * returns object whose described by 'markdown-table' format
  132. * ref. https://github.com/wooorm/markdown-table
  133. * @param {string} lines all of table
  134. */
  135. parseFromTableStringToJSON(editor, posBeg, posEnd) {
  136. console.log("parseFromTableStringToJSON: posBeg.line: " + posBeg.line + ", posEnd.line: " + posEnd.line);
  137. let contents = [];
  138. let aligns = [];
  139. for (let pos = posBeg; pos.line <= posEnd.line; pos.line++) {
  140. const line = editor.getDoc().getLine(pos.line);
  141. console.log("line#" + pos.line + ": " + line);
  142. if (this.tableAlignmentLineRE.test(line)) {
  143. // parse line which described alignment
  144. const alignRuleRE = [
  145. { align: 'c', regex: /^:-+:$/ },
  146. { align: 'l', regex: /^:-+$/ },
  147. { align: 'r', regex: /^-+:$/ },
  148. ];
  149. let lineText = "";
  150. lineText = line.replace(/^\||\|$/g, ''); // strip off pipe charactor which is placed head of line and last of line.
  151. lineText = lineText.replace(/\s*/g, '');
  152. aligns = lineText.split(/\|/).map(col => {
  153. const rule = alignRuleRE.find(rule => col.match(rule.regex));
  154. return (rule != undefined) ? rule.align : '';
  155. });
  156. } else {
  157. // parse line whether header or body
  158. let lineText = "";
  159. lineText = line.replace(/\s*\|\s*/g, '|');
  160. lineText = lineText.replace(/^\||\|$/g, ''); // strip off pipe charactor which is placed head of line and last of line.
  161. const row = lineText.split(/\|/);
  162. console.log('row: ' + row);
  163. contents.push(row);
  164. }
  165. }
  166. console.log('contents: ' + JSON.stringify(contents));
  167. console.log('aligns: ' + JSON.stringify(aligns));
  168. return markdownTable(contents, { align: aligns } );
  169. }
  170. }