Improved auto-complete for SciTE

The popular SciTE-based AutoHotkey Script Editor
lexikos
Posts: 9554
Joined: 30 Sep 2013, 04:07
Contact:

Improved auto-complete for SciTE

20 Feb 2016, 18:13

Scite Auto Complete Any Language

This is a SciTE startup script that provides auto-completion for any file type. It scans the file for identifiers on save, open and buffer switch and uses those identifiers in auto-completion. It doesn't use any external files for lists of identifiers.

What constitutes an identifier is determined by the list of patterns in IDENTIFIER_PATTERNS. This example allows identifiers to include dots (e.g. to suggest a whole "object.member.property" string) and dashes, (e.g. "lisp-or-css-identifier").

This script may not behave well if you have auto-completion enabled in SciTE properties.

http://lua-users.org/wiki/SciteAutoCompleteAnyLanguage
This allows any word in the document (whether they are variables, functions, labels, comments, etc.) to be auto-completed. I found this to be a step up from SciTE4AutoHotkey's auto-completion, which often annoys me by auto-completing the wrong word or interfering with my use of single-character variable names. ;)

Take 2

I took the script above and modified it to include everything from the current language's API files (such as AutoHotkey commands) and IMO improve the usability of the auto-complete popups. The following are features of my script (the ones I can remember):
  • Automatically brings up an auto-complete list after typing a minimum of MIN_PREFIX_LEN characters, except while typing in a comment or quoted string. Ctrl+Space also triggers the auto-complete list.
  • Auto-completes any word (greater than MIN_IDENTIFIER_LEN characters) saved in the document, except for words in comments or quoted strings. Only words consisting of alphanumeric characters and/or underscore are used, but this can be changed via IDENTIFIER_PATTERNS.
  • Case is ignored by default.
  • If INCREMENTAL is set to true, the list is narrowed down while typing, to show only the relevant items. This is disabled by default because current versions of SciTE destroy and recreate the auto-complete window when editor:AutoCShow() is called, and this doesn't look nice.
  • If INCREMENTAL is set to true, the auto-complete popup is automatically dismissed if there's only one item and you type it in full.
  • Pressing UP at the top or DOWN at the bottom of the list does one of the following:
  • Wraps around to the other end of the list if WRAP_ARROW_KEYS is true.
  • Cancels the list and allows the caret to move to the line above/below the current line.
  • Other options are available in the script (in ALL_CAPS).
  • The list is updated only on saving or opening the document.
  • It is disabled for languages other than AutoHotkey and Lua, but this can be changed in the script (see setLexerSpecificStuff; or add the appropriate list of styles to IGNORE_STYLES).
  • It should play nice with other scripts, such as the one included in SciTE4AutoHotkey.
AutoComplete.lua

To use this script with SciTE4AutoHotkey:
  • Place AutoComplete.lua in your SciTE user settings folder (i.e. %A_MyDocuments%\AutoHotkey\SciTE).
  • Add the following to UserLuaScript.lua:

    Code: Select all

    dofile(props['SciteUserHome'].."/AutoComplete.lua")
  • Restart SciTE.
To configure the script, edit the ALL_CAPS local variables at the top of the script.

Original topic: https://autohotkey.com/board/topic/7081 ... for-scite/
User avatar
boiler
Posts: 16768
Joined: 21 Dec 2014, 02:44

Re: Improved auto-complete for SciTE

20 Feb 2016, 18:15

[Note by Lexikos: This was re-posted from another topic. The original was deleted.]

This obviously isn't the best place to post this, but let me start here since the original thread is in the archived forums. If I should start a new thread regarding this, I will. As I try Lexikos' auto-complete script, I'm finding it not doing some of the things expected (the ones I was most interested in). It's not narrowing the list as I type (and incremental is set to true). It also isn't adding variables in my script to the list even after I save my file. I'm using SciTE4AutoHotkey v3.0.06.01. It very well may be that I didn't implement something correctly. Any ideas?

Also, when I added autocomplete.ahk1.start.characters= (as is or followed with a 2) to SciTEUser.properties, then the auto-complete doesn't work at all.

EDIT: After looking more through that thread, I renamed the script to UserLuaScript.lua (not sure if that's necessary as the next thing may have done it), and I trigger auto-complete by pressing control-space. Then it seems to work as intended. But there was some version of auto-complete working before that (unless I included that start.characters line in my user properties file). Is that necessary to trigger it?
lexikos
Posts: 9554
Joined: 30 Sep 2013, 04:07
Contact:

Re: Improved auto-complete for SciTE

20 Feb 2016, 18:23

boiler wrote:I renamed the script to UserLuaScript.lua (not sure if that's necessary ...
Of course, for the file to do anything, SciTE must know to load it. The original instructions told you to rename the script to UserLuaScript.lua, but there's a better way. See the instructions above (also in the script, which I have updated). It's no longer necessary to set autocomplete.ahk1.start.characters as it is overridden by the script; I have no idea why I didn't do that in the first place.
hobboy
Posts: 41
Joined: 05 Jan 2016, 09:59

Re: Improved auto-complete for SciTE

21 Feb 2016, 07:18

This sounds great! I'll give it a go
User avatar
boiler
Posts: 16768
Joined: 21 Dec 2014, 02:44

Re: Improved auto-complete for SciTE

21 Feb 2016, 11:14

I can't get the new version of the script to work. When I start typing in SciTE4AutoHotkey's main edit window, the following appears in the output pane:
...ers\Mike\Documents\AutoHotkey\SciTE/AutoComplete.lua:156: attempt to call upvalue 'shouldIgnorePos' (a nil value)
and it repeats with every subsequent keypress.

I'm using SciTE4AutoHotkey version 3.0.06.01 - Based on SciTE 3.5.1.

I'd appreciate anything you might be able to suggest.
lexikos
Posts: 9554
Joined: 30 Sep 2013, 04:07
Contact:

Re: Improved auto-complete for SciTE

21 Feb 2016, 22:30

I suppose that means the OnSwitchFile event is not being called. Did you have the full file (currently 296 lines)? The event handlers are set at the end of the file. Do you have some other custom Lua code running?

Edit: I had recently tested it on two standard up-to-date SciTE4AutoHotkey installations and my own custom SciTE4AutoHotkey setup. I have now re-tested it on a fresh portable copy, without any problem.
User avatar
boiler
Posts: 16768
Joined: 21 Dec 2014, 02:44

Re: Improved auto-complete for SciTE

21 Feb 2016, 23:48

(skip to the last line of this post for the update, the rest left for reference)

Yes, it's 296 lines including the event handlers. I do have some other custom Lua code that haichen started and I modified which highlights and counts all instances of the selected text. I imagine it's that we didn't add the event handlers "in a cooperative fashion" as you put it in your script. I'll try disabling that code and I expect this code will then work, and I'll see what I can do to modify the other code to make it play nice with others. Thanks for the feedback and insight.

Looking at event handling in that Lua extension code, there is this at the end:

Code: Select all

local events = {
    OnUpdateUI = function(shift,ctrl,alt)
    if markOccurrences() then     return true     end
    return false
    end
}

RegisterEvents(events)
And I believe I added this at the top (quite possibly the wrong place and not written to avoid conflicts):

Code: Select all

OnOpen = function()
    props['matchCase'] = 'insensitive'
    props['wholeWord'] = 'not '
    return true
end
Perhaps the part I wrote should also be within the local events block. I don't remember if I tried that and it didn't work or I just didn't think to put it there.

UPDATE: I put the part I wrote into a "local" block, and now they're playing nicely together. Everything works. Love the auto-complete. Thank you very much for the help!
lexikos
Posts: 9554
Joined: 30 Sep 2013, 04:07
Contact:

Re: Improved auto-complete for SciTE

22 Feb 2016, 00:34

It will be the OnOpen. I didn't notice (or remember) that shouldIgnorePos is initialized via either OnOpen or OnSwitchFile. If OnSwitchFile is working but not OnOpen, I suppose that if you switch documents and back, it will work.

Wrap your function with RegisterEvents({ ... }) and remove return true, like:

Code: Select all

RegisterEvents({OnOpen = function()
    props['matchCase'] = 'insensitive'
    props['wholeWord'] = 'not '
end})
Or you can use a temporary variable like in your post above.

RegisterEvents just contains a copy of my event registration code.
function RegisterEvents(events)
-- Code originally written by Lexikos (AutoComplete.lua)
User avatar
boiler
Posts: 16768
Joined: 21 Dec 2014, 02:44

Re: Improved auto-complete for SciTE

22 Feb 2016, 07:11

Very helpful info. It didn't occur to me that the other Lua code could have been conflicting. Thanks again.
joshatt
Posts: 151
Joined: 07 Dec 2014, 08:41

Re: Improved auto-complete for SciTE

29 Aug 2016, 22:27

Thanks, lexikos.
It works on version " 3.0.06.01 - Based on SciTE 3.5.1". But file has to be saved in order for any new variable be remembered.
I guess (such a long time,I could barely remember any of it) the following code for old version can make any variable remembered without saving. But I don't know anything about lua, and is this lua? Is it possible to add it to version 3.0.06.01?

Code: Select all

-- Dynamically generate autocomplete lists from possible identifiers in any file.

local IGNORE_CASE = true
-- Number of chars to type before the autocomplete list appears:
local MIN_PREFIX_LEN = 3
-- Length of shortest word to add to the autocomplete list
local MIN_IDENTIFIER_LEN = 5
-- A list of string patterns for finding suggestions for the autocomplete menu.
local IDENTIFIER_PATTERNS = {"[%a_$][%w_]+", "[%a_$][%w_.]*[%w_]", "[%a_$][%w_-]*[%w_]"}


local list_names = {}
local notempty = next


if IGNORE_CASE then
    normalize = string.lower
else
    normalize = function(word) return word end
end


function buildNames()
    list_names = {}
    local text = editor:GetText()
    for i, pattern in ipairs(IDENTIFIER_PATTERNS) do
        for word in string.gmatch(text, pattern) do
            if string.len(word) >= MIN_IDENTIFIER_LEN then
                list_names[word] = true
            end
        end
    end
end


function handleChar()
    if not editor:AutoCActive() then
        editor.AutoCIgnoreCase = IGNORE_CASE            
        local pos = editor.CurrentPos
        local startPos = editor:WordStartPosition(pos, true)
        local len = pos - startPos
        if len >= MIN_PREFIX_LEN then
            local prefix = editor:textrange(startPos, pos)
            local menuItems = {}
            for name, v in pairs(list_names) do
                if normalize(string.sub(name, 1, len)) == normalize(prefix) then 
                    table.insert(menuItems, name)
                end
            end
            if notempty(menuItems) then
                table.sort(menuItems)
                editor:AutoCShow(len, table.concat(menuItems, " "))
            end
        end
    end
end

-- Event handlers
--OnChar       = handleChar
--OnSave       = buildNames
--OnSwitchFile = buildNames
--OnOpen       = buildNames
lexikos
Posts: 9554
Joined: 30 Sep 2013, 04:07
Contact:

Re: Improved auto-complete for SciTE

30 Aug 2016, 03:10

joshatt wrote:But file has to be saved in order for any new variable be remembered.
The list of words is retrieved by buildNames, which is only called when you save or open a file. The difference is that my script caches the list of words, whereas the one you posted recreates it (by scanning the entire file) every time you switch files. The script you posted still won't add new words until you save or switch files.
joshatt
Posts: 151
Joined: 07 Dec 2014, 08:41

Re: Improved auto-complete for SciTE

30 Aug 2016, 03:19

lexikos wrote:
joshatt wrote:But file has to be saved in order for any new variable be remembered.
The list of words is retrieved by buildNames, which is only called when you save or open a file. The difference is that my script caches the list of words, whereas the one you posted recreates it (by scanning the entire file) every time you switch files. The script you posted still won't add new words until you save or switch files.
Ok. Thanks for your help.
User avatar
Joe Glines
Posts: 770
Joined: 30 Sep 2013, 20:49
Location: Dallas
Contact:

Re: Improved auto-complete for SciTE

27 Jun 2017, 05:49

This is incredibly useful! I recorded a short video demonstrating its usage and hope others take a look at it to see how helpful it is!


I did make a small tweak to my version of this script. I added " OnUpdateUI = buildNames" which has SciTE scan for new words when you update the gui. This might be too frequent (especially on larger files) but I'll report back if it causes issues.

Code: Select all

local events = {
    OnChar          = handleChar,
    OnKey           = handleKey,
    OnSave          = buildNames,
    OnUpdateUI      = buildNames, --I added this line @ line 282 
    OnSwitchFile    = function()
Sign-up for the 🅰️HK Newsletter

ImageImageImageImage:clap:
AHK Tutorials:Web Scraping | | Webservice APIs | AHK and Excel | Chrome | RegEx | Functions
Training: AHK Webinars Courses on AutoHotkey :ugeek:
YouTube

:thumbup: Quick Access Popup, the powerful Windows folders, apps and documents launcher!
joshatt
Posts: 151
Joined: 07 Dec 2014, 08:41

Re: Improved auto-complete for SciTE

23 Dec 2018, 19:29

Joe Glines wrote:
27 Jun 2017, 05:49
This is incredibly useful! I recorded a short video demonstrating its usage and hope others take a look at it to see how helpful it is!


I did make a small tweak to my version of this script. I added " OnUpdateUI = buildNames" which has SciTE scan for new words when you update the gui. This might be too frequent (especially on larger files) but I'll report back if it causes issues.

Code: Select all

local events = {
    OnChar          = handleChar,
    OnKey           = handleKey,
    OnSave          = buildNames,
    OnUpdateUI      = buildNames, --I added this line @ line 282 
    OnSwitchFile    = function()
Wow, although cann't see your video tuts, but I added this line and it's perfect!
User avatar
rediffusion
Posts: 58
Joined: 15 Mar 2019, 05:16

Re: Improved auto-complete for SciTE

01 Oct 2019, 13:04

@Joe Glines
Hi, I read the manual carefully. I've placed file here:

Code: Select all

C:\Users\NIKA\Documents\AutoHotkey\SciTE\AutoComplete.lua
I've also added entries in this .lua file:

Code: Select all

dofile(props['SciteUserHome'].."/AutoComplete.lua")
But it's not working!? ʅ_(ツ)_ʃ

···· ···· ···· ···· ···· ···· ···· ···· ···· ···· ···· ···· ···· ···· ···· ····
For me works only `Lifting tips` which are placed in this file:

Code: Select all

ahk.api
Donxr
Posts: 5
Joined: 15 May 2018, 14:32

Re: Improved auto-complete for SciTE

10 Dec 2020, 18:41

This is a godsend. The standard Auto Complete experience was going to push me over the edge, every time I wanted to use a single letter variable.

Thank you, thank you, thank you.

Return to “SciTE4AutoHotkey”

Who is online

Users browsing this forum: No registered users and 33 guests