Demo
Description
When using the default “Toggle To-Do” command, it is not possible to add a completion date in conjunction with the Tasks plugin.
Therefore, this TP script was written to add a completion date while toggling the completion status.
It also supports:
- Converting plain text into task items
- Toggling between completed/uncompleted status
- Toggling between empty lists and empty tasks
Simply place the following TP script document into your library and register it as a shortcut in the Templater plugin (I directly overwrote the default Ctrl+L
key).
TP Script: Toggle Task Status
<%*
// Get the editor instance
const editor = app.workspace.activeEditor.editor;
// Get the current line
const cursor = editor.getCursor();
const line = editor.getLine(cursor.line);
// 1. Convert plain text or plain list into an uncompleted task
if (!/^[\s]*- \[[ x-]\]/.test(line)) {
// Convert plain text or plain list into an uncompleted task
let newLine;
if (line.startsWith('- ') || line.trim().startsWith('- ')) {
// If it's a plain list item, insert the task marker after the dash
newLine = line.replace(/^(\s*- )/, '$1[ ] ');
} else {
// If it's plain text, convert it into a task, preserving the original indentation
const indentation = line.match(/^\s*/)[0]; // Get the leading whitespace
newLine = `${indentation}- [ ] ${line.trim()}`;
}
editor.replaceRange(newLine, { line: cursor.line, ch: 0 }, { line: cursor.line, ch: line.length });
// Move the cursor to the end of the line
editor.setCursor({ line: cursor.line, ch: newLine.length });
return;
}
// ! Check the current task status
let newLine = line;
if (line.includes('[ ]')) {
// If it's in an uncompleted state, first check if there is content
if (line.replace('- [ ]', '').trim().length > 0) {
// Mark as completed and add the date
const today = new Date();
const dateStr = today.toISOString().split('T')[0].replace(/-/g, '-');
newLine = newLine.replace(/\[ \]/, '[x]');
newLine = newLine + ` ✅ ${dateStr}`; // Add the date here, removing trailing spaces
}
// Otherwise, switch back to a plain list
else {
// If there is no content, directly remove the task marker
newLine = newLine.replace(/\[ \]/, '');
}
} else if (line.includes('[x]')) {
// If it's in a completed state, switch back to an uncompleted state
newLine = newLine.replace(/\[[x]\]/, '[ ]');
newLine = newLine.replace(/\s*✅\s*\d{4}-\d{2}-\d{2}\s*$/, '');
} else {
// If it's in another state, switch to an uncompleted state
newLine = newLine.replace(/\[[ x]\]/, '[ ]');
}
// Replace the current line—note the trimmed length, otherwise it may result in an extra space
editor.replaceRange(
newLine.trimEnd(),
{ line: cursor.line, ch: 0 },
{ line: cursor.line, ch: line.trimEnd().length }
);
-%>
Direct download: ToggleTask 切换任务状态.md