| 7 | export const TASK_LINE_RE = /^(\s*(?:>\s*)*(?:[-+*]|\d+[.)])\s+\[)( |x|X)(\].*)$/ |
| 8 | |
| 9 | export function toggleTaskAtIndex( |
| 10 | markdown: string, |
| 11 | taskIndex: number, |
| 12 | checked: boolean |
| 13 | ): string { |
| 14 | if (taskIndex < 0) return markdown |
| 15 | |
| 16 | const lines = markdown.split('\n') |
| 17 | let currentTaskIndex = 0 |
| 18 | let inFence = false |
| 19 | let fenceMarker: string | null = null |
| 20 | |
| 21 | for (let i = 0; i < lines.length; i++) { |
| 22 | const line = lines[i] |
| 23 | const fenceMatch = line.match(FENCE_RE) |
| 24 | if (fenceMatch) { |
| 25 | const marker = fenceMatch[2] |
| 26 | if (!inFence) { |
| 27 | inFence = true |
| 28 | fenceMarker = marker |
| 29 | } else if (marker === fenceMarker) { |
| 30 | inFence = false |
| 31 | fenceMarker = null |
| 32 | } |
| 33 | continue |
| 34 | } |
| 35 | if (inFence) continue |
| 36 | |
| 37 | const taskMatch = line.match(TASK_LINE_RE) |
| 38 | if (!taskMatch) continue |
| 39 | if (currentTaskIndex !== taskIndex) { |
| 40 | currentTaskIndex += 1 |
| 41 | continue |
| 42 | } |
| 43 | |
| 44 | lines[i] = `${taskMatch[1]}${checked ? 'x' : ' '}${taskMatch[3]}` |
| 45 | return lines.join('\n') |
| 46 | } |
| 47 | |
| 48 | return markdown |
| 49 | } |