Script: selecting the whole current text block


#1

To extend selection from the cursor position to the whole current paragraph or text block (delimited by next and most recent empty lines).

In Yosemite Javascript, or in Applescript:

10.10 JXA:

function run() {

	function fnFT(editor, opt) {

		function selectBlock(editor) {
			// select back to previous gap (or start of doc)
			// and forward to next gap (or end of doc)
			var rngSeln = editor.selectedRange(),
				tree = editor.tree(),
				
				// Most recent empty node, if any ?
				lstBefore = tree.evaluateNodePath(
					'//@id=' + rngSeln.startNode.id + '/preceding::(@type=empty)[-1]'
				),
				
				// Next empty node, if any ?
				lstAfter = tree.evaluateNodePath(
					'//@id=' + rngSeln.endNode.id + '/following::(@type=empty)[0]'
				),

				// From just after any previous node
				lngFrom = lstBefore.length ?
					lstBefore[0].lineTextStart() + 1 :
					0, // or from the start of the text
				
				// to just before any following node.
				lngTo = lstAfter.length ?
					lstAfter[0].lineTextStart() - 1 :
					tree.textLength(); // or to the end of the text

			// Select from a certain point, to a certain number of characters beyond
			editor.setSelectedRange(
				tree.createRangeFromLocation(lngFrom, lngTo - lngFrom)
			);

			return true;
		}

		return selectBlock(editor);
	}

	var docsFT = Application("FoldingText").documents(),
		varResult = docsFT.length && docsFT[0].evaluate({
			script: fnFT.toString(),
			withOptions: {}
		});

	return varResult;
}

or Applescript:

property pstrJS : "

	function fnFT(editor, opt) {

		function selectBlock(editor) {
			// select back to previous gap (or start of doc)
			// and forward to next gap (or end of doc)
			var rngSeln = editor.selectedRange(),
				tree = editor.tree(),
				
				// Most recent empty node, if any ?
				lstBefore = tree.evaluateNodePath(
					'//@id=' + rngSeln.startNode.id + '/preceding::(@type=empty)[-1]'
				),
				
				// Next empty node, if any ?
				lstAfter = tree.evaluateNodePath(
					'//@id=' + rngSeln.endNode.id + '/following::(@type=empty)[0]'
				),

				// From just after any previous node
				lngFrom = lstBefore.length ?
					lstBefore[0].lineTextStart() + 1 :
					0, // or from the start of the text
				
				// to just before any following node.
				lngTo = lstAfter.length ?
					lstAfter[0].lineTextStart() - 1 :
					tree.textLength(); // or to the end of the text

			// Select from a certain point, to a certain number of characters beyond
			editor.setSelectedRange(
				tree.createRangeFromLocation(lngFrom, lngTo - lngFrom)
			);

			return true;
		}

		return selectBlock(editor);
	}
"

on run
	tell application "FoldingText"
		set lstDocs to documents
		if lstDocs ≠ {} then
			tell item 1 of lstDocs to set varResult to (evaluate script pstrJS)
		end if
		return varResult
	end tell
end run