Reputation: 139
I'm trying to figure out how to see if the active editor's last line that's selected contains any characters/text excluding spaces. The purpose of this is to identify if there are any text highlighted and if not then to go back up a number in the editor and not include that line.
I know that you can do this
const editor = vscode.window.activeTextEditor
const lastLineSelected = editor.selection.end
in order to get the last line number, but how can I evaluate the text that's highlighted in that line?
Upvotes: 0
Views: 738
Reputation: 180805
If I understand correctly, you want to get the text of the last line of a selection which may be multi-line. The below does that, with a check in case the only selected line is partially selected.
const editor = vscode.window.activeTextEditor;
const selection = editor.selection;
if (selection && !selection?.isEmpty) {
// is more than one line selected, if so use 0 as the start of the selection on the last line
// otherwise use the actual first character selected on that line
const firstSelectedCharacterOnLastLine = (selection.start.line < selection.end.line) ? 0 : selection.start.character;
// make a Range to use with getText(<some Range>)
const lastLineOfSelectionRange = new vscode.Range(selection.end.line, firstSelectedCharacterOnLastLine, selection.end.line, selection.end.character);
const text = editor.document.getText(lastLineOfSelectionRange);
// do your testing on the text using javascript String methods
// like text.search(/[^\s]/) search for any non-whitespace character
}
Upvotes: 1