zyedidia / micro

A modern and intuitive terminal-based text editor
https://micro-editor.github.io
MIT License
24.47k stars 1.16k forks source link

Help using func (*Buffer) FindNext #3092

Closed Gavin-Holt closed 7 months ago

Gavin-Holt commented 7 months ago

Hi,

I am trying to augment my JumpToMatchingBrace shortcut, by finding the next closing brace if this function fails i.e. binding:

    "CtrlJ": "JumpToMatchingBrace|lua:initlua.myfindnext",

I have modified dmaluka's myfindnext function, but it is not working for me:

function myfindnext(bp, s, down)
    -- Defaults to find next closing brace
    if not s then local s = "\)|\]|\}" end
    if not down then local down = true end

    -- the '-' is to dereference the pointer (see gopher-luar documentation & the comment in autoclose plugin)
    local searchLoc = -bp.Cursor.Loc
    if bp.Cursor:HasSelection() then
        if down then
            searchLoc = -bp.Cursor.CurSelection[2]
        else
            searchLoc = -bp.Cursor.CurSelection[1]
        end
    end
    local match, found = bp.Buf:FindNext(s, bp.Buf:Start(), bp.Buf:End(), searchLoc, down, true)
    if found then
        bp.Cursor:SetSelectionStart(match[1])
        bp.Cursor:SetSelectionEnd(match[2])
        bp.Cursor.OrigSelection[1] = -bp.Cursor.CurSelection[1]
        bp.Cursor.OrigSelection[2] = -bp.Cursor.CurSelection[2]
        bp.Cursor:GotoLoc(match[2])
        bp:Relocate()
    end
end

When this function is called I get an error:

  init:766: bad argument #2 to FindNext (cannot use nil as type string)
    stack traceback:
            [G]: in function 'FindNext'
            init:766: in main chunk
            [G]: ?

    Press enter to continue

I continue to struggle with the GoDev documentation (no examples!), and the entry for FindNext is not giving me much insight.

Any help welcome

Kind Regards Gavin Holt

PS. I don't want to use bp.Search as it will pollute my search history and highlight all the closing braces.

OS: Windows 10 Version: 2.0.13 Commit hash: 68d88b57 Compiled on December 12, 2023

niten94 commented 7 months ago

There is nothing the parameters in myfindnext are being assigned with because there are different variables with the same name being declared in the if statements at beginning. The parameters can only be accessed in the function so just assigning parameters with something would be fine. Backslash is also used in Lua when escaping characters so \\ would have to be written when putting it in a string.

If down is assigned true when not down is true, then it would be true even if it was false so I think doing something like this instead would be better:

if not s then s = "\\)|\\]|\\}" end
if down == nil then down = true end
Gavin-Holt commented 7 months ago

Hi,

Many thanks - solved.

Kind Regards Gavin Holt