Action

Suggest Completion

Posted by agiletortoise, Last update 1 day ago

Suggest word completions based on the partial word currently being typed, or the selection if present.

The action will scan the current draft for words that start with the value, and prompt to select one to insert.

Steps

  • script

    function scanBackwardToWhitespace(str, startIndex) {
    	let i = startIndex;
    	while (i > 0 && !/\s/.test(str[i - 1])) {
    		i--
    	}
    	return i
    }
    
    function findMatchingWords(str, substring) {
    	const lowerSub = substring.toLowerCase()
    	let arr = str
    		.split(/\s+/) // split on whitespace
    		.map(x => x.replace(/^[\p{P}\p{S}]+|[\p{P}\p{S}]+$/gu, ''))
    		.filter(word => word.toLowerCase().startsWith(lowerSub))
    	return [...new Set(arr)]
    }
    
    let f = () => {
    	// get values
    	const text = editor.getText()
    	const [st, len] = editor.getSelectedRange()
    	var newSt = st
    	let query = editor.getSelectedText()
    	if (query.length == 0) {
    		newSt = scanBackwardToWhitespace(text, st)
    		query = text.substring(newSt, st)
    	}
    	if (query.length == 0) { return false}
    
    	// look for matching words 
    	let matches = findMatchingWords(text, query)
    	if (matches.length == 0) { return false }
    
    	// prompt to select a word
    	let p = new Prompt()
    	p.title = "Complete"
    	p.isCancellable = true
    	for (let m of matches) {
    		if (m != query) {
    			p.addButton(m, m)
    		}
    	}
    	if (!p.show()) { return false }
    
    	let sel = p.buttonPressed
    	editor.setTextInRange(newSt, query.length, sel)
    	editor.setSelectedRange(newSt + sel.length, 0)
    	editor.activate()
    	return true
    }
    
    if (!f()) {
    	context.cancel()
    }
    

Options

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