MarkdownTableUtil.js 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. import markdownTable from 'markdown-table';
  2. import stringWidth from 'string-width';
  3. /**
  4. * Utility for markdown table
  5. */
  6. class MarkdownTableUtil {
  7. constructor() {
  8. // https://github.com/markdown-it/markdown-it/blob/d29f421927e93e88daf75f22089a3e732e195bd2/lib/rules_block/table.js#L83
  9. // https://regex101.com/r/7BN2fR/7
  10. this.tableAlignmentLineRE = /^[-:|][-:|\s]*$/;
  11. this.tableAlignmentLineNegRE = /^[^-:]*$/; // it is need to check to ignore empty row which is matched above RE
  12. this.linePartOfTableRE = /^\|[^\r\n]*|[^\r\n]*\|$|([^|\r\n]+\|[^|\r\n]*)+/; // own idea
  13. this.getBot = this.getBot.bind(this);
  14. this.getEot = this.getEot.bind(this);
  15. this.getBol = this.getBol.bind(this);
  16. this.getStrFromBot = this.getStrFromBot.bind(this);
  17. this.getStrToEot = this.getStrToEot.bind(this);
  18. this.parseFromTableStringToMarkdownTable = this.parseFromTableStringToMarkdownTable.bind(this);
  19. this.replaceMarkdownTableWithReformed = this.replaceMarkdownTableWithReformed.bind(this);
  20. }
  21. /**
  22. * return the postion of the BOT(beginning of table)
  23. * (It is assumed that current line is a part of table)
  24. */
  25. getBot(editor) {
  26. const firstLine = editor.getDoc().firstLine();
  27. const curPos = editor.getCursor();
  28. let line = curPos.line - 1;
  29. for (; line >= firstLine; line--) {
  30. const strLine = editor.getDoc().getLine(line);
  31. if (!this.linePartOfTableRE.test(strLine)) {
  32. break;
  33. }
  34. }
  35. const botLine = Math.max(firstLine, line + 1);
  36. return { line: botLine, ch: 0 };
  37. }
  38. /**
  39. * return the postion of the EOT(end of table)
  40. * (It is assumed that current line is a part of table)
  41. */
  42. getEot(editor) {
  43. const lastLine = editor.getDoc().lastLine();
  44. const curPos = editor.getCursor();
  45. let line = curPos.line + 1;
  46. for (; line <= lastLine; line++) {
  47. const strLine = editor.getDoc().getLine(line);
  48. if (!this.linePartOfTableRE.test(strLine)) {
  49. break;
  50. }
  51. }
  52. const eotLine = Math.min(line - 1, lastLine);
  53. const lineLength = editor.getDoc().getLine(eotLine).length;
  54. return { line: eotLine, ch: lineLength };
  55. }
  56. /**
  57. * return the postion of the BOL(beginning of line)
  58. */
  59. getBol(editor) {
  60. const curPos = editor.getCursor();
  61. return { line: curPos.line, ch: 0 };
  62. }
  63. /**
  64. * return strings from BOT(beginning of table) to current position
  65. */
  66. getStrFromBot(editor) {
  67. const curPos = editor.getCursor();
  68. return editor.getDoc().getRange(this.getBot(editor), curPos);
  69. }
  70. /**
  71. * return strings from current position to EOT(end of table)
  72. */
  73. getStrToEot(editor) {
  74. const curPos = editor.getCursor();
  75. return editor.getDoc().getRange(curPos, this.getEot(editor));
  76. }
  77. /**
  78. * returns markdown table whose described by 'markdown-table' format
  79. * ref. https://github.com/wooorm/markdown-table
  80. * @param {string} lines all of table
  81. */
  82. parseFromTableStringToMarkdownTable(strMDTable) {
  83. const arrMDTableLines = strMDTable.split(/(\r\n|\r|\n)/);
  84. let contents = [];
  85. let aligns = [];
  86. for (let n = 0; n < arrMDTableLines.length; n++) {
  87. const line = arrMDTableLines[n];
  88. if (this.tableAlignmentLineRE.test(line) && !this.tableAlignmentLineNegRE.test(line)) {
  89. // parse line which described alignment
  90. const alignRuleRE = [
  91. { align: 'c', regex: /^:-+:$/ },
  92. { align: 'l', regex: /^:-+$/ },
  93. { align: 'r', regex: /^-+:$/ },
  94. ];
  95. let lineText = '';
  96. lineText = line.replace(/^\||\|$/g, ''); // strip off pipe charactor which is placed head of line and last of line.
  97. lineText = lineText.replace(/\s*/g, '');
  98. aligns = lineText.split(/\|/).map(col => {
  99. const rule = alignRuleRE.find(rule => col.match(rule.regex));
  100. return (rule != undefined) ? rule.align : '';
  101. });
  102. }
  103. else if (this.linePartOfTableRE.test(line)) {
  104. // parse line whether header or body
  105. let lineText = '';
  106. lineText = line.replace(/\s*\|\s*/g, '|');
  107. lineText = lineText.replace(/^\||\|$/g, ''); // strip off pipe charactor which is placed head of line and last of line.
  108. const row = lineText.split(/\|/);
  109. contents.push(row);
  110. }
  111. }
  112. return (new MarkdownTable(contents, { align: aligns, stringLength: stringWidth }));
  113. }
  114. /**
  115. * return boolean value whether the current position of cursor is end of line
  116. */
  117. isEndOfLine(editor) {
  118. const curPos = editor.getCursor();
  119. return (curPos.ch == editor.getDoc().getLine(curPos.line).length);
  120. }
  121. /**
  122. * add a row at the end
  123. * (This function overwrite directory markdown table specified as argument.)
  124. * @param {MarkdownTable} markdown table
  125. */
  126. addRowToMarkdownTable(mdtable) {
  127. const numCol = mdtable.table.length > 0 ? mdtable.table[0].length : 1;
  128. let newRow = [];
  129. (new Array(numCol)).forEach(() => newRow.push('')); // create cols
  130. mdtable.table.push(newRow);
  131. }
  132. /**
  133. * returns markdown table that is merged all of markdown table in array
  134. * (The merged markdown table options are used for the first markdown table.)
  135. * @param {Array} array of markdown table
  136. */
  137. mergeMarkdownTable(mdtable_list) {
  138. if (mdtable_list == undefined
  139. || !(mdtable_list instanceof Array)) {
  140. return undefined;
  141. }
  142. let newTable = [];
  143. const options = mdtable_list[0].options; // use option of first markdown-table
  144. mdtable_list.forEach((mdtable) => {
  145. newTable = newTable.concat(mdtable.table);
  146. });
  147. return (new MarkdownTable(newTable, options));
  148. }
  149. /**
  150. * replace markdown table which is reformed by markdown-table
  151. * @param {MarkdownTable} markdown table
  152. */
  153. replaceMarkdownTableWithReformed(editor, table) {
  154. const curPos = editor.getCursor();
  155. // replace the lines to strTableLinesFormated
  156. const strTableLinesFormated = table.toString();
  157. editor.getDoc().replaceRange(strTableLinesFormated, this.getBot(editor), this.getEot(editor));
  158. // set cursor to first column
  159. editor.getDoc().setCursor(curPos.line + 1, 2);
  160. }
  161. }
  162. /**
  163. * markdown table class for markdown-table module
  164. * ref. https://github.com/wooorm/markdown-table
  165. */
  166. class MarkdownTable {
  167. constructor(table, options) {
  168. this.table = table || [];
  169. this.options = options || {};
  170. this.toString = this.toString.bind(this);
  171. }
  172. toString() {
  173. return markdownTable(this.table, this.options);
  174. }
  175. }
  176. // singleton pattern
  177. const instance = new MarkdownTableUtil();
  178. Object.freeze(instance);
  179. export default instance;