snow-editor

small markdown and org-mode editor
Log | Files | Refs | README

editorUtils.js (1216B)


      1 const CHECKLIST_RE = /^(\s*)([-+*])\s+\[([ Xx\-])\](.*)$/;
      2 const HEADING_RE = /^(\*+)\s+(.*)$/;
      3 
      4 export function isChecklistLine(line) {
      5   return CHECKLIST_RE.test(line);
      6 }
      7 
      8 export function toggleChecklistLine(line) {
      9   const match = line.match(CHECKLIST_RE);
     10   if (!match) return line;
     11 
     12   const [, indent, bullet, state, rest] = match;
     13   const nextState = state === 'X' || state === 'x' ? ' ' : 'X';
     14   return `${indent}${bullet} [${nextState}]${rest}`;
     15 }
     16 
     17 export function adjustHeading(line, delta) {
     18   const match = line.match(HEADING_RE);
     19   if (!match) return line;
     20 
     21   const nextLevel = match[1].length + delta;
     22   if (nextLevel < 1 || nextLevel > 8) return line;
     23   return `${'*'.repeat(nextLevel)} ${match[2]}`;
     24 }
     25 
     26 export function isHeadingLine(line) {
     27   return HEADING_RE.test(line);
     28 }
     29 
     30 export function insertNewListItem(line) {
     31   const checklist = line.match(/^(\s*)([-+*])\s+\[[ Xx\-]\](.*)$/);
     32   if (checklist) {
     33     return `${checklist[1]}${checklist[2]} [ ]`;
     34   }
     35 
     36   const list = line.match(/^(\s*)([-+*]|\d+\.)\s+(.*)$/);
     37   if (list) {
     38     const bullet = list[2].endsWith('.') ? list[2] : list[2];
     39     return `${list[1]}${bullet} `;
     40   }
     41 
     42   if (isHeadingLine(line)) {
     43     return '- ';
     44   }
     45 
     46   return '- ';
     47 }