Action

Toggle Tasks

Posted by @mattgemmell, Last update over 6 years ago

Toggle task marks on selected lines, as follows:

  • If a line is checked, it will become unchecked.
  • If a line is unchecked, it will become checked.
  • If a line has no checkbox, it will be given one (unchecked), along with a list-hyphen if necessary.

Steps

  • script

    // Add a function to replace substrings in a given range.
    String.prototype.splice = function(start,length,replacement) {
    	return this.substr(0,start)+replacement+this.substr(start+length);
    }
    
    // Grab the full line(s) which span the selection, as an array.
    var lineRange = editor.getSelectedLineRange();
    var selectedLines = editor.getTextInRange(lineRange[0], lineRange[1]);
    var shrinkSelection = (selectedLines.slice(-1) == "\n");
    var lines = selectedLines.split("\n");
    
    // Set up some RegExps and useful strings.
    var uncheckedRE = new RegExp(/^(-\s*(\[\s\])\s*)/, 'i');
    var checkedRE = new RegExp(/^-\s*\[x\]\s*/, 'i');
    var uncheckedPrefix = "- [ ] "
    var checkedPrefix = "- [x] "
    
    // Check or uncheck each line as appropriate, accumulating the new lines.
    var newLines = [];
    for (var line of lines) {
    	var checkedMatch = checkedRE.exec(line);
    	if (checkedMatch) { // This is a checked line.
    		// Uncheck this line.
    		newLines.push(line.splice(0, checkedMatch[0].length, uncheckedPrefix));
    		
    	} else { // This is an unchecked line, either with an empty checkbox or none.
    		uncheckedMatch = uncheckedRE.exec(line);
    		if (uncheckedMatch && line.length > 0) {
    			// Check this line.
    			newLines.push(line.splice(0, uncheckedMatch[0].length, checkedPrefix));
    		} else if (line.length == 0) { // Empty line. Keep as-is.
    			newLines.push(line);
    		} else {
    			// This line has no checkbox-brackets. First, strip any hyphen.
    			line = line.replace(/^\s*-\s*/i, '');
    			// Add checkbox hyphen and brackets, unchecked.
    			newLines.push(line.splice(0, 0, uncheckedPrefix));
    		}
    	}
    }
    
    // Replace the selected line(s) with their transformed versions.
    var newLinesChunk = newLines.join("\n");
    var selectionLength = newLinesChunk.length;
    if (shrinkSelection) {
    	selectionLength = selectionLength - 1;
    }
    editor.setTextInRange(lineRange[0], lineRange[1], newLinesChunk);
    editor.setSelectedRange(lineRange[0] + selectionLength, 0);

Options

  • After Success Nothing
    Notification Error
    Log Level Error
Items available in the Drafts Directory are uploaded by community members. Use appropriate caution reviewing downloaded items before use.