@github/text-expander-element
Version:
Activates a suggestion menu to expand text snippets as you type.
42 lines (41 loc) • 1.32 kB
JavaScript
const boundary = /\s|\(|\[/;
export default function query(text, key, cursor, { multiWord, lookBackIndex, lastMatchPosition } = {
multiWord: false,
lookBackIndex: 0,
lastMatchPosition: null
}) {
let keyIndex = text.lastIndexOf(key, cursor - 1);
if (keyIndex === -1)
return;
if (keyIndex < lookBackIndex)
return;
if (multiWord) {
if (lastMatchPosition != null) {
if (lastMatchPosition === keyIndex)
return;
keyIndex = lastMatchPosition - key.length;
}
const charAfterKey = text[keyIndex + 1];
if (charAfterKey === ' ' && cursor >= keyIndex + key.length + 1)
return;
const newLineIndex = text.lastIndexOf('\n', cursor - 1);
if (newLineIndex > keyIndex)
return;
const dotIndex = text.lastIndexOf('.', cursor - 1);
if (dotIndex > keyIndex)
return;
}
else {
const spaceIndex = text.lastIndexOf(' ', cursor - 1);
if (spaceIndex > keyIndex)
return;
}
const pre = text[keyIndex - 1];
if (pre && !boundary.test(pre))
return;
const queryString = text.substring(keyIndex + key.length, cursor);
return {
text: queryString,
position: keyIndex + key.length
};
}