From 15a07205fd590c10ebc9656d65881e7b829f1be6 Mon Sep 17 00:00:00 2001 From: Shish Date: Fri, 29 Dec 2023 10:35:23 +0000 Subject: [PATCH] [autocomplete] refactor getCurrentWord --- ext/autocomplete/script.js | 31 ++++++++++++++++++++----------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/ext/autocomplete/script.js b/ext/autocomplete/script.js index e01c5757..fcb325c1 100644 --- a/ext/autocomplete/script.js +++ b/ext/autocomplete/script.js @@ -2,6 +2,25 @@ let completions_el = document.createElement('ul'); completions_el.className = 'autocomplete_completions'; completions_el.id = 'completions'; +/** + * Find the word currently being typed in the given element + * + * @param {HTMLInputElement} element + * @returns {string} + */ +function getCurrentWord(element) { + let text = element.value; + let pos = element.selectionStart; + var start = text.lastIndexOf(' ', pos-1); + if(start === -1) { + start = 0; + } + else { + start++; // skip the space + } + return text.substring(start, pos); +} + /** * Whenever input changes, look at what word is currently * being typed, and fetch completions for it. @@ -11,18 +30,8 @@ completions_el.id = 'completions'; function updateCompletions(element) { highlightCompletion(element, -1); - let text = element.value; - let pos = element.selectionStart; - // get the word before the cursor - var start = text.lastIndexOf(' ', pos-1); - if(start === -1) { - start = 0; - } - else { - start++; // skip the space - } - var word = text.substring(start, pos); + var word = getCurrentWord(element); // search for completions if(element.completer_timeout !== null) {