Templater script to toggle between 3 checkbox states and bullet

The script toggles between four states on a given line:
-: Bullet point
- [ ]: Empty checkbox
- [x]: Checked checkbox
- [b]: Special state (modify as needed)


<%*
const states = ['-', '- [ ]', '- [x]', '- [b]'];
const editor = app.workspace.activeLeaf.view.editor;
const cur = editor.getCursor("from");
const lineIndex = cur.line;
const cursorPos = cur.ch;

let lineText = editor.getLine(lineIndex);
const currentState = lineText.match(/(-\s\[[ x b]\]|-)/);

if (currentState) {
    const nextState = states[(states.indexOf(currentState[0]) + 1) % states.length];
    editor.setLine(lineIndex, lineText.replace(/(-\s\[[ x b]\]|-)/, nextState));
} else {
     app.commands.executeCommandById('editor:toggle-bullet-list');
}

editor.setCursor({ line: lineIndex, ch: cursorPos });

return "";
%>


5 Likes