diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 5c1b6d082..8dcb94062 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -3,7 +3,7 @@ name: Build and test the editor on: # Runs on pushes targeting the default branch push: - branches: ["main", "terminal-graphics"] + branches: ["main", "vim-motions"] # Allows you to run this workflow manually from the Actions tab workflow_dispatch: @@ -93,7 +93,6 @@ jobs: run: PATH=/github/home/.nimble/bin:$PATH nimble setup # linux builds - - run: nimble buildNimConfigWasmAll - run: nimble buildWasmModule - run: nim c --out:nev -D:enableGui=false -D:enableTerminal=true --app:console -D:forceLogToFile --passC:-std=gnu11 -d:exposeScriptingApi -D:isCI -D:isCINimbleCached=${{steps.cache-nimble.outputs.cache-hit}} src/desktop_main.nim # - run: nim c --out:nevc -D:enableGui=false -D:enableTerminal=true --app:console -D:forceLogToFile --passC:-std=gnu11 -d:exposeScriptingApi -D:isCI -D:isCINimbleCached=${{steps.cache-nimble.outputs.cache-hit}} --cc:clang --passC:-Wno-incompatible-function-pointer-types --passL:-ladvapi32.lib -d:enableSystemClipboard=false src/desktop_main.nim @@ -101,9 +100,8 @@ jobs: - run: nim c --out:nev-musl -D:enableGui=false -D:enableTerminal=true --app:console -d:musl -d:nimWasmtimeBuildMusl -D:forceLogToFile --passC:-std=gnu11 -d:exposeScriptingApi -D:isCI -D:isCINimbleCached=${{steps.cache-nimble.outputs.cache-hit}} src/desktop_main.nim #- run: PATH=/github/home/.nimble/bin:$PATH nimble buildRemoteWorkspaceHost #- run: PATH=/github/home/.nimble/bin:$PATH nimble buildLspWs - + # create release packages - - run: rm -r ./config/nimcache - run: PATH=/github/home/.nimble/bin:$PATH nim ./tools/package_release.nims -l # make zips @@ -171,7 +169,6 @@ jobs: - run: Invoke-WebRequest -Uri "https://github.com/electron/rcedit/releases/download/v2.0.0/rcedit-x64.exe" -OutFile "./rcedit-x64.exe" # windows builds - - run: ./emsdk/emsdk.ps1 activate 4.0.10; nimble buildNimConfigWasmAll - run: ./emsdk/emsdk.ps1 activate 4.0.10; nimble buildWasmModule - run: nim c --out:nev.exe -D:enableGui=false -D:enableTerminal=true --app:console -D:forceLogToFile --passC:-std=gnu11 -d:exposeScriptingApi -D:isCI -D:isCINimbleCached=${{steps.cache-nimble.outputs.cache-hit}} src/desktop_main.nim - run: nim c --out:nevg.exe -D:enableGui=true -D:enableTerminal=false --app:gui -D:forceLogToFile --passC:-std=gnu11 -d:exposeScriptingApi -D:isCI -D:isCINimbleCached=${{steps.cache-nimble.outputs.cache-hit}} src/desktop_main.nim @@ -183,7 +180,6 @@ jobs: - run: ./rcedit-x64.exe nevc.exe --set-icon ./res/icon.ico # create release packages - - run: rm -r ./config/nimcache - run: nim ./tools/package_release.nims -w # make zips @@ -192,7 +188,7 @@ jobs: # with: # files: release_windows # dest: release_windows.zip - + # upload artifacts - name: Upload release_windows diff --git a/config/keybindings.json b/config/keybindings.json index 2a0256ce1..f5374d3d8 100644 --- a/config/keybindings.json +++ b/config/keybindings.json @@ -3,13 +3,13 @@ "": [""], "vim.command-line-low": { - "": "vim-exit-command-line", + "": "vim.exit-command-line", "": "execute-command-line", "": "select-previous-command-in-history", "": "select-next-command-in-history", }, "vim.command-line-result-low": { - "": "vim-exit-command-line", + "": "vim.exit-command-line", }, "editor": { @@ -151,7 +151,7 @@ "": ["accept"], "": ["accept"], // "": ["cancel"], - "": ["vim-exit-popup"], + "": ["vim.exit-popup"], "": ["prev"], "": ["prev"], "": ["next"], @@ -318,84 +318,101 @@ }, "vim#text_object": { - "iw": ["vim-select-text-object", "vim-word-inner", false, true, "<#text_object.count>"], - "aw": ["vim-select-text-object", "vim-word-outer", false, true, "<#text_object.count>"], - "iW": ["vim-select-text-object", "vim-WORD-inner", false, true, "<#text_object.count>"], - "aW": ["vim-select-text-object", "vim-WORD-outer", false, true, "<#text_object.count>"], - "ip": ["vim-select-text-object", "vim-paragraph-inner", false, true, "<#text_object.count>"], - "ap": ["vim-select-text-object", "vim-paragraph-outer", false, true, "<#text_object.count>"], - - "i{": ["vim-select-surrounding", "vim-surround-{-inner", false, true, "<#text_object.count>"], - "a{": ["vim-select-surrounding", "vim-surround-{-outer", false, true, "<#text_object.count>"], - "i}": ["vim-select-surrounding", "vim-surround-{-inner", false, true, "<#text_object.count>"], - "a}": ["vim-select-surrounding", "vim-surround-{-outer", false, true, "<#text_object.count>"], - "i(": ["vim-select-surrounding", "vim-surround-(-inner", false, true, "<#text_object.count>"], - "a(": ["vim-select-surrounding", "vim-surround-(-outer", false, true, "<#text_object.count>"], - "i)": ["vim-select-surrounding", "vim-surround-(-inner", false, true, "<#text_object.count>"], - "a)": ["vim-select-surrounding", "vim-surround-(-outer", false, true, "<#text_object.count>"], - "i[": ["vim-select-surrounding", "vim-surround-[-inner", false, true, "<#text_object.count>"], - "a[": ["vim-select-surrounding", "vim-surround-[-outer", false, true, "<#text_object.count>"], - "i]": ["vim-select-surrounding", "vim-surround-[-inner", false, true, "<#text_object.count>"], - "a]": ["vim-select-surrounding", "vim-surround-[-outer", false, true, "<#text_object.count>"], - "i\\<": ["vim-select-surrounding", "vim-surround-angle-inner", false, true, "<#text_object.count>"], - "a\\<": ["vim-select-surrounding", "vim-surround-angle-outer", false, true, "<#text_object.count>"], - "i\\>": ["vim-select-surrounding", "vim-surround-angle-inner", false, true, "<#text_object.count>"], - "a\\>": ["vim-select-surrounding", "vim-surround-angle-outer", false, true, "<#text_object.count>"], - "i\"": ["vim-select-surrounding", "vim-surround-\"-inner", false, true, "<#text_object.count>"], - "a\"": ["vim-select-surrounding", "vim-surround-\"-outer", false, true, "<#text_object.count>"], - "i'": ["vim-select-surrounding", "vim-surround-'-inner", false, true, "<#text_object.count>"], - "a'": ["vim-select-surrounding", "vim-surround-'-outer", false, true, "<#text_object.count>"], + "iw": ["(count* <#text_object.count>) (vim.word-inner) (inclusive)"], + "aw": ["(count* <#text_object.count>) (vim.word-inner) (inclusive)"], + "iW": ["(count* <#text_object.count>) (vim.WORD-inner) (inclusive)"], + "aW": ["(count* <#text_object.count>) (vim.WORD-inner) (inclusive)"], + "ip": ["(vim.paragraph-inner) (inclusive)"], + "ap": ["(vim.paragraph-outer) (inclusive)"], + + "i{": ["(surround \"{\" \"}\" true)"], + "a{": ["(surround \"{\" \"}\" false)"], + "i}": ["(surround \"{\" \"}\" true)"], + "a}": ["(surround \"{\" \"}\" false)"], + "i(": ["(surround \"(\" \")\" true)"], + "a(": ["(surround \"(\" \")\" false)"], + "i)": ["(surround \"(\" \")\" true)"], + "a)": ["(surround \"(\" \")\" false)"], + "i[": ["(surround \"[\" \"]\" true)"], + "a[": ["(surround \"[\" \"]\" false)"], + "i]": ["(surround \"[\" \"]\" true)"], + "a]": ["(surround \"[\" \"]\" false)"], + "i\\<": ["(surround \"<\" \">\" true)"], + "a\\<": ["(surround \"<\" \">\" false)"], + "i\\>": ["(surround \"<\" \">\" true)"], + "a\\>": ["(surround \"<\" \">\" false)"], + "i\"": ["(surround \"\\\"\" \"\\\"\" true)"], + "a\"": ["(surround \"\\\"\" \"\\\"\" false)"], + "i'": ["(surround \"'\" \"'\" true)"], + "a'": ["(surround \"'\" \"'\" false)"], + }, + + "vim.visual-line#move": { + "": ["vim.move-direction", "line-up", "<#move.count>"], + "": ["vim.move-direction", "line-down", "<#move.count>"], + "k": ["vim.move-direction", "line-up", "<#move.count>"], + "j": ["vim.move-direction", "line-down", "<#move.count>"], }, "vim#move": { - "": ["vim-move-cursor-column", -1, "<#move.count>"], - "": ["vim-move-cursor-column", 1, "<#move.count>"], - "": ["vim-move-cursor-visual-line", -1, "<#move.count>"], - "": ["vim-move-cursor-visual-line", 1, "<#move.count>"], - "h": ["vim-move-cursor-column", -1, "<#move.count>"], - "j": ["vim-move-cursor-visual-line", 1, "<#move.count>"], - "k": ["vim-move-cursor-visual-line", -1, "<#move.count>"], - "l": ["vim-move-cursor-column", 1, "<#move.count>"], - "gm": ["move-cursor-line-center"], - "gM": ["move-cursor-center"], - - "0": ["vim-move-first", "line"], - "": ["vim-move-first", "visual-line"], - "^": ["vim-move-first", "line-no-indent"], - "$": ["vim-move-to-end-of-line", "<#move.count>"], - "": ["vim-move-to-end-of-visual-line", "<#move.count>"], - "g0": ["vim-move-first", "line"], - "g^": ["vim-move-first", "line-no-indent"], - "g$": ["vim-move-to-end-of-line", "<#move.count>"], - "gg": ["vim-move-file-start", "<#move.count>"], - "G": ["vim-move-file-end", "<#move.count>"], - "%": ["vim-move-to-matching-or-file-offset", "<#move.count>"], - - "w": ["move-selection-next", "vim-word", false, true, "<#move.count>"], - "": ["move-selection-next", "vim-word", false, true, "<#move.count>"], - "W": ["move-selection-next", "vim-WORD", false, true, "<#move.count>"], - "": ["move-selection-next", "vim-WORD", false, true, "<#move.count>"], - "e": ["move-selection-end", "vim-word", false, false, "<#move.count>"], - "E": ["move-selection-end", "vim-WORD", false, false, "<#move.count>"], - "b": ["move-selection-end", "vim-word", true, true, "<#move.count>"], - "": ["move-selection-end", "vim-word", true, true, "<#move.count>"], - "B": ["move-selection-end", "vim-WORD", true, true, "<#move.count>"], - "": ["move-selection-end", "vim-WORD", true, true, "<#move.count>"], - "ge": ["move-selection-next", "vim-word", true, false, "<#move.count>"], - "gE": ["move-selection-next", "vim-WORD", true, false, "<#move.count>"], - "}": ["move-paragraph", false, "<#move.count>"], - "{": ["move-paragraph", true, "<#move.count>"], - "f": ["vim-move-to ", false, "<#move.count>"], - "t": ["vim-move-to ", true, "<#move.count>"], - - "": ["vim-move-cursor-visual-page", 0.5, "<#move.count>", true], - "": ["vim-move-cursor-visual-page", 1, "<#move.count>", true], - "": ["vim-move-cursor-visual-page", -0.5, "<#move.count>", true], - "": ["vim-move-cursor-visual-page", -1, "<#move.count>", true], - "|": ["vim-move-to-column", "<#move.count>"], - "-": ["vim-move-cursor-line-first-char", -1, "<#move.count>"], - "+": ["vim-move-cursor-line-first-char", 1, "<#move.count>"], - "_": ["vim-move-to-start-of-line", "<#move.count>"], + "": ["(count* <#move.count>) (column -1)"], + "": ["(count* <#move.count>) (column 1)"], + "": ["(count* <#move.count>) (visual-line-up) (dont-update-target-column)"], + "": ["(count* <#move.count>) (visual-line-down) (dont-update-target-column)"], + "h": ["(count* <#move.count>) (column -1)"], + "l": ["(count* <#move.count>) (column 1)"], + "k": ["(count* <#move.count>) (visual-line-up) (dont-update-target-column)"], + "j": ["(count* <#move.count>) (visual-line-down) (dont-update-target-column)"], + "gM": ["move-cursor-line-center"], // todo + "gm": ["move-cursor-center"], // todo + "n": ["(next-search-result (or <#move.count> 1)) (start)"], + "N": ["(prev-search-result (or <#move.count> 1)) (start)"], + "gf": ["(next-change (or <#move.count> 1)) (start)"], + "gh": ["(prev-change (or <#move.count> 1)) (start)"], + "gt": ["(next-diagnostic (or <#move.count> 1)) (start)"], + "gn": ["(prev-diagnostic (or <#move.count> 1)) (start)"], + + "0": ["(line) (start)"], + "": ["(visual-line) (start)"], + "^": ["(line-no-indent) (start)"], + "$": ["(line (or <#move.count> 1)) (end)"], + "": ["(visual-line (or <#move.count> 1)) (end)"], + "g0": ["(line) (start)"], + "g^": ["(line-no-indent) (start)"], + "g$": ["(visual-line (or <#move.count> 1)) (end)"], + "gg": ["(let c <#move.count>) (if (eq c 0) (start (file)) (start (line-no-indent (line-num (- c 1)))))"], + "G": ["(file) (end) (line) (start) (if same? (end (line)))"], + "%": ["(let c <#move.count>) (if (eq c 0) (surround) (start (line-no-indent (line-num (floor (* num-lines (/ c 100)))))))"], + + "w": ["vim.move-selection-next", "(vim.word) (inclusive)", false, true, "<#move.count>"], + "": ["vim.move-selection-next", "(vim.word) (inclusive)", false, true, "<#move.count>"], + "W": ["vim.move-selection-next", "(vim.WORD) (inclusive)", false, true, "<#move.count>"], + "": ["vim.move-selection-next", "(vim.WORD) (inclusive)", false, true, "<#move.count>"], + "e": ["vim.move-selection-end", "(vim.word) (inclusive)", false, false, "<#move.count>"], + "E": ["vim.move-selection-end", "(vim.WORD) (inclusive)", false, false, "<#move.count>"], + "b": ["vim.move-selection-end", "(vim.word) (inclusive)", true, true, "<#move.count>"], + "": ["vim.move-selection-end", "(vim.word) (inclusive)", true, true, "<#move.count>"], + "B": ["vim.move-selection-end", "(vim.WORD) (inclusive)", true, true, "<#move.count>"], + "": ["vim.move-selection-end", "(vim.WORD) (inclusive)", true, true, "<#move.count>"], + "ge": ["vim.move-selection-next", "(vim.word) (inclusive)", true, false, "<#move.count>"], + "gE": ["vim.move-selection-next", "(vim.WORD) (inclusive)", true, false, "<#move.count>"], + "}": ["vim.move-paragraph", false, "<#move.count>"], + "{": ["vim.move-paragraph", true, "<#move.count>"], + "f": ["(move-to )"], + "t": ["(column) (move-to ) (column -1)"], + "f": ["(move-to \" \")"], + "t": ["(column) (move-to \" \") (column -1)"], + "f": ["(move-to \"\n\")"], + "t": ["(column) (move-to \"\n\") (column -1)"], + + "": ["vim.move-cursor-visual-page", 50, "<#move.count>", true], + "": ["vim.move-cursor-visual-page", 100, "<#move.count>", true], + "": ["vim.move-cursor-visual-page", -50, "<#move.count>", true], + "": ["vim.move-cursor-visual-page", -100, "<#move.count>", true], + "|": ["vim.move-to-column", "<#move.count>"], + "-": ["vim.move-cursor-line-first-char", -1, "<#move.count>"], + "+": ["vim.move-cursor-line-first-char", 1, "<#move.count>"], + "_": ["vim.move-to-start-of-line", "<#move.count>"], }, "vim.base": { @@ -416,7 +433,7 @@ "w": ["focus-next-view", "**"], "p": ["open-prev-view"], "": ["open-prev-view"], - "q": ["vim-close-current-view-or-quit"], + "q": ["vim.close-current-view-or-quit"], "": ["close-active-view"], "c": ["hide-active-view"], "C": ["close-active-view"], @@ -442,18 +459,18 @@ }, "vim": { - "": ["vim-normal-mode"], - "": ["vim-add-cursor-above"], - "": ["vim-add-cursor-below"], + "": ["vim.normal-mode"], + "": ["vim.add-cursor-above"], + "": ["vim.add-cursor-below"], // special - "d": ["vim-delete-move <#count>"], - "c": ["vim-change-move <#count>"], - "y": ["vim-yank-move <#count>"], + "d": ["vim.delete-move <#count>"], + "c": ["vim.change-move <#count>"], + "y": ["vim.yank-move <#count>"], - "d": ["vim-delete-move <#count>"], - "c": ["vim-change-move <#count>"], - "y": ["vim-yank-move <#count>"], + "d": ["vim.delete-move <#count>"], + "c": ["vim.change-move <#count>"], + "y": ["vim.yank-move <#count>"], "": ["scroll-lines", -2], "": ["scroll-text-horizontal", -4], @@ -462,52 +479,45 @@ "": ["scroll-lines", -1], "": ["scroll-lines", 1], - "/": ["vim-open-search-bar"], - "gc": ["vim-toggle-line-comment"], - "*": ["vim-set-search-query-from-word"], - "n": ["vim-next-search-result"], - "N": ["vim-prev-search-result"], + "/": ["vim.open-search-bar"], + "gc": ["vim.toggle-line-comment"], + "*": ["vim.set-search-query-from-word"], ".": ["replay-commands", "."], - "L": ["vim-select-word-or-add-cursor"], - "H": ["vim-move-last-selection-to-next-search-result"], + "L": ["vim.select-word-or-add-cursor"], + "H": ["vim.move-last-selection-to-next-search-result"], - "m": ["vim-add-mark "], - "'": ["vim-goto-mark "], + "m": ["vim.add-mark "], + "'": ["vim.goto-mark "], - "q": ["vim-start-macro "], - "@": ["vim-play-macro "], - "Q": ["vim-stop-macro"], + "q": ["vim.start-macro "], + "@": ["vim.play-macro "], + "Q": ["vim.stop-macro"], - "M": ["enter-choose-cursor-mode", "vim-handle-select-word"], + "M": ["enter-choose-cursor-mode", "vim.handle-select-word"], // movement "": ["select-prev"], "": ["select-next"], - "": ["vim-select-last "], - "o": ["vim-reverse-selections"], - "": ["select-next-tab-stop"], - "": ["select-prev-tab-stop"], - "gt": ["vim-goto-next-diagnostic"], - "gn": ["vim-goto-prev-diagnostic"], - "gf": ["vim-goto-next-change"], - "gh": ["vim-goto-prev-change"], + "": ["vim.select-last "], + "o": ["move", "(reverse)"], + "": ["move", "(next-tab-stop)"], + "": ["move", "(prev-tab-stop)"], // copy/paste - "p": ["vim-paste", true, false, "vim-default-register"], - "P": ["vim-paste", true, false], + "p": ["vim.paste", true, false, "vim.default-register"], + "P": ["vim.paste", true, false], // editing - "x": ["vim-delete-right"], - "": ["vim-delete-right"], - "": ["vim-delete-left"], - "": ["vim-delete-left"], - "": ["vim-delete-left"], + "x": ["vim.delete-right"], + "": ["vim.delete-right"], + "": ["vim.delete-left"], + "": ["vim.delete-left"], "r": ["set-mode", "vim.replace"], // undo/redo - "u": ["vim-undo", true], - "U": ["vim-redo", false], + "u": ["vim.undo", true], + "U": ["vim.redo", false], // vcs "gx": ["close-diff"], @@ -516,35 +526,35 @@ "vim.normal": { // special - "a": ["vim-insert-mode", "right"], - "i": ["vim-insert-mode"], - "A": ["vim-insert-mode", "line-end"], - "I": ["vim-insert-mode", "line-no-indent"], - "gI": ["vim-insert-mode", "line-start"], - "o": ["vim-insert-line-below"], - "O": ["vim-insert-line-above"], + "a": ["vim.insert-mode", "right"], + "i": ["vim.insert-mode"], + "A": ["vim.insert-mode", "line-end"], + "I": ["vim.insert-mode", "line-no-indent"], + "gI": ["vim.insert-mode", "line-start"], + "o": ["vim.insert-line-below"], + "O": ["vim.insert-line-above"], "v": ["set-mode", "vim.visual"], - "V": ["vim-visual-line-mode"], + "V": ["vim.visual-line-mode"], - "dd": ["vim-delete-line"], - "cc": ["vim-change-line"], - "yy": ["vim-yank-line"], - "D": ["vim-delete-to-line-end"], - "C": ["vim-change-to-line-end"], - "Y": ["vim-yank-to-line-end"], + "dd": ["vim.delete-line"], + "cc": ["vim.change-line"], + "yy": ["vim.yank-line"], + "D": ["vim.delete-to-line-end"], + "C": ["vim.change-to-line-end"], + "Y": ["vim.yank-to-line-end"], // cursor movement - "gxf": ["vim-increment"], - "gxh": ["vim-decrement"], - "gxc": ["vim-increment-by-index"], + "gxf": ["vim.increment"], + "gxh": ["vim.decrement"], + "gxc": ["vim.increment-by-index"], // editing - "~": ["vim-toggle-case", true], - "\\>\\>": ["vim-indent"], - "\\<\\<": ["vim-unindent"], - "s": ["all", [".set-mode", "vim.visual"], [".vim-change-selection", true]], - "J": ["vim-join-lines", true], - "gJ": ["vim-join-lines", false], + "~": ["vim.toggle-case", true], + "\\>\\>": ["vim.indent"], + "\\<\\<": ["vim.unindent"], + "s": ["all", [".set-mode", "vim.visual"], [".vim.change-selection", true]], + "J": ["vim.join-lines", true], + "gJ": ["vim.join-lines", false], // lsp "gd": ["goto-definition"], @@ -561,12 +571,12 @@ "H": ["show-diagnostics-for-current"], // scroll - "z": ["vim-scroll-line-to-top-and-move-line-start"], - "zt": ["vim-scroll-line-to-top"], - "z.": ["vim-center-line-and-move-line-start"], - "zz": ["vim-center-line"], - "z-": ["vim-scroll-line-to-bottom-and-move-line-start"], - "zb": ["vim-scroll-line-to-bottom"], + "z": ["vim.scroll-line-to-top-and-move-line-start"], + "zt": ["vim.scroll-line-to-top"], + "z.": ["vim.center-line-and-move-line-start"], + "zz": ["vim.center-line"], + "z-": ["vim.scroll-line-to-bottom-and-move-line-start"], + "zb": ["vim.scroll-line-to-bottom"], // vcs "gy": ["stage-selected", false], @@ -576,65 +586,66 @@ "vim.insert": { "cf": ["set-mode", "vim.normal"], "": ["insert-text", " "], - "": ["vim-enter"], - "": ["vim-delete-word-back"], - "": ["vim-delete-line-back"], + "": ["vim.enter"], + "": ["vim.delete-word-back"], + "": ["vim.delete-line-back"], "": ["get-completions"], "": ["get-completions"], "": ["insert-indent"], - "": ["vim-indent"], - "": ["vim-unindent"], + "": ["vim.indent"], + "": ["vim.unindent"], "": ["set-mode", "vim.insert-register"], }, "vim.visual": { // special - "A": ["vim-insert-mode", "right"], - "I": ["vim-insert-mode", "first"], - "": ["vim-select "], - "": ["vim-select-move <#count>"], - - "y": ["vim-yank-selection"], - "gy": ["vim-yank-selection-clipboard"], - "d": ["vim-delete-selection", true], - "x": ["vim-delete-selection", true], - "X": ["vim-delete-selection", true], - "": ["vim-delete-selection", true], - "": ["vim-delete-selection", true], - "c": ["vim-change-selection", true], - "s": ["vim-change-selection", true], - "*": ["vim-set-search-query-from-selection"], - - "L": ["vim-set-search-query-or-add-cursor"], + "A": ["vim.insert-mode", "right"], + "I": ["vim.insert-mode", "first"], + "": ["vim.select "], + "": ["vim.select-move "], + + "y": ["vim.yank-selection"], + "gy": ["vim.yank-selection-clipboard"], + "d": ["vim.delete-selection", true], + "x": ["vim.delete-selection", true], + "X": ["vim.delete-selection", true], + "": ["vim.delete-selection", true], + "": ["vim.delete-selection", true], + "c": ["vim.change-selection", true], + "s": ["vim.change-selection", true], + "*": ["vim.set-search-query-from-selection"], + + "L": ["vim.set-search-query-or-add-cursor"], // copy/paste - "p": ["vim-paste", false, true, "vim-default-register"], - "P": ["vim-paste", false, true], - "y": ["vim-yank-selection"], - "gy": ["vim-yank-selection-clipboard"], - "d": ["vim-delete-selection", true], - "c": ["vim-change-selection", true], - "s": ["vim-change-selection", true], + "p": ["vim.paste", false, true, "vim.default-register"], + "P": ["vim.paste", false, true], + "y": ["vim.yank-selection"], + "gy": ["vim.yank-selection-clipboard"], + "d": ["vim.delete-selection", true], + "c": ["vim.change-selection", true], + "s": ["vim.change-selection", true], // cursor movement - "o": ["vim-invert-selections"], + "o": ["vim.invert-selections"], "gp": ["select-parent-current-ts", false], - "gl": ["vim-add-next-same-node-to-selection"], - "gh": ["vim-move-selection-to-next-same-node"], - "gs": ["vim-add-next-sibling-to-selection"], - "gd": ["vim-move-selection-to-next-sibling"], - "gi": ["vim-shrink-selection"], - "gxx": ["vim-evaluate-selection"], - "gxf": ["vim-increment-selection"], - "gxh": ["vim-decrement-selection"], - "gxc": ["vim-increment-selection-by-index"], + "gl": ["vim.add-next-same-node-to-selection"], + "gh": ["vim.move-selection-to-next-same-node"], + "gs": ["vim.add-next-sibling-to-selection"], + "gd": ["vim.move-selection-to-next-sibling"], + "gi": ["vim.grow-selection", -1], + "ga": ["vim.grow-selection", 1], + "gxx": ["vim.evaluate-selection"], + "gxf": ["vim.increment-selection"], + "gxh": ["vim.decrement-selection"], + "gxc": ["vim.increment-selection-by-index"], "gxg": "cycle-selected-case", // editing - "~": ["vim-toggle-case", false], - "\\>": ["vim-indent"], - "\\<": ["vim-unindent"], - "S": ["vim-surround "], + "~": ["vim.toggle-case", false], + "\\>": ["vim.indent"], + "\\<": ["vim.unindent"], + "S": ["vim.surround "], // vcs "gy": ["stage-selected", true], @@ -643,25 +654,25 @@ "vim.visual-line": { // special - "": ["vim-select "], - "": ["vim-select-move <#count>"], + "": ["vim.select "], + "": ["vim.select-move <#count>"], // copy/paste - "p": ["vim-paste", false, true, "vim-default-register"], - "P": ["vim-paste", false, true], - "y": ["vim-yank-selection"], - "gy": ["vim-yank-selection-clipboard"], - "d": ["vim-delete-selection", true], - "c": ["vim-change-selection", true], - "s": ["vim-change-selection", true], + "p": ["vim.paste", false, true, "vim.default-register"], + "P": ["vim.paste", false, true], + "y": ["vim.yank-selection"], + "gy": ["vim.yank-selection-clipboard"], + "d": ["vim.delete-selection", true], + "c": ["vim.change-selection", true], + "s": ["vim.change-selection", true], // cursor movement - "o": ["vim-invert-line-selections"], + "o": ["vim.invert-line-selections"], // editing - "~": ["vim-toggle-case", false], - "\\>": ["vim-indent"], - "\\<": ["vim-unindent"], + "~": ["vim.toggle-case", false], + "\\>": ["vim.indent"], + "\\<": ["vim.unindent"], // vcs "gy": ["stage-selected", true], @@ -669,13 +680,13 @@ }, "vim.replace": { - "": ["vim-replace", " "], + "": ["vim.replace", " "], "": ["set-mode", "vim.normal"], }, "vim.insert-register": { "": ["set-mode", "vim.insert"], - "": ["all", [".vim-paste", false, true, "vim-default-register"], [".set-mode", "vim.insert"]], + "": ["all", [".vim.paste", false, true, "vim.default-register"], [".set-mode", "vim.insert"]], }, "vim.completion": { @@ -750,36 +761,37 @@ "vscode": { "": ["vscode-escape"], - "": ["move-cursor-column", -1], - "": ["move-cursor-column", 1], - "": ["move-last", "word-line-back"], - "": ["move-last", "word-line"], - "": ["move-first", "line"], - "": ["move-last", "line"], + "": ["move", "(column -1)"], + "": ["move", "(column 1)"], + "": ["move", "(word-line-back) (start)"], + "": ["move", "(word-line) (end)"], + "": ["move", "(line) (start)"], + "": ["move", "(line) (end)"], + "": ["move", "(word-line-back) (join orig-start curr-start)"], + "": ["move", "(word-line) (join)"], + "": ["move", "(visual-line-up)", false], + "": ["move", "(visual-line-down)", false], + "": ["move", "(file) (start)"], + "": ["move", "(file) (end)"], + "": ["move", "(file) (join . curr-start)"], + "": ["move", "(file) (join . curr-end)"], + "": ["move", "(column -1) (join)"], + "": ["move", "(column 1) (join)"], + "": ["move", "(visual-line-up) (join)", false], + "": ["move", "(visual-line-down) (join)", false], + "": ["move", "(line) (start) (join)"], + "": ["move", "(line) (end) (join)"], + "": ["scroll-text", 20], "": ["scroll-text", -20], - "": ["move-last", "word-line-back", "last"], - "": ["move-last", "word-line", "last"], - "": ["move-cursor-line", -1], - "": ["move-cursor-line", 1], - "": ["move-first", "file"], - "": ["move-last", "file"], - "": ["move-first", "file", "last"], - "": ["move-last", "file", "last"], - "": ["move-cursor-column", -1, "last"], - "": ["move-cursor-column", 1, "last"], - "": ["move-cursor-line", -1, "last"], - "": ["move-cursor-line", 1, "last"], - "": ["move-first", "line", "last"], - "": ["move-last", "line", "last"], "": ["undo", ""], "": ["redo", ""], "": ["copy"], "": ["paste"], - "": ["delete-left"], - "": ["delete-move", "word-line-back"], - "": ["delete-right"], - "": ["delete-move", "word-line"], + "": ["delete-move", "(column -1) (join)"], + "": ["delete-move", "(word-line-back) (start) (join)"], + "": ["delete-move", "(column 1) (join)"], + "": ["delete-move", "(word-line) (end) (join)"], "": ["insert-text", "\n"], "": ["insert-text", " "], "": ["insert-indent"], @@ -790,7 +802,7 @@ "": ["move-cursor-visual-page", -1, "last"], "": ["move-cursor-visual-page", 1, "last"], - "": ["vscode-delete-line"], + "": ["all", [".delete-move", "(line) (column) (join last-start curr-end)", false], [".move", "(line) (start) (column target-column)", false, {"wrap": false}]], "": ["vscode-todo", "move-line-up"], "": ["vscode-todo", "move-line-down"], "": ["vscode-todo", "copy-line-up"], @@ -810,7 +822,7 @@ "": ["open-prev-view" ], // todo: jump list "": ["select-next" ], // todo: jump list "": ["select-prev" ], // todo: jump list - "": ["select-line-current"], + "": ["move", "(line)"], "": ["vscode-todo", "move-selection-to-last-find-match"], "": ["add-cursor-above"], "": ["add-cursor-below"], @@ -948,4 +960,4 @@ "": "toggle-all-breakpoints-enabled", }, -} \ No newline at end of file +} diff --git a/config/keybindings_custom.nim b/config/keybindings_custom.nim deleted file mode 100644 index 0945d6077..000000000 --- a/config/keybindings_custom.nim +++ /dev/null @@ -1,292 +0,0 @@ -import plugin_runtime, keybindings_normal - -proc loadCustomKeybindings*() {.expose("load-custom-keybindings").} = - loadNormalKeybindings() - - info "Applying Custom keybindings" - - # clearCommands("editor.text") - # for id in getAllEditors(): - # if id.isTextEditor(editor): - # editor.setMode("") - - # Normal mode - setHandleInputs "editor.text", false - setOption "editor.text.cursor.movement.", "both" - setOption "editor.text.cursor.wide.", true - - # navigation - addTextCommand "", "", "move-cursor-line", 30 - addTextCommand "", "", "move-cursor-line", -30 - - addTextCommandBlock "", "gg": - let count = editor.getCommandCount - if count == 0: - editor.selection = (0, 0).toSelection - else: - editor.selection = (count, 0).toSelection - editor.setCommandCount 0 - editor.scrollToCursor(Last) - - addTextCommand "", "G", "move-last", "file" - - addTextCommand "", "n", "select-move", "next-find-result", true - addTextCommand "", "N", "select-move", "prev-find-result", true - addTextCommand "", "", "addNextFindResultToSelection" - addTextCommand "", "", "addPrevFindResultToSelection" - addTextCommand "", "", "setAllFindResultToSelection" - addTextCommandBlock "", "*": editor.setSearchQueryFromMove("word") - - addTextCommand "", "", "select-line-current" - addTextCommand "", "miw", "select-inside-current" - - # lsp - addTextCommand "", "gd", "goto-definition" - addTextCommand "", "gs", "goto-symbol" - addTextCommand "", "", "get-completions" - - # editing - addTextCommand "", "x", "delete-right" - addTextCommand "", "u", "undo" - addTextCommand "", "U", "redo" - addTextCommand "", "y", "copy" - addTextCommand "", "p", "paste" - - # mode switches - addTextCommand "", "i", "set-mode", "insert" - addTextCommandBlock "", "a": - editor.setMode("insert") - editor.selections = editor.selections.mapIt((it.first, it.last.move(columns=1))) - - addTextCommand "", "v", "set-mode", "visual" - addTextCommand "", "V", "set-mode", "visual-temp" - - addTextCommandBlock "", "s": - editor.setMode("insert") - editor.selections = editor.delete(editor.selections) - - for i in 0..9: - capture i: - proc updateCommandCountHelper(editor: TextDocumentEditor) = - editor.updateCommandCount i - # echo "updateCommandCount ", editor.getCommandCount - editor.setCommandCountRestore editor.getCommandCount - editor.setCommandCount 0 - - addTextCommand "", $i, updateCommandCountHelper - addTextCommand "delete", $i, updateCommandCountHelper - addTextCommand "move", $i, updateCommandCountHelper - - addTextCommandBlock "", "d": - editor.setMode "move" - setOption "text.move-action", "delete-move" - setOption "text.move-next-mode", "" - setOption "text.move-command-count", editor.getCommandCount() - editor.setCommandCount 0 - - addTextCommand "", "D", "delete-move", "line" - - addTextCommandBlock "", "c": - editor.setMode "move" - setOption "text.move-action", "change-move" - setOption "text.move-next-mode", "insert" - setOption "text.move-command-count", editor.getCommandCount() - editor.setCommandCount 0 - - addTextCommandBlock "", "y": - editor.setMode "move" - setOption "text.move-action", "copy-move" - setOption "text.move-next-mode", "" - setOption "text.move-command-count", editor.getCommandCount() - editor.setCommandCount 0 - - addTextCommandBlock "", "f": - setOption("text.move-next-mode", editor.mode) - editor.setMode "move-to" - setOption "text.move-command-count", editor.getCommandCount() - editor.setCommandCount 0 - - addTextCommandBlock "", "t": - setOption("text.move-next-mode", editor.mode) - editor.setMode "move-before" - setOption "text.move-command-count", editor.getCommandCount() - editor.setCommandCount 0 - - addTextCommandBlock "", "D": - editor.deleteMove("line") - - addTextCommandBlock "", "C": - editor.deleteMove("line") - editor.setMode("insert") - - addTextCommandBlock "", "Y": - editor.selectMove("line") - editor.copy() - - addTextCommand "", "dl", "delete-move", "line-next" - addTextCommand "", "b", "move-last", "word-line-back" - addTextCommand "", "w", "move-last", "word-line" - addTextCommand "", "e", "move-last", "word-line" - addTextCommand "", "", "move-first", "line" - addTextCommand "", "", "move-last", "line" - addTextCommandBlock "", "o": - editor.moveCursorEnd() - editor.insertText("\n") - editor.setMode("insert") - addTextCommandBlock "", "O": - editor.moveCursorEnd() - editor.insertText("\n") - addTextCommandBlock "", "": - editor.setMode("") - editor.selection = editor.selection.last.toSelection - addTextCommandBlock "", "": - editor.setMode("") - editor.selection = editor.selection.last.toSelection - - # move mode - setHandleInputs "editor.text.move", false - setOption "editor.text.cursor.wide.move", true - setOption "editor.text.cursor.movement.move", "both" - addTextCommand "move", "i", "set-mode", "move-inside" - - template addTextMoveCommand(keys: string, move: string): untyped = - addTextCommand "move", keys, "apply-move", move, false - addTextCommand "move-inside", keys, "apply-move", move, true - - addTextMoveCommand "w", "word-line" - addTextMoveCommand "W", "word" - addTextMoveCommand "b", "word-line-back" - addTextMoveCommand "B", "word-back" - addTextMoveCommand "p", "paragraph" - addTextMoveCommand "l", "line-next" - addTextMoveCommand "L", "line" - addTextMoveCommand "d", "line-next" - addTextMoveCommand "F", "file" - addTextMoveCommand "\"", "\"" - addTextMoveCommand "'", "'" - addTextMoveCommand "(", "(" - addTextMoveCommand ")", "(" - addTextMoveCommand "[", "[" - addTextMoveCommand "]", "[" - addTextMoveCommand "}", "}" - - addTextCommandBlock "move", "f": - editor.setMode "move-to" - setOption "text.move-command-count", editor.getCommandCount() - editor.setCommandCount 0 - - addTextCommandBlock "move", "t": - editor.setMode "move-before" - setOption "text.move-command-count", editor.getCommandCount() - editor.setCommandCount 0 - - # move-to mode - setHandleActions "editor.text.move-to", false - setTextInputHandler "move-to", proc(editor: TextDocumentEditor, input: string): bool = - editor.setMode getOption[string]("text.move-next-mode") - if getOption[string]("text.move-action") != "": - editor.setCommandCount getOption[int]("text.move-command-count") - var args = newJArray() - args.add newJString("move-to " & input) - discard editor.runAction(getOption[string]("text.move-action"), args) - setOption[string]("text.move-action", "") - else: - editor.moveCursorTo(input) - return true - setOption "editor.text.cursor.wide.move-to", true - setOption "editor.text.cursor.movement.move-to", "both" - - # move-before mode - setHandleActions "editor.text.move-before", false - setTextInputHandler "move-before", proc(editor: TextDocumentEditor, input: string): bool = - editor.setMode getOption[string]("text.move-next-mode") - if getOption[string]("text.move-action") != "": - editor.setCommandCount getOption[int]("text.move-command-count") - var args = newJArray() - args.add newJString("move-before " & input) - discard editor.runAction(getOption[string]("text.move-action"), args) - setOption[string]("text.move-action", "") - else: - editor.moveCursorBefore(input) - return true - setOption "editor.text.cursor.wide.move-before", true - setOption "editor.text.cursor.movement.move-before", "both" - - # Insert mode - setHandleInputs "editor.text.insert", true - setOption "editor.text.cursor.wide.insert", false - addTextCommand "insert", "", "insert-text", "\n" - addTextCommand "insert", "", "insert-text", " " - - # Visual mode - setHandleInputs "editor.text.visual", false - setOption "editor.text.cursor.wide.visual", true - setOption "editor.text.cursor.movement.visual", "last" - addTextCommandBlock "visual", "i": - editor.setMode("move") - setOption("text.move-action", "select-move") - setOption("text.move-next-mode", "visual") - - addTextCommandBlock "visual", "d": - editor.selections = editor.delete(editor.selections) - editor.setMode("") - editor.scrollToCursor(Last) - editor.updateTargetColumn(Last) - - addTextCommandBlock "visual", "c": - editor.selections = editor.delete(editor.selections) - editor.setMode("insert") - editor.scrollToCursor(Last) - editor.updateTargetColumn(Last) - - # Visual temp mode - setHandleInputs "editor.text.visual-temp", false - setOption "editor.text.cursor.wide.visual-temp", false - setOption "editor.text.cursor.movement.visual-temp", "last-to-first" - addTextCommandBlock "visual-temp", "i": - editor.setMode("move") - setOption("text.move-action", "select-move") - setOption("text.move-next-mode", "visual-temp") - - addTextCommandBlock "visual", "d": - editor.selections = editor.delete(editor.selections) - editor.setMode("") - editor.scrollToCursor(Last) - editor.updateTargetColumn(Last) - - addTextCommandBlock "visual", "c": - editor.selections = editor.delete(editor.selections) - editor.setMode("insert") - editor.scrollToCursor(Last) - editor.updateTargetColumn(Last) - - addTextCommand "", "", "set-mode", "cursor-build" - addTextCommand "cursor-build", "c", "set-mode", "normal" - addTextCommand "cursor-build", "", "move-cursor-column", -1, "config", false - addTextCommand "cursor-build", "", "move-cursor-column", 1, "config", false - addTextCommand "cursor-build", "", "move-first", "word-line", "config", false - addTextCommand "cursor-build", "", "move-last", "word-line", "config", false - addTextCommand "cursor-build", "", "move-first", "line", "config", false - addTextCommand "cursor-build", "", "move-last", "line", "config", false - addTextCommand "cursor-build", "", "move-first", "word-line", "last", false - addTextCommand "cursor-build", "", "move-last", "word-line", "last", false - addTextCommand "cursor-build", "", "move-cursor-line", -1, "config", false - addTextCommand "cursor-build", "", "move-cursor-line", 1, "config", false - addTextCommand "cursor-build", "", "move-first", "file", "config", false - addTextCommand "cursor-build", "", "move-last", "file", "config", false - addTextCommand "cursor-build", "", "move-first", "file", "last", false - addTextCommand "cursor-build", "", "move-last", "file", "last", false - addTextCommand "cursor-build", "", "move-cursor-column", -1, "last", false - addTextCommand "cursor-build", "", "move-cursor-column", 1, "last", false - addTextCommand "cursor-build", "", "move-cursor-line", -1, "last", false - addTextCommand "cursor-build", "", "move-cursor-line", 1, "last", false - addTextCommand "cursor-build", "", "move-first", "line", "last", false - addTextCommand "cursor-build", "", "move-last", "line", "last", false - addTextCommand "cursor-build", "n", "select-move", "next-find-result", false, false - addTextCommand "cursor-build", "N", "select-move", "prev-find-result", false, false - addTextCommandBlock "cursor-build", "y": - editor.runAction("duplicate-last-selection") - editor.runAction("select-move", "\"next-find-result\" false false") - addTextCommandBlock "cursor-build", "Y": - editor.runAction("duplicate-last-selection") - editor.runAction("select-move", "\"prev-find-result\" false false") diff --git a/config/keybindings_helix.nim b/config/keybindings_helix.nim deleted file mode 100644 index 8e13fa126..000000000 --- a/config/keybindings_helix.nim +++ /dev/null @@ -1,97 +0,0 @@ -import plugin_runtime, keybindings_normal - -proc loadHelixKeybindings*() {.expose("load-helix-keybindings").} = - loadNormalKeybindings() - - info "Applying Helix keybindings" - - # clearCommands("editor.text") - # for id in getAllEditors(): - # if id.isTextEditor(editor): - # editor.setMode("") - - # Normal mode - setHandleInputs "editor.text", false - setOption "editor.text.cursor.movement.", "last-to-first" - setOption "editor.text.cursor.wide.", true - - addTextCommand "", "x", "delete-right" - addTextCommand "", "", "select-line-current" - addTextCommand "", "miw", "select-inside-current" - addTextCommand "", "u", "undo" - addTextCommand "", "U", "redo" - addTextCommand "", "i", "set-mode", "insert" - addTextCommand "", "v", "set-mode", "visual" - addTextCommand "", "m", "set-mode", "match" - addTextCommand "", "dl", "delete-move", "line-next" - addTextCommand "", "b", "move-first", "word-line" - addTextCommand "", "w", "move-last", "word-line" - addTextCommand "", "e", "move-last", "word-line" - addTextCommand "", "", "move-first", "line" - addTextCommand "", "", "move-last", "line" - - addTextCommandBlock "", "di": - editor.setMode("move") - setOption("text.move-action", "delete-move") - setOption("text.move-next-mode", "") - addTextCommandBlock "", "c": - editor.setMode("move") - setOption("text.move-action", "change-move") - setOption("text.move-next-mode", "") - addTextCommandBlock "", "o": - editor.moveCursorEnd() - editor.insertText("\n") - editor.setMode("insert") - addTextCommandBlock "", "O": - editor.moveCursorEnd() - editor.insertText("\n") - addTextCommandBlock "", "": - editor.setMode("") - editor.selection = editor.selection.last.toSelection - addTextCommandBlock "", "": - editor.setMode("") - editor.selection = editor.selection.last.toSelection - - # Match mode - setHandleInputs "editor.text.move", false - setOption "editor.text.cursor.movement.match", "both" - setOption "editor.text.cursor.wide.match", true - addTextCommandBlock "match", "i": - editor.setMode("move") - setOption("text.move-action", "select-move") - setOption("text.move-next-mode", "") - - # Move mode - setHandleInputs "editor.text.move", false - setOption "editor.text.cursor.movement.move", "both" - setOption "editor.text.cursor.wide.move", true - addTextCommand "move", "w", "set-move", "word" - addTextCommand "move", "W", "set-move", "word-line" - addTextCommand "move", "p", "set-move", "paragraph" - addTextCommand "move", "l", "set-move", "line" - addTextCommand "move", "L", "set-move", "line-next" - addTextCommand "move", "\"", "set-move", "\"" - addTextCommand "move", "'", "set-move", "'" - addTextCommand "move", "(", "set-move", "(" - addTextCommand "move", ")", "set-move", "(" - addTextCommand "move", "[", "set-move", "[" - addTextCommand "move", "]", "set-move", "[" - addTextCommand "move", "}", "set-move", "}" - addTextCommand "move", "}", "set-move", "}" - - # Insert mode - setHandleInputs "editor.text.insert", true - setOption "editor.text.cursor.wide.insert", false - setOption "editor.text.cursor.movement.visual", "both" - addTextCommand "insert", "", "insert-text", "\n" - addTextCommand "insert", "", "insert-text", " " - - # Visual mode - setHandleInputs "editor.text.visual", false - setOption "editor.text.cursor.wide.insert", true - setOption "editor.text.cursor.movement.visual", "last" - addTextCommand "visual", "v", "set-mode", "" - addTextCommandBlock "visual", "i": - editor.setMode("move") - setOption("text.move-action", "select-move") - setOption("text.move-next-mode", "visual") \ No newline at end of file diff --git a/config/keybindings_normal.nim b/config/keybindings_normal.nim deleted file mode 100644 index 975b273fe..000000000 --- a/config/keybindings_normal.nim +++ /dev/null @@ -1,205 +0,0 @@ -import plugin_runtime -import misc/[event, id, timer] - -{.used.} - -proc setModeChangedHandler*(handler: proc(editor: TextDocumentEditor, oldMode: string, newMode: string) {.gcsafe, raises: [].}) = - let modeChangedHandler = getOption("editor.text.mode-changed-handler", "") - if modeChangedHandler != "": - onEditorModeChanged.unsubscribe(parseId(modeChangedHandler)) - let id = onEditorModeChanged.subscribe proc(arg: auto) {.gcsafe, raises: [].} = - # infof"onEditorModeChanged: {arg.editor}, {arg.oldMode}, {arg.newMode}" - if arg.editor.isTextEditor(editor) and not editor.isRunningSavedCommands: - handler(editor, arg.oldMode, arg.newMode) - setOption("editor.text.mode-changed-handler", $id) - -proc addModeChangedHandler*(id: var Id, handler: proc(editor: TextDocumentEditor, oldMode: string, newMode: string) {.gcsafe, raises: [].}) = - if id != idNone(): - onEditorModeChanged.unsubscribe(id) - id = onEditorModeChanged.subscribe proc(arg: auto) {.gcsafe, raises: [].} = - # infof"onEditorModeChanged: {arg.editor}, {arg.oldMode}, {arg.newMode}" - if arg.editor.isTextEditor(editor) and not editor.isRunningSavedCommands: - handler(editor, arg.oldMode, arg.newMode) - -proc vscodeEscape(editor: TextDocumentEditor) {.exposeActive("editor.text", "vscode-escape").} = - editor.selection = editor.selection.last.toSelection - editor.clearTabStops() - -proc loadModelKeybindings*() {.expose("load-model-keybindings").} = - let t = startTimer() - defer: - infof"loadModelKeybindings: {t.elapsed.ms} ms" - - info "Applying model keybindings" - - # setHandleInputs "editor.model", true - setOption "editor.model.cursor.wide.", false - - addCommand("editor.model", "", "move-cursor-left-line") - addCommand("editor.model", "", "move-cursor-right-line") - addCommand("editor.model", "", "move-cursor-up") - addCommand("editor.model", "", "move-cursor-down") - addCommand("editor.model", "", "select-prev-neighbor") - addCommand("editor.model", "", "select-next-neighbor") - addCommand("editor.model", "", "select-prev-neighbor", true) - addCommand("editor.model", "", "select-next-neighbor", true) - addCommand("editor.model", "", "select-node") - addCommand("editor.model", "", "select-prev") - addCommand("editor.model", "", "move-cursor-left-cell") - addCommand("editor.model", "", "move-cursor-right-cell") - addCommand("editor.model", "", "move-cursor-line-start") - addCommand("editor.model", "", "move-cursor-line-end") - addCommand("editor.model", "", "move-cursor-line-start-inline") - addCommand("editor.model", "", "move-cursor-line-end-inline") - addCommand("editor.model", "", "scroll-lines", 1) - addCommand("editor.model", "", "scroll-lines", -1) - - addCommand("editor.model", "", "move-cursor-left-line", true) - addCommand("editor.model", "", "move-cursor-right-line", true) - addCommand("editor.model", "", "move-cursor-left", true) - addCommand("editor.model", "", "move-cursor-right", true) - addCommand("editor.model", "", "move-cursor-up", true) - addCommand("editor.model", "", "move-cursor-down", true) - addCommand("editor.model", "", "move-cursor-up", true) - addCommand("editor.model", "", "move-cursor-down", true) - addCommand("editor.model", "", "move-cursor-left-cell", true) - addCommand("editor.model", "", "move-cursor-right-cell", true) - addCommand("editor.model", "", "move-cursor-line-start", true) - addCommand("editor.model", "", "move-cursor-line-end", true) - addCommand("editor.model", "", "move-cursor-line-start-inline", true) - addCommand("editor.model", "", "move-cursor-line-end-inline", true) - - addCommand("editor.model", "", "undo") - addCommand("editor.model", "", "redo") - - addCommand("editor.model", "", "copy-node") - addCommand("editor.model", "", "paste-node") - - addCommand("editor.model", "", "invert-selection") - addModelCommand "", "", "select-prev" - addModelCommand "", "", "select-next" - addModelCommand "", "", "select-next" - - addModelCommand "", "g", "find-declaration", false - addModelCommand "", "G", "find-declaration", true - - addModelCommand "", "<*C-g>c", "goto-next-node-of-class", "ConstDecl" - addModelCommand "", "<*C-g>C", "goto-prev-node-of-class", "ConstDecl" - addModelCommand "", "<*C-g>l", "goto-next-node-of-class", "LetDecl" - addModelCommand "", "<*C-g>L", "goto-prev-node-of-class", "LetDecl" - addModelCommand "", "<*C-g>v", "goto-next-node-of-class", "VarDecl" - addModelCommand "", "<*C-g>V", "goto-prev-node-of-class", "VarDecl" - addModelCommand "", "<*C-g>f", "goto-next-node-of-class", "FunctionDefinition" - addModelCommand "", "<*C-g>F", "goto-prev-node-of-class", "FunctionDefinition" - addModelCommand "", "<*C-g>p", "goto-next-node-of-class", "ParameterDecl" - addModelCommand "", "<*C-g>P", "goto-prev-node-of-class", "ParameterDecl" - addModelCommand "", "<*C-g>i", "goto-next-node-of-class", "ThenCase" - addModelCommand "", "<*C-g>I", "goto-prev-node-of-class", "ThenCase" - addModelCommand "", "<*C-g>o", "goto-next-node-of-class", "ForLoop" - addModelCommand "", "<*C-g>O", "goto-prev-node-of-class", "ForLoop" - addModelCommand "", "<*C-g>w", "goto-next-node-of-class", "WhileExpression" - addModelCommand "", "<*C-g>W", "goto-prev-node-of-class", "WhileExpression" - addModelCommand "", "<*C-g>r", "goto-next-reference" - addModelCommand "", "<*C-g>R", "goto-prev-reference" - addModelCommand "", "<*C-g>e", "goto-next-invalid-node" - addModelCommand "", "<*C-g>E", "goto-prev-invalid-node" - - addCommand "editor.model", "", "replace-left" - addCommand "editor.model", "", "replace-right" - addCommand "editor.model", "", "delete-left" - addCommand "editor.model", "", "delete-right" - addCommand "editor.model", "", "create-new-node" - addCommand "editor.model", "", "select-next-placeholder" - addCommand "editor.model", "", "select-prev-placeholder" - - addCommand "editor.model", "", "show-completions" - - addCommand "editor.model", "er", "run-selected-function" - addCommand "editor.model", "ed", "toggle-use-default-cell-builder" - addCommand "editor.model", "ec", "compile-language" - - addCommand "editor.model", "gd", "goto-definition" - addCommand "editor.model", "gp", "goto-prev-reference" - addCommand "editor.model", "gn", "goto-next-reference" - addCommand "editor.model", "tt", "toggle-bool-cell" - - addCommand "editor.model.completion", "", "hide-completions" - addCommand "editor.model.completion", "", "select-prev-completion" - addCommand "editor.model.completion", "", "select-next-completion" - addCommand "editor.model.completion", "", "move-cursor-start" - addCommand "editor.model.completion", "", "apply-selected-completion" - addCommand "editor.model.completion", "", "apply-selected-completion" - - addCommand "editor.model.goto", "", "end" - -proc vscodeSelectLines(editor: TextDocumentEditor, selections: Selections): Selections = - result = selections.mapIt (if it.isBackwards: - ((it.first.line, editor.lineLength(it.first.line)), (it.last.line, 0)) - else: - ((it.first.line, 0), (it.last.line, editor.lineLength(it.last.line)))) - -proc vscodeExtendForLineDeletion(editor: TextDocumentEditor, selections: Selections): Selections = - result = selections.mapIt ( - if it.isBackwards: - if it.last.line > 0: - (it.first, editor.doMoveCursorColumn(it.last, -1)) - elif it.first.line + 1 < editor.lineCount: - (editor.doMoveCursorColumn(it.first, 1), it.last) - else: - it - else: - if it.first.line > 0: - (editor.doMoveCursorColumn(it.first, -1), it.last) - elif it.last.line + 1 < editor.lineCount: - (it.first, editor.doMoveCursorColumn(it.last, 1)) - else: - it - ) - -proc vscodeDeleteLine(editor: TextDocumentEditor) {.expose("vscode-delete-line").} = - editor.addNextCheckpoint("word") - let lineSelections = editor.vscodeExtendForLineDeletion(editor.vscodeSelectLines(editor.selections)) - editor.selections = editor.delete(lineSelections, inclusiveEnd=true).mapIt( - editor.doMoveCursorLine(it.normalized.first, 1).toSelection - ) - -proc vscodeTodo(editor: TextDocumentEditor, command: string) {.expose("vscode-todo").} = - infof"command not implemented: '{command}'. Open an issue." - -proc vscodeSelectNextDiagnostic(editor: TextDocumentEditor) {.exposeActive("editor.text", "vscode-select-next-diagnostic").} = - editor.selection = editor.getNextDiagnostic(editor.selection.last, 1).first.toSelection - editor.scrollToCursor Last - editor.updateTargetColumn() - -proc vscodeSelectPrevDiagnostic(editor: TextDocumentEditor) {.exposeActive("editor.text", "vscode-select-prev-diagnostic").} = - editor.selection = editor.getPrevDiagnostic(editor.selection.last, 1).first.toSelection - editor.scrollToCursor Last - editor.updateTargetColumn() - -proc vscodeSearch(editor: TextDocumentEditor) {.exposeActive("editor.text", "vscode-search").} = - commandLine(".set-search-query \\") - if getActiveEditor().isTextEditor(editor): - var arr = newJArray() - arr.add newJString("file") - discard editor.runAction("move-last", arr) - editor.setMode("insert") - -proc vscodeSelectNextFindResult(editor: TextDocumentEditor) {.exposeActive("editor.text", "vscode-select-next-find-result").} = - editor.selection = editor.getNextFindResult(editor.selection.last).first.toSelection - editor.scrollToCursor Last - editor.updateTargetColumn() - -proc vscodeSelectPrevFindResult(editor: TextDocumentEditor) {.exposeActive("editor.text", "vscode-select-prev-find-result").} = - editor.selection = editor.getPrevFindResult(editor.selection.last).first.toSelection - editor.scrollToCursor Last - editor.updateTargetColumn() - -proc vscodeAddNextFindResultToSelection(editor: TextDocumentEditor) {.exposeActive("editor.text", "vscode-add-next-find-result-to-selection").} = - if editor.selections.len == 1 and editor.selection.isEmpty: - let selection = editor.setSearchQueryFromMove("word", prefix=r"\b", suffix=r"\b") - editor.selection = selection - else: - let next = editor.getNextFindResult(editor.selection.last, includeAfter=true) - editor.selections = editor.selections & next - editor.scrollToCursor Last - editor.updateTargetColumn() diff --git a/config/keybindings_plugin.nim b/config/keybindings_plugin.nim deleted file mode 100644 index 0727dec2c..000000000 --- a/config/keybindings_plugin.nim +++ /dev/null @@ -1,11 +0,0 @@ -import plugin_runtime -import std/[strutils, unicode] - -proc postInitialize*(): bool {.wasmexport.} = - return true - -import keybindings_vim -import keybindings_normal - -when defined(wasm): - include plugin_runtime_impl diff --git a/config/keybindings_vim.nim b/config/keybindings_vim.nim deleted file mode 100644 index cd6aeeba6..000000000 --- a/config/keybindings_vim.nim +++ /dev/null @@ -1,1356 +0,0 @@ -import std/[strutils, macros, genasts, sequtils, sets, algorithm, jsonutils] -import plugin_runtime, keybindings_normal -import misc/[timer, util, myjsonutils, custom_unicode, id, regex] -import input_api - -embedSource() - -infof"import vim keybindings" - -var yankedLines: bool = false ## Whether the last thing we yanked was in a line mode - -type EditorVimState = object - ## Contains state which can vary per editor - selectLines: bool = false ## Whether entire lines should be selected (e.g. in visual-line mode/when using dd) - deleteInclusiveEnd: bool = true ## Whether the next time we delete some the selection end should be inclusive - cursorIncludeEol: bool = false ## Whether the cursor can be after the last character in a line (e.g. in insert mode) - currentUndoCheckpoint: string = "insert" ## Which checkpoint to undo to (depends on mode) - revisionBeforeImplicitInsertMacro: int - marks: Table[string, seq[(Anchor, Anchor)]] - unresolveMarks: Table[string, seq[Selection]] - -var editorStates: Table[EditorId, EditorVimState] - -const editorContext = "editor.text" - -proc vimState(editor: TextDocumentEditor): var EditorVimState = - if not editorStates.contains(editor.id): - editorStates[editor.id] = EditorVimState() - return editorStates[editor.id] - -proc shouldRecortImplicitPeriodMacro(editor: TextDocumentEditor): bool = - case editor.getUsage() - of "command-line", "search-bar": - return false - else: - return true - -proc recordCurrentCommandInPeriodMacro(editor: TextDocumentEditor) = - if not isReplayingCommands() and editor.shouldRecortImplicitPeriodMacro(): - setRegisterText("", ".") - editor.recordCurrentCommand(@["."]) - -proc startRecordingCurrentCommandInPeriodMacro(editor: TextDocumentEditor) = - if not isReplayingCommands() and editor.shouldRecortImplicitPeriodMacro(): - startRecordingCommands(".-temp") - setRegisterText("", ".-temp") - editor.recordCurrentCommand(@[".-temp"]) - editor.vimState.revisionBeforeImplicitInsertMacro = editor.getRevision - -type VimTextObjectRange* = enum Inner, Outer, CurrentToEnd - -proc getVimLineMargin*(): float = getOption[float]("editor.text.vim.line-margin", 5) -proc getVimClipboard*(): string = getOption[string]("editor.text.vim.clipboard", "") -proc getVimDefaultRegister*(): string = - case getVimClipboard(): - of "unnamed": return "*" - of "unnamedplus": return "+" - else: return "\"" - -proc getCurrentMacroRegister*(): string = getOption("editor.current-macro-register", "") - -proc getEnclosing(line: string, column: int, predicate: proc(c: char): bool): (int, int) = - var startColumn = column - var endColumn = column - while endColumn < line.high and predicate(line[endColumn + 1]): - inc endColumn - while startColumn > 0 and predicate(line[startColumn - 1]): - dec startColumn - return (startColumn, endColumn) - -proc vimHandleSelectWord(editor: TextDocumentEditor, cursor: Cursor) {.exposeActive(editorContext, "vim-handle-select-word").} = - editor.setSelection(cursor.toSelection) - -proc vimSelectLine(editor: TextDocumentEditor) {.exposeActive(editorContext, "vim-select-line").} = - editor.selections = editor.selections.mapIt (if it.isBackwards: - ((it.first.line, editor.lineLength(it.first.line)), (it.last.line, 0)) - else: - ((it.first.line, 0), (it.last.line, editor.lineLength(it.last.line)))) - -proc vimSelectLastCursor(editor: TextDocumentEditor) {.exposeActive(editorContext, "vim-select-last-cursor").} = - # infof"vimSelectLastCursor" - editor.selections = editor.selections.mapIt(it.last.toSelection) - editor.updateTargetColumn() - editor.setNextScrollBehaviour(ScrollToMargin) - editor.setNextSnapBehaviour(MinDistanceOffscreen) - -proc vimSelectLast(editor: TextDocumentEditor, move: string, count: int = 1) {.exposeActive(editorContext, "vim-select-last").} = - # infof"vimSelectLast '{move}' {count}" - let (action, arg) = move.parseAction - for i in 0.. 0: - (it.first, editor.doMoveCursorColumn(it.last, -1)) - elif it.first.line + 1 < editor.lineCount: - (editor.doMoveCursorColumn(it.first, 1), it.last) - else: - it - else: - if it.first.line > 0: - (editor.doMoveCursorColumn(it.first, -1), it.last) - elif it.last.line + 1 < editor.lineCount: - (it.first, editor.doMoveCursorColumn(it.last, 1)) - else: - it - ) - - return selections.mapIt(it.normalized.first.toSelection) - -proc vimUpdateSelections(editor: TextDocumentEditor, selections: Selections) = - if editor.vimState.selectLines: - editor.selections = selections.mapIt editor.doMoveCursorLine(it.normalized.first, 1).toSelection - - else: - editor.selections = selections - editor.updateTargetColumn() - editor.scrollToCursor Last - -proc vimDeleteSelection(editor: TextDocumentEditor, forceInclusiveEnd: bool, oldSelections: Option[Selections] = Selections.none) {.exposeActive(editorContext, "vim-delete-selection").} = - let newSelections = editor.copySelection(getVimDefaultRegister()) - let selectionsToDelete = editor.selections - if oldSelections.isSome: - editor.selections = oldSelections.get - editor.addNextCheckpoint("insert") - let inclusiveEnd = (not editor.vimState.selectLines) and (editor.vimState.deleteInclusiveEnd or forceInclusiveEnd) - editor.vimUpdateSelections editor.delete( - selectionsToDelete, inclusiveEnd=inclusiveEnd) - editor.vimState.deleteInclusiveEnd = true - editor.setMode "vim.normal" - -proc vimChangeSelection*(editor: TextDocumentEditor, forceInclusiveEnd: bool, oldSelections: Option[Selections] = Selections.none) {.exposeActive(editorContext, "vim-change-selection").} = - let newSelections = editor.copySelection(getVimDefaultRegister()) - let selectionsToDelete = editor.selections - if oldSelections.isSome: - editor.selections = oldSelections.get - editor.addNextCheckpoint("insert") - # todo: figure out if we should check for selectLines here as well - editor.vimUpdateSelections editor.delete( - selectionsToDelete, inclusiveEnd=editor.vimState.deleteInclusiveEnd or forceInclusiveEnd) - editor.vimState.deleteInclusiveEnd = true - editor.setMode "vim.insert" - -proc vimYankSelection*(editor: TextDocumentEditor) {.exposeActive(editorContext, "vim-yank-selection").} = - let selections = editor.copySelection(getVimDefaultRegister()) - editor.selections = selections - editor.setMode "vim.normal" - -proc vimYankSelectionClipboard*(editor: TextDocumentEditor) {.exposeActive(editorContext, "vim-yank-selection-clipboard").} = - let selections = editor.copySelection() - editor.selections = selections - editor.setMode "vim.normal" - -proc vimReplace(editor: TextDocumentEditor, input: string) {.exposeActive(editorContext, "vim-replace").} = - let texts = editor.selections.mapIt(block: - let selection = it - let text = editor.getText(selection, inclusiveEnd=true) - var newText = newStringOfCap(text.runeLen.int * input.runeLen.int) - var lastIndex = 0 - var index = text.find('\n') - if index == -1: - newText.add input.repeat(text.runeLen.int) - else: - while index != -1: - let lineLen = text.toOpenArray(lastIndex, index).runeLen.int - 1 - newText.add input.repeat(lineLen) - newText.add "\n" - lastIndex = index + 1 - index = text.find('\n', index + 1) - - let lineLen = text.toOpenArray(lastIndex, text.high).runeLen.int - newText.add input.repeat(lineLen) - - newText - ) - - # infof"replace {editor.selections} with '{input}' -> {texts}" - - editor.addNextCheckpoint "insert" - editor.selections = editor.edit(editor.selections, texts, inclusiveEnd=true).mapIt(it.first.toSelection) - editor.setMode "vim.normal" - -proc vimSelectMove(editor: TextDocumentEditor, move: string, count: int = 1) {.exposeActive(editorContext, "vim-select-move").} = - # infof"vimSelectMove '{move}' {count}" - let (action, arg) = move.parseAction - for i in 0.. failed to parse key: {target}" - - let key = parseTarget(target) - - for _ in 0.. 0: lineLen.dec - result = (cursor.line, min(cursor.column, lineLen)) - -proc vimMotionLine*(editor: TextDocumentEditor, cursor: Cursor, count: int): Selection = - var lineLen = editor.lineLength(cursor.line) - if not editor.vimState.cursorIncludeEol and lineLen > 0: lineLen.dec - result = ((cursor.line, 0), (cursor.line, lineLen)) - -proc vimMotionVisualLine*(editor: TextDocumentEditor, cursor: Cursor, count: int): Selection = - var lineLen = editor.lineLength(cursor.line) - result = editor.getSelectionForMove(cursor, "visual-line", count) - if not editor.vimState.cursorIncludeEol and result.last.column > result.first.column: - result.last.column.dec - elif result.last.column < lineLen: # This is the case if we're not in the last visual sub line - result.last.column.dec - -proc vimMotionParagraphInner*(editor: TextDocumentEditor, cursor: Cursor, count: int): Selection = - let isEmpty = editor.lineLength(cursor.line) == 0 - - result = ((cursor.line, 0), cursor) - while result.first.line - 1 >= 0 and (editor.lineLength(result.first.line - 1) == 0) == isEmpty: - dec result.first.line - while result.last.line + 1 < editor.lineCount and (editor.lineLength(result.last.line + 1) == 0) == isEmpty: - inc result.last.line - - result.last.column = editor.lineLength(result.last.line) - -proc vimMotionParagraphOuter*(editor: TextDocumentEditor, cursor: Cursor, count: int): Selection = - result = editor.vimMotionParagraphInner(cursor, count) - if result.last.line + 1 < editor.lineCount: - result = result or editor.vimMotionParagraphInner((result.last.line + 1, 0), 1) - -proc vimMotionWordOuter*(editor: TextDocumentEditor, cursor: Cursor, count: int): Selection = - result = vimMotionWord(editor, cursor, count) - if result.last.column < editor.lineLength(result.last.line) and editor.getChar(result.last) in Whitespace: - result.last = editor.vimMotionWord(result.last, 1).last - -proc vimMotionWordBigOuter*(editor: TextDocumentEditor, cursor: Cursor, count: int): Selection = - result = vimMotionWordBig(editor, cursor, count) - if result.last.column < editor.lineLength(result.last.line) and editor.getChar(result.last) in Whitespace: - result.last = editor.vimMotionWordBig(result.last, 1).last - -proc charAt*(editor: TextDocumentEditor, cursor: Cursor): char = - let res = editor.getText(cursor.toSelection, inclusiveEnd=true) - if res.len > 0: - return res[0] - else: - return '\0' - -proc vimMotionSurround*(editor: TextDocumentEditor, cursor: Cursor, count: int, c0: char, c1: char, inside: bool): Selection = - result = cursor.toSelection - # infof"vimMotionSurround: {cursor}, {count}, {c0}, {c1}, {inside}" - while true: - let lastChar = editor.charAt(result.last) - let (startDepth, endDepth) = if lastChar == c0: - (1, 0) - elif lastChar == c1: - (0, 1) - else: - (1, 1) - - # infof"vimMotionSurround: {cursor}, {count}, {c0}, {c1}, {inside}: try find around: {startDepth}, {endDepth}" - if editor.findSurroundStart(result.first, count, c0, c1, startDepth).getSome(opening) and editor.findSurroundEnd(result.last, count, c0, c1, endDepth).getSome(closing): - result = (opening, closing) - # infof"vimMotionSurround: found inside {result}" - if inside: - result.first = editor.doMoveCursorColumn(result.first, 1) - result.last = editor.doMoveCursorColumn(result.last, -1) - return - - # infof"vimMotionSurround: {cursor}, {count}, {c0}, {c1}, {inside}: try find ahead: {startDepth}, {endDepth}" - if editor.findSurroundEnd(result.first, count, c0, c1, -1).getSome(opening) and editor.findSurroundEnd(opening, count, c0, c1, 0).getSome(closing): - result = (opening, closing) - # infof"vimMotionSurround: found ahead {result}" - if inside: - result.first = editor.doMoveCursorColumn(result.first, 1) - result.last = editor.doMoveCursorColumn(result.last, -1) - return - else: - # infof"vimMotionSurround: found nothing {result}" - return - -proc vimMoveToMatching(editor: TextDocumentEditor) {.exposeActive(editorContext, "vim-move-to-matching").} = - # todo: pass as parameter - let which = if editor.mode == "vim.visual" or editor.mode == "vim.visual-line": - SelectionCursor.Last - else: - SelectionCursor.Both - - editor.selections = editor.selections.mapIt(block: - let c = editor.charAt(it.last) - let (open, close, last) = case c - of '(': ('(', ')', true) - of '{': ('{', '}', true) - of '[': ('[', ']', true) - of '<': ('<', '>', true) - of ')': ('(', ')', false) - of '}': ('{', '}', false) - of ']': ('[', ']', false) - of '>': ('<', '>', false) - of '"': ('"', '"', true) - of '\'': ('\'', '\'', true) - else: return - - let selection = editor.vimMotionSurround(it.last, 0, open, close, false) - - if last: - selection.last.toSelection(it, which) - else: - selection.first.toSelection(it, which) - ) - - editor.scrollToCursor Last - editor.updateTargetColumn() - -proc vimMotionSurroundBracesInner*(editor: TextDocumentEditor, cursor: Cursor, count: int): Selection = vimMotionSurround(editor, cursor, count, '{', '}', true) -proc vimMotionSurroundBracesOuter*(editor: TextDocumentEditor, cursor: Cursor, count: int): Selection = vimMotionSurround(editor, cursor, count, '{', '}', false) -proc vimMotionSurroundParensInner*(editor: TextDocumentEditor, cursor: Cursor, count: int): Selection = vimMotionSurround(editor, cursor, count, '(', ')', true) -proc vimMotionSurroundParensOuter*(editor: TextDocumentEditor, cursor: Cursor, count: int): Selection = vimMotionSurround(editor, cursor, count, '(', ')', false) -proc vimMotionSurroundBracketsInner*(editor: TextDocumentEditor, cursor: Cursor, count: int): Selection = vimMotionSurround(editor, cursor, count, '[', ']', true) -proc vimMotionSurroundBracketsOuter*(editor: TextDocumentEditor, cursor: Cursor, count: int): Selection = vimMotionSurround(editor, cursor, count, '[', ']', false) -proc vimMotionSurroundAngleInner*(editor: TextDocumentEditor, cursor: Cursor, count: int): Selection = vimMotionSurround(editor, cursor, count, '<', '>', true) -proc vimMotionSurroundAngleOuter*(editor: TextDocumentEditor, cursor: Cursor, count: int): Selection = vimMotionSurround(editor, cursor, count, '<', '>', false) -proc vimMotionSurroundDoubleQuotesInner*(editor: TextDocumentEditor, cursor: Cursor, count: int): Selection = vimMotionSurround(editor, cursor, count, '"', '"', true) -proc vimMotionSurroundDoubleQuotesOuter*(editor: TextDocumentEditor, cursor: Cursor, count: int): Selection = vimMotionSurround(editor, cursor, count, '"', '"', false) -proc vimMotionSurroundSingleQuotesInner*(editor: TextDocumentEditor, cursor: Cursor, count: int): Selection = vimMotionSurround(editor, cursor, count, '\'', '\'', true) -proc vimMotionSurroundSingleQuotesOuter*(editor: TextDocumentEditor, cursor: Cursor, count: int): Selection = vimMotionSurround(editor, cursor, count, '\'', '\'', false) - -# todo -addCustomTextMove "vim-line", vimMotionLine -addCustomTextMove "vim-visual-line", vimMotionVisualLine -addCustomTextMove "vim-word-outer", vimMotionWordOuter -addCustomTextMove "vim-WORD-outer", vimMotionWordBigOuter -addCustomTextMove "vim-paragraph-inner", vimMotionParagraphInner -addCustomTextMove "vim-paragraph-outer", vimMotionParagraphOuter -addCustomTextMove "vim-surround-{-inner", vimMotionSurroundBracesInner -addCustomTextMove "vim-surround-{-outer", vimMotionSurroundBracesOuter -addCustomTextMove "vim-surround-(-inner", vimMotionSurroundParensInner -addCustomTextMove "vim-surround-(-outer", vimMotionSurroundParensOuter -addCustomTextMove "vim-surround-[-inner", vimMotionSurroundBracketsInner -addCustomTextMove "vim-surround-[-outer", vimMotionSurroundBracketsOuter -addCustomTextMove "vim-surround-angle-inner", vimMotionSurroundAngleInner -addCustomTextMove "vim-surround-angle-outer", vimMotionSurroundAngleOuter -addCustomTextMove "vim-surround-\"-inner", vimMotionSurroundDoubleQuotesInner -addCustomTextMove "vim-surround-\"-outer", vimMotionSurroundDoubleQuotesOuter -addCustomTextMove "vim-surround-'-inner", vimMotionSurroundSingleQuotesInner -addCustomTextMove "vim-surround-'-outer", vimMotionSurroundSingleQuotesOuter - -iterator iterateTextObjects*(editor: TextDocumentEditor, cursor: Cursor, move: string, backwards: bool = false): Selection = - var selection = editor.getSelectionForMove(cursor, move, 0) - # infof"iterateTextObjects({cursor}, {move}, {backwards}), selection: {selection}" - yield selection - while true: - let lastSelection = selection - if not backwards and selection.last.column == editor.lineLength(selection.last.line): - if selection.last.line == editor.lineCount - 1: - break - selection = (selection.last.line + 1, 0).toSelection - elif backwards and selection.first.column == 0: - if selection.first.line == 0: - break - selection = (selection.first.line - 1, editor.lineLength(selection.first.line - 1)).toSelection - if selection.first.column == 0: - yield selection - continue - - let nextCursor = if backwards: (selection.first.line, selection.first.column - 1) else: (selection.last.line, selection.last.column + 1) - let newSelection = editor.getSelectionForMove(nextCursor, move, 0) - # infof"iterateTextObjects({cursor}, {move}, {backwards}) nextCursor: {nextCursor}, newSelection: {newSelection}" - if newSelection == lastSelection: - break - - selection = newSelection - yield selection - -iterator enumerateTextObjects*(editor: TextDocumentEditor, cursor: Cursor, move: string, backwards: bool = false): (int, Selection) = - var i = 0 - for selection in iterateTextObjects(editor, cursor, move, backwards): - yield (i, selection) - inc i - -proc vimSelectTextObject(editor: TextDocumentEditor, textObject: string, backwards: bool = false, allowEmpty: bool = false, count: int = 1, textObjectRange: VimTextObjectRange = Inner) {.exposeActive(editorContext, "vim-select-text-object").} = - # infof"vimSelectTextObject({textObject}, {textObjectRange}, {backwards}, {allowEmpty}, {count})" - - editor.selections = editor.selections.mapIt(block: - var res = it.last - var resultSelection = it - # infof"-> {resultSelection}" - - for i, selection in enumerateTextObjects(editor, res, textObject, backwards): - # infof"{i}: {res} -> {selection}" - resultSelection = resultSelection or selection - if i == max(count, 1) - 1: - break - - # infof"vimSelectTextObject({textObject}, {textObjectRange}, {backwards}, {allowEmpty}, {count}): {resultSelection}" - if it.isBackwards: - resultSelection.reverse - else: - resultSelection - ) - - editor.scrollToCursor(Last) - editor.updateTargetColumn() - -proc vimSelectSurrounding(editor: TextDocumentEditor, textObject: string, backwards: bool = false, allowEmpty: bool = false, count: int = 1, textObjectRange: VimTextObjectRange = Inner) {.exposeActive(editorContext, "vim-select-surrounding").} = - # infof"vimSelectSurrounding({textObject}, {textObjectRange}, {backwards}, {allowEmpty}, {count})" - - editor.selections = editor.selections.mapIt(block: - let resultSelection = editor.getSelectionForMove(it.last, textObject, count) - # infof"vimSelectSurrounding({textObject}, {textObjectRange}, {backwards}, {allowEmpty}, {count}): {resultSelection}" - if it.isBackwards: - resultSelection.reverse - else: - resultSelection - ) - - editor.scrollToCursor(Last) - editor.updateTargetColumn() - -proc moveSelectionNext(editor: TextDocumentEditor, move: string, backwards: bool = false, allowEmpty: bool = false, count: int = 1) {.exposeActive(editorContext, "move-selection-next").} = - # infof"moveSelectionNext '{move}' {count} {backwards} {allowEmpty}" - editor.vimState.deleteInclusiveEnd = false - let which = getOption[SelectionCursor](editor.getContextWithMode("editor.text.cursor.movement"), SelectionCursor.Both) - editor.selections = editor.selections.mapIt(block: - var res = it.last - for k in 0..= editor.lineLength(selection.first.line) or editor.getChar(selection.first) notin Whitespace: - res = cursor - break - # echo res, ", ", it, ", ", which - res.toSelection(it, which) - ) - - editor.scrollToCursor(Last) - editor.updateTargetColumn() - -proc applyMove(editor: TextDocumentEditor, selections: seq[Selection], move: string, backwards: bool = false, allowEmpty: bool = false, count: int = 1, which: Option[SelectionCursor] = SelectionCursor.none): seq[Selection] = - ## Applies the given move `count` times and returns the resulting selections - ## `allowEmpty` If true then the move can stop on empty lines - ## `backwards` Move backwards - ## `count` How often to apply the move - ## `which` How to assemble the final selection from the input and the move. If not set uses `editor.text.cursor.movement` - - # infof"moveSelectionEnd '{move}' {count} {backwards} {allowEmpty}" - let which = which.get(getOption[SelectionCursor](editor.getContextWithMode("editor.text.cursor.movement"), SelectionCursor.Both)) - return selections.mapIt(block: - var res = it.last - for k in 0.. 1: - editor.moveCursorLine(count - 1) - editor.moveLast("vim-line") - editor.scrollToCursor Last - editor.updateTargetColumn() - -proc vimMoveToEndOfVisualLine(editor: TextDocumentEditor, count: int = 1) {.exposeActive(editorContext, "vim-move-to-end-of-visual-line").} = - # infof"vimMoveToEndOfLine {count}" - let count = max(1, count) - if count > 1: - editor.moveCursorLine(count - 1) - editor.moveLast("vim-visual-line") - editor.scrollToCursor Last - editor.updateTargetColumn() - -proc vimMoveCursorLineFirstChar(editor: TextDocumentEditor, direction: int, count: int = 1) {.exposeActive(editorContext, "vim-move-cursor-line-first-char").} = - editor.moveCursorLine(direction * max(count, 1)) - editor.moveFirst "line-no-indent" - editor.updateTargetColumn() - -proc vimMoveToStartOfLine(editor: TextDocumentEditor, count: int = 1) {.exposeActive(editorContext, "vim-move-to-start-of-line").} = - # infof"vimMoveToStartOfLine {count}" - let count = max(1, count) - if count > 1: - editor.moveCursorLine(count - 1) - editor.moveFirst "line-no-indent" - editor.scrollToCursor Last - editor.updateTargetColumn() - -proc vimPaste(editor: TextDocumentEditor, pasteRight: bool = false, inclusiveEnd: bool = false, register: string = "") {.exposeActive(editorContext, "vim-paste").} = - # infof"vimPaste {register}, lines: {yankedLines}" - let register = if register == "vim-default-register": - getVimDefaultRegister() - else: - register - - editor.addNextCheckpoint "insert" - - let selectionsToDelete = editor.selections - editor.selections = editor.delete(selectionsToDelete, inclusiveEnd=false) - - if yankedLines: - # todo: pass bool as parameter - if editor.mode != "vim.visual-line": - editor.moveLast "line", Both - editor.insertText "\n", autoIndent=false - - if pasteRight: - editor.selections = editor.selections.mapIt(editor.doMoveCursorColumn(it.last, 1, wrap=false).toSelection) - - editor.setMode "vim.normal" - editor.paste register, inclusiveEnd=inclusiveEnd - -proc vimToggleCase(editor: TextDocumentEditor, moveCursorRight: bool) {.exposeActive(editorContext, "vim-toggle-case").} = - var editTexts: seq[string] - - for s in editor.selections: - let text = editor.getText(s, inclusiveEnd=true) - var newText = "" - for r in text.runes: - if r.isLower: - newText.add $r.toUpper - else: - newText.add $r.toLower - editTexts.add newText - - editor.addNextCheckpoint "insert" - let oldSelections = editor.selections - discard editor.edit(editor.selections, editTexts, inclusiveEnd=true) - editor.selections = oldSelections.mapIt(it.first.toSelection) - - editor.setMode "vim.normal" - - if moveCursorRight: - editor.moveCursorColumn(1, Both, wrap=false, - includeAfter=editor.vimState.cursorIncludeEol) - editor.updateTargetColumn() - -proc vimCloseCurrentViewOrQuit() {.exposeActive(editorContext, "vim-close-current-view-or-quit").} = - let openEditors = getNumVisibleViews() + getNumHiddenViews() - if openEditors == 1: - plugin_runtime.quit() - else: - closeActiveView() - -proc vimIndent(editor: TextDocumentEditor) {.exposeActive(editorContext, "vim-indent").} = - editor.addNextCheckpoint "insert" - editor.indent() - -proc vimUnindent(editor: TextDocumentEditor) {.exposeActive(editorContext, "vim-unindent").} = - editor.addNextCheckpoint "insert" - editor.unindent() - -proc vimAddCursorAbove(editor: TextDocumentEditor) {.exposeActive(editorContext, "vim-add-cursor-above").} = - editor.addCursorAbove() - editor.scrollToCursor(Last) - -proc vimAddCursorBelow(editor: TextDocumentEditor) {.exposeActive(editorContext, "vim-add-cursor-below").} = - editor.addCursorBelow() - editor.scrollToCursor(Last) - -proc vimEnter(editor: TextDocumentEditor) {.exposeActive(editorContext, "vim-enter").} = - editor.addNextCheckpoint "insert" - editor.insertText("\n") - -proc vimNormalMode(editor: TextDocumentEditor) {.exposeActive(editorContext, "vim-normal-mode").} = - ## Exit to normal mode and clear things - if editor.mode == "vim.normal": - editor.selection = editor.selection.last.toSelection - editor.clearTabStops() - editor.setMode("vim.normal") - -proc vimVisualLineMode(editor: TextDocumentEditor) {.exposeActive(editorContext, "vim-visual-line-mode").} = - editor.setMode "vim.visual-line" - editor.vimSelectLine() - -proc vimYankLine(editor: TextDocumentEditor) {.exposeActive(editorContext, "vim-yank-line").} = - editor.vimState.selectLines = true - editor.vimSelectLine() - editor.vimYankSelection() - editor.vimState.selectLines = false - -proc vimDeleteLine(editor: TextDocumentEditor) {.exposeActive(editorContext, "vim-delete-line").} = - editor.vimState.selectLines = true - let oldSelections = editor.selections - editor.vimSelectLine() - editor.vimDeleteSelection(true, oldSelections=oldSelections.some) - editor.vimState.selectLines = false - -proc vimChangeLine(editor: TextDocumentEditor) {.exposeActive(editorContext, "vim-change-line").} = - let oldSelections = editor.selections - editor.vimSelectLine() - editor.vimChangeSelection(true, oldSelections=oldSelections.some) - -proc vimDeleteToLineEnd(editor: TextDocumentEditor) {.exposeActive(editorContext, "vim-delete-to-line-end").} = - let oldSelections = editor.selections - editor.selections = editor.selections.mapIt (it.last, editor.vimMotionLine(it.last, 0).last) - editor.vimDeleteSelection(true, oldSelections=oldSelections.some) - editor.vimState.selectLines = false - -proc vimChangeToLineEnd(editor: TextDocumentEditor) {.exposeActive(editorContext, "vim-change-to-line-end").} = - let oldSelections = editor.selections - editor.selections = editor.selections.mapIt (it.last, editor.vimMotionLine(it.last, 0).last) - editor.vimChangeSelection(true, oldSelections=oldSelections.some) - editor.vimState.selectLines = false - -proc vimYankToLineEnd(editor: TextDocumentEditor) {.exposeActive(editorContext, "vim-yank-to-line-end").} = - editor.selections = editor.selections.mapIt (it.last, editor.vimMotionLine(it.last, 0).last) - editor.vimYankSelection() - editor.vimState.selectLines = false - -proc vimMoveFileStart(editor: TextDocumentEditor, count: int = 1) {.exposeActive(editorContext, "vim-move-file-start").} = - let which = getOption[SelectionCursor](editor.getContextWithMode("editor.text.cursor.movement"), SelectionCursor.Both) - editor.selection = (count - 1, 0).toSelection(editor.selection, which) - editor.moveFirst "line-no-indent" - editor.scrollToCursor Last - editor.setNextSnapBehaviour(MinDistanceOffscreen) - -proc vimMoveFileEnd(editor: TextDocumentEditor, count: int = 1) {.exposeActive(editorContext, "vim-move-file-end").} = - let line = if count == 0: editor.lineCount - 1 else: count - 1 - let which = getOption[SelectionCursor](editor.getContextWithMode("editor.text.cursor.movement"), SelectionCursor.Both) - var newSelection = (line, 0).toSelection(editor.selection, which) - if newSelection == editor.selection: - let lineLen = editor.lineLength(line) - editor.selection = (line, lineLen).toSelection(editor.selection, which) - else: - editor.selection = newSelection - editor.moveFirst "line-no-indent" - editor.scrollToCursor Last - editor.setNextSnapBehaviour(MinDistanceOffscreen) - -proc vimMoveToMatchingOrFileOffset(editor: TextDocumentEditor, count: int = 1) {.exposeActive(editorContext, "vim-move-to-matching-or-file-offset").} = - if count == 0: - editor.vimMoveToMatching() - else: - let line = clamp((count * editor.lineCount) div 100, 0, editor.lineCount - 1) - let which = getOption[SelectionCursor](editor.getContextWithMode("editor.text.cursor.movement"), SelectionCursor.Both) - editor.selection = (line, 0).toSelection(editor.selection, which) - editor.moveFirst "line-no-indent" - editor.scrollToCursor Last - editor.setNextSnapBehaviour(MinDistanceOffscreen) - -proc vimScrollLineToTopAndMoveLineStart(editor: TextDocumentEditor, count: int = 1) {.exposeActive(editorContext, "vim-scroll-line-to-top-and-move-line-start").} = - if editor.getCommandCount != 0: - editor.selection = (editor.getCommandCount, 0).toSelection - editor.moveFirst "line-no-indent" - editor.setCursorScrollOffset getVimLineMargin() * platformTotalLineHeight() - -proc vimScrollLineToTop(editor: TextDocumentEditor, count: int = 1) {.exposeActive(editorContext, "vim-scroll-line-to-top").} = - if editor.getCommandCount != 0: - editor.selection = (editor.getCommandCount, editor.selection.last.column).toSelection - editor.setCursorScrollOffset getVimLineMargin() * platformTotalLineHeight() - -proc vimCenterLineAndMoveLineStart(editor: TextDocumentEditor, count: int = 1) {.exposeActive(editorContext, "vim-center-line-and-move-line-start").} = - if editor.getCommandCount != 0: - editor.selection = (editor.getCommandCount, 0).toSelection - editor.moveFirst "line-no-indent" - editor.centerCursor() - -proc vimCenterLine(editor: TextDocumentEditor, count: int = 1) {.exposeActive(editorContext, "vim-center-line").} = - if editor.getCommandCount != 0: - editor.selection = (editor.getCommandCount, editor.selection.last.column).toSelection - editor.centerCursor() - -proc vimScrollLineToBottomAndMoveLineStart(editor: TextDocumentEditor, count: int = 1) {.exposeActive(editorContext, "vim-scroll-line-to-bottom-and-move-line-start").} = - if editor.getCommandCount != 0: - editor.selection = (editor.getCommandCount, 0).toSelection - editor.moveFirst "line-no-indent" - editor.setCursorScrollOffset (editor.screenLineCount.float - getVimLineMargin()) * platformTotalLineHeight() - -proc vimScrollLineToBottom(editor: TextDocumentEditor, count: int = 1) {.exposeActive(editorContext, "vim-scroll-line-to-bottom").} = - if editor.getCommandCount != 0: - editor.selection = (editor.getCommandCount, editor.selection.last.column).toSelection - editor.setCursorScrollOffset (editor.screenLineCount.float - getVimLineMargin()) * platformTotalLineHeight() - -proc vimInsertMode(editor: TextDocumentEditor, move: string = "") {.exposeActive(editorContext, "vim-insert-mode").} = - case move - of "right": - editor.selections = editor.selections.mapIt(editor.doMoveCursorColumn(it.last, 1, wrap=false).toSelection) - of "line-end": - editor.moveLast "line", Both - of "line-no-indent": - editor.moveFirst "line-no-indent", Both - of "first": - editor.selections = editor.selections.mapIt(it.normalized.first.toSelection) - of "line-start": - editor.moveFirst "line", Both - else: - discard - editor.setMode "vim.insert" - editor.addNextCheckpoint "insert" - -proc vimInsertLineBelow(editor: TextDocumentEditor) {.exposeActive(editorContext, "vim-insert-line-below").} = - editor.moveLast "line", Both - editor.addNextCheckpoint "insert" - editor.insertText "\n" - editor.setMode "vim.insert" - -proc vimInsertLineAbove(editor: TextDocumentEditor, move: string = "") {.exposeActive(editorContext, "vim-insert-line-above").} = - editor.moveFirst "line", Both - editor.addNextCheckpoint "insert" - editor.insertText "\n", autoIndent=false - editor.vimMoveCursorLine -1 - editor.setMode "vim.insert" - -proc vimSetSearchQueryFromWord(editor: TextDocumentEditor) {.exposeActive(editorContext, "vim-set-search-query-from-word").} = - editor.selection = editor.setSearchQueryFromMove("word", prefix=r"\b", suffix=r"\b").first.toSelection - -proc vimSetSearchQueryFromSelection(editor: TextDocumentEditor) {.exposeActive(editorContext, "vim-set-search-query-from-selection").} = - discard editor.setSearchQuery(editor.getText(editor.selection, inclusiveEnd=true), escapeRegex=true) - editor.selection = editor.selection.first.toSelection - editor.setMode("vim.normal") - -proc vimNextSearchResult(editor: TextDocumentEditor) {.exposeActive(editorContext, "vim-next-search-result").} = - editor.selection = editor.getNextFindResult(editor.selection.last).first.toSelection - editor.scrollToCursor Last - editor.setNextSnapBehaviour(MinDistanceOffscreen) - editor.updateTargetColumn() - -proc vimPrevSearchResult(editor: TextDocumentEditor) {.exposeActive(editorContext, "vim-prev-search-result").} = - editor.selection = editor.getPrevFindResult(editor.selection.last).first.toSelection - editor.scrollToCursor Last - editor.setNextSnapBehaviour(MinDistanceOffscreen) - editor.updateTargetColumn() - -proc vimOpenSearchBar(editor: TextDocumentEditor) {.exposeActive(editorContext, "vim-open-search-bar").} = - editor.openSearchBar() - if getActiveEditor().isTextEditor(editor): - editor.setMode("vim.insert") - -proc vimExitCommandLine() {.expose("vim-exit-command-line").} = - if getActiveEditor().isTextEditor(editor): - if editor.mode == "vim.normal": - exitCommandLine() - return - - editor.setMode("vim.normal") - -proc vimExitPopup() {.expose("vim-exit-popup").} = - if getActiveEditor().isTextEditor(editor): - if editor.mode == "vim.normal": - if getActivePopup().isSelectorPopup(popup): - popup.cancel() - return - - editor.setMode("vim.normal") - -proc vimSelectWordOrAddCursor(editor: TextDocumentEditor) {.exposeActive(editorContext, "vim-select-word-or-add-cursor").} = - if editor.selections.len == 1: - var selection = editor.setSearchQueryFromMove("word", prefix=r"\b", suffix=r"\b") - selection.last.column -= 1 - editor.selection = selection - else: - let next = editor.getNextFindResult(editor.selection.last, includeAfter=false) - editor.selections = editor.selections & next - editor.scrollToCursor Last - editor.setNextSnapBehaviour(MinDistanceOffscreen) - editor.updateTargetColumn() - - editor.setMode("vim.visual") - -proc vimMoveLastSelectionToNextSearchResult(editor: TextDocumentEditor) {.exposeActive(editorContext, "vim-move-last-selection-to-next-search-result").} = - if editor.selections.len == 1: - var selection = editor.setSearchQueryFromMove("word", prefix=r"\b", suffix=r"\b") - selection.last.column -= 1 - editor.selection = selection - else: - let next = editor.getNextFindResult(editor.selection.last, includeAfter=false) - editor.selections = editor.selections[0..^2] & next - editor.scrollToCursor Last - editor.setNextSnapBehaviour(MinDistanceOffscreen) - editor.updateTargetColumn() - - editor.setMode("vim.visual") - -proc vimSetSearchQueryOrAddCursor(editor: TextDocumentEditor) {.exposeActive(editorContext, "vim-set-search-query-or-add-cursor").} = - if editor.selections.len == 1: - let text = editor.getText(editor.selection, inclusiveEnd=true) - let textEscaped = text.escapeRegex - let currentSearchQuery = editor.getSearchQuery() - # infof"'{text}' -> '{textEscaped}' -> '{currentSearchQuery}'" - if textEscaped != currentSearchQuery and r"\b" & textEscaped & r"\b" != currentSearchQuery: - if editor.setSearchQuery(text, escapeRegex=true): - return - - let next = editor.getNextFindResult(editor.selection.last, includeAfter=false) - editor.selections = editor.selections & next - editor.scrollToCursor Last - editor.updateTargetColumn() - -proc vimSaveState() {.expose("vim-save-state").} = - try: - var states = initTable[string, JsonNode]() - - for id, state in editorStates: - if id.isTextEditor(editor): - let filename = editor.getFileName() - if filename == "": - continue - - var marks = initTable[string, seq[Selection]]() - for name, anchors in editor.vimState.marks: - let selections = editor.resolveAnchors(anchors) - marks[name] = selections - for name, selections in editor.vimState.unresolveMarks: - marks[name] = selections - - if marks.len > 0: - states[filename] = %*{ - "marks": marks.toJson, - } - - setSessionData("vim.states", states) - except: - infof"Failed to save vim editor states" - -proc resolveMarks(editor: TextDocumentEditor) = - let unresolveMarks = editor.vimState.unresolveMarks - for name, selections in unresolveMarks: - let anchors = editor.createAnchors(selections) - if anchors.len > 0: - editor.vimState.marks[name] = anchors - editor.vimState.unresolveMarks.del(name) - -proc vimAddMark(editor: TextDocumentEditor, name: string) {.exposeActive(editorContext, "vim-add-mark").} = - editor.resolveMarks() - editor.vimState.marks[name] = editor.createAnchors(editor.selections) - -proc vimGotoMark(editor: TextDocumentEditor, name: string) {.exposeActive(editorContext, "vim-goto-mark").} = - editor.resolveMarks() - - if name in editor.vimState.marks: - let newSelections = editor.resolveAnchors(editor.vimState.marks[name]) - if newSelections.len == 0: - return - - case editor.mode - of "vim.visual", "vim.visual-line": - let oldSelections = editor.selections - if newSelections.len == oldSelections.len: - editor.selections = collect: - for i in 0..newSelections.high: - oldSelections[i] or newSelections[i] - else: - editor.selections = newSelections - else: - editor.selections = newSelections - - editor.updateTargetColumn() - editor.scrollToCursor Last - editor.setNextSnapBehaviour(MinDistanceOffscreen) - -proc vimDeleteWordBack(editor: TextDocumentEditor) {.exposeActive(editorContext, "vim-delete-word-back").} = - let selections = editor.applyMove(editor.selections, "vim-word", true, true, 1, which = SelectionCursor.Last.some) - editor.selections = editor.delete(selections) - editor.autoShowCompletions() - -proc vimDeleteLineBack(editor: TextDocumentEditor) {.exposeActive(editorContext, "vim-delete-line-back").} = - let selections = editor.applyMove(editor.selections, "vim-line", true, true, 1, which = SelectionCursor.Last.some) - editor.selections = editor.delete(selections) - editor.autoShowCompletions() - -proc vimSurround(editor: TextDocumentEditor, text: string) {.exposeActive(editorContext, "vim-surround").} = - let (left, right) = case text - of "(", ")": ("(", ")") - of "{", "}": ("{", "}") - of "[", "]": ("[", "]") - of "<", ">": ("<", ">") - else: - (text, text) - - var insertSelections: Selections = @[] - var insertTexts: seq[string] = @[] - for s in editor.selections: - let s = s.normalized - insertSelections.add s.first.toSelection - insertSelections.add editor.doMoveCursorColumn(s.last, 1).toSelection - insertTexts.add left - insertTexts.add right - - editor.addNextCheckpoint "insert" - let newSelections = editor.insertMulti(insertSelections, insertTexts) - if newSelections.len mod 2 != 0: - return - - editor.selections = collect: - for i in 0.. {newModes}" - - let oldMode = if oldModes.len > 0: - oldModes[0] - else: - "" - - if newModes.len == 0: - return - - let newMode = newModes[0] - - if not editor.getCurrentEventHandlers().contains("vim"): - return - - if newMode == "": - editor.setMode "vim.normal" - return - - if not newMode.startsWith("vim"): - return - - let recordModes = [ - "vim.visual", - "vim.visual-line", - "vim.insert", - ].toHashSet - - # infof"vim: handle mode change {oldMode} -> {newMode}" - if newMode == "vim.normal": - if not isReplayingCommands() and isRecordingCommands(".-temp"): - stopRecordingCommands(".-temp") - - if editor.getRevision > editor.vimState.revisionBeforeImplicitInsertMacro: - infof"Record implicit macro because document was modified" - let text = getRegisterText(".-temp") - setRegisterText(text, ".") - # else: - # infof"Don't record implicit macro because nothing was modified" - else: - if oldMode == "vim.normal" and newMode in recordModes: - editor.startRecordingCurrentCommandInPeriodMacro() - - editor.clearCurrentCommandHistory(retainLast=true) - - editor.vimState.selectLines = newMode == "vim.visual-line" - editor.vimState.cursorIncludeEol = newMode == "vim.insert" - editor.vimState.currentUndoCheckpoint = if newMode == "vim.insert": "word" else: "insert" - - case newMode - of "vim.normal": - editor.setConfig "text.inclusive-selection", false - editor.selections = editor.selections.mapIt(editor.vimClamp(it.last).toSelection) - editor.saveCurrentCommandHistory() - editor.hideCompletions() - - of "vim.insert": - editor.setConfig "text.inclusive-selection", false - - of "vim.visual": - editor.setConfig "text.inclusive-selection", true - - of "vim.visual-line": - editor.setConfig "text.inclusive-selection", false - - else: - editor.setConfig "text.inclusive-selection", false - -proc loadVimKeybindings*() {.expose("load-vim-keybindings").} = - let afterRestoreSessionHandle = addCallback proc(args: JsonNode): JsonNode = - let states = getSessionData[Table[string, JsonNode]]("vim.states") - for id in getAllEditors(): - if id.isTextEditor(editor): - try: - let filename = editor.getFileName() - if states.hasKey(filename): - let editorState = states[filename] - if editorState.hasKey("marks"): - let marks = editorState["marks"].jsonTo(Table[string, seq[Selection]]) - for name, selections in marks: - editor.vimState.unresolveMarks[name] = selections - except: - infof"Failed to restore marks for {editor}" - scriptSetCallback("after-restore-session", afterRestoreSessionHandle) - - let beforeSaveAppStateHandle = addCallback proc(args: JsonNode): JsonNode = - vimSaveState() - scriptSetCallback("before-save-app-state", beforeSaveAppStateHandle) diff --git a/config/keybindings_vim_like.nim b/config/keybindings_vim_like.nim deleted file mode 100644 index 15a208e05..000000000 --- a/config/keybindings_vim_like.nim +++ /dev/null @@ -1,300 +0,0 @@ -import plugin_runtime, keybindings_normal -import misc/[timer] - -proc loadVimLikeKeybindings*() {.expose("load-vim-like-keybindings").} = - loadNormalKeybindings() - - let t = startTimer() - defer: - infof"loadVimLikeKeybindings: {t.elapsed.ms} ms" - - info "Applying Vim-like keybindings" - - # clearCommands("editor.text") - # for id in getAllEditors(): - # if id.isTextEditor(editor): - # editor.setMode("") - - setModeChangedHandler proc(editor, oldMode, newMode: auto) = - if oldMode == "" and newMode != "": - editor.clearCurrentCommandHistory(retainLast=true) - elif oldMode != "" and newMode == "": - editor.saveCurrentCommandHistory() - - # Normal mode - setHandleInputs "editor.text", false - setOption "editor.text.cursor.movement.", "both" - setOption "editor.text.cursor.wide.", true - - # navigation - addTextCommand "", "", "move-cursor-line", 30 - addTextCommand "", "", "move-cursor-line", -30 - - addTextCommandBlock "", "gg": - let count = editor.getCommandCount - editor.selection = (count, 0).toSelection - editor.setCommandCount 0 - editor.scrollToCursor Last - - addTextCommand "", "G", "move-last", "file" - - addTextCommand "", "n", "select-move", "next-find-result", true - addTextCommand "", "N", "select-move", "prev-find-result", true - - addTextCommandBlock "", "*": editor.selection = editor.setSearchQueryFromMove("word") - - # editing - addTextCommand "", "x", "delete-right" - addTextCommand "", "u", "undo" - addTextCommand "", "U", "redo" - addTextCommand "", "p", "paste" - - addTextCommand "", "\\>", "indent" - addTextCommand "", "\\<", "unindent" - - addTextCommand "", ".", "run-saved-commands" - - # mode switches - addTextCommand "", "i", "set-mode", "insert" - addTextCommandBlock "", "I": - editor.moveFirst("line-no-indent") - editor.setMode("insert") - addTextCommandBlock "", "a": - editor.selections = editor.selections.mapIt(editor.doMoveCursorColumn(it.last, 1).toSelection) - editor.setMode("insert") - addTextCommandBlock "", "A": - editor.moveLast("line") - editor.setMode("insert") - - addTextCommand "", "v", "set-mode", "visual" - - addTextCommandBlock "", "s": - editor.selections = editor.delete(editor.selections) - editor.setMode("insert") - - for i in 0..9: - capture i: - proc updateCommandCountHelper(editor: TextDocumentEditor) = - editor.updateCommandCount i - # echo "updateCommandCount ", editor.getCommandCount - editor.setCommandCountRestore editor.getCommandCount - editor.setCommandCount 0 - - addTextCommand "", $i, updateCommandCountHelper - - addTextCommandBlock "", "d": - editor.setMode "move" - setOption "text.move-action", "delete-move" - setOption "text.move-next-mode", "" - setOption "text.move-command-count", editor.getCommandCount() - editor.setCommandCount 0 - - addTextCommand "", "D", "delete-move", "line" - - addTextCommandBlock "", "c": - editor.setMode "move" - setOption "text.move-action", "change-move" - setOption "text.move-next-mode", "insert" - setOption "text.move-command-count", editor.getCommandCount() - editor.setCommandCount 0 - - addTextCommandBlock "", "y": - editor.setMode "move" - setOption "text.move-action", "copy-move" - setOption "text.move-next-mode", "" - setOption "text.move-command-count", editor.getCommandCount() - editor.setCommandCount 0 - - addTextCommandBlock "", "f": - setOption("text.move-next-mode", editor.mode) - editor.setMode "move-to" - setOption "text.move-command-count", editor.getCommandCount() - editor.setCommandCount 0 - - addTextCommandBlock "", "t": - setOption("text.move-next-mode", editor.mode) - editor.setMode "move-before" - setOption "text.move-command-count", editor.getCommandCount() - editor.setCommandCount 0 - - addTextCommandBlock "", "D": - editor.deleteMove("line") - - addTextCommandBlock "", "C": - editor.deleteMove("line") - editor.setMode("insert") - - addTextCommandBlock "", "Y": - editor.selectMove("line") - editor.copy() - - addTextCommand "", "dl", "delete-move", "line-next" - addTextCommand "", "b", "move-last", "word-line-back" - addTextCommand "", "w", "move-last", "word-line" - addTextCommand "", "e", "move-last", "word-line" - addTextCommand "", "", "move-first", "line" - addTextCommand "", "", "move-last", "line" - addTextCommandBlock "", "o": - editor.moveCursorEnd() - editor.insertText("\n") - editor.setMode("insert") - addTextCommandBlock "", "O": - editor.moveCursorEnd() - editor.insertText("\n") - addTextCommandBlock "", "": - editor.setMode("") - editor.selection = editor.selection.last.toSelection - addTextCommandBlock "", "": - editor.setMode("") - editor.selection = editor.selection.last.toSelection - addTextCommandBlock "", "": - editor.setMode("") - editor.selection = editor.selection.last.toSelection - - # move mode - setHandleInputs "editor.text.move", false - setOption "editor.text.cursor.wide.move", true - setOption "editor.text.cursor.movement.move", "both" - - template addTextMoveCommand(keys: string, move: string): untyped = - addTextCommand "move", keys, "apply-move", move, false - addTextCommand "move-inside", keys, "apply-move", move, true - - addTextMoveCommand "w", "word-line" - addTextMoveCommand "W", "word" - addTextMoveCommand "b", "word-line-back" - addTextMoveCommand "B", "word-back" - addTextMoveCommand "p", "paragraph" - addTextMoveCommand "F", "file" - addTextMoveCommand "\"", "\"" - addTextMoveCommand "'", "'" - addTextMoveCommand "(", "(" - addTextMoveCommand ")", "(" - addTextMoveCommand "[", "[" - addTextMoveCommand "]", "[" - addTextMoveCommand "}", "}" - - addTextCommand "move", "d", "apply-move", "line-next", true - addTextCommand "move-inside", "d", "apply-move", "line-next", true - addTextCommand "move", "y", "apply-move", "line-next", true - addTextCommand "move-inside", "y", "apply-move", "line-next", true - - addTextCommandBlock "move", "f": - editor.setMode "move-to" - setOption "text.move-command-count", editor.getCommandCount() - editor.setCommandCount 0 - - addTextCommandBlock "move", "t": - editor.setMode "move-before" - setOption "text.move-command-count", editor.getCommandCount() - editor.setCommandCount 0 - - # move-to mode - setHandleActions "editor.text.move-to", false - setTextInputHandler "move-to", proc(editor: TextDocumentEditor, input: string): bool = - editor.setMode getOption[string]("text.move-next-mode") - if getOption[string]("text.move-action") != "": - editor.setCommandCount getOption[int]("text.move-command-count") - var args = newJArray() - args.add newJString("move-to " & input) - discard editor.runAction(getOption[string]("text.move-action"), args) - setOption[string]("text.move-action", "") - else: - editor.moveCursorTo(input) - return true - setOption "editor.text.cursor.wide.move-to", true - setOption "editor.text.cursor.movement.move-to", "both" - - # move-before mode - setHandleActions "editor.text.move-before", false - setTextInputHandler "move-before", proc(editor: TextDocumentEditor, input: string): bool = - editor.setMode getOption[string]("text.move-next-mode") - if getOption[string]("text.move-action") != "": - editor.setCommandCount getOption[int]("text.move-command-count") - var args = newJArray() - args.add newJString("move-before " & input) - discard editor.runAction(getOption[string]("text.move-action"), args) - setOption[string]("text.move-action", "") - else: - editor.moveCursorBefore(input) - return true - setOption "editor.text.cursor.wide.move-before", true - setOption "editor.text.cursor.movement.move-before", "both" - - # Insert mode - setHandleInputs "editor.text.insert", true - setOption "editor.text.cursor.wide.insert", false - addTextCommand "insert", "", "insert-text", "\n" - addTextCommand "insert", "", "insert-text", " " - - # Visual mode - setHandleInputs "editor.text.visual", false - setOption "editor.text.cursor.wide.visual", true - setOption "editor.text.cursor.movement.visual", "last" - addTextCommand "visual", "y", "copy" - - addTextCommandBlock "visual", "i": - editor.setMode("move-inside") - setOption("text.move-action", "select-move") - setOption("text.move-next-mode", "visual") - - addTextCommandBlock "visual", "d": - editor.selections = editor.delete(editor.selections) - editor.setMode("") - editor.scrollToCursor(Last) - editor.updateTargetColumn(Last) - - addTextCommandBlock "visual", "c": - editor.selections = editor.delete(editor.selections) - editor.setMode("insert") - editor.scrollToCursor(Last) - editor.updateTargetColumn(Last) - - addTextCommandBlock "visual", "d": - editor.selections = editor.delete(editor.selections) - editor.setMode("") - editor.scrollToCursor(Last) - editor.updateTargetColumn(Last) - - addTextCommandBlock "visual", "c": - editor.selections = editor.delete(editor.selections) - editor.setMode("insert") - editor.scrollToCursor(Last) - editor.updateTargetColumn(Last) - - when enableAst: - setHandleInputs "editor.model", false - setOption "editor.model.cursor.wide.", true - - addCommand("editor.model", "b", "move-cursor-left-cell") - addCommand("editor.model", "w", "move-cursor-right-cell") - addCommand("editor.model", "u", "undo") - addCommand("editor.model", "U", "redo") - addModelCommand "", "}", "goto-next-node-of-class", "EmptyLine" - addModelCommand "", "{", "goto-prev-node-of-class", "EmptyLine" - - addModelCommandBlock "", "": - editor.setMode("") - # editor.selection = editor.selection.last.toSelection - addModelCommandBlock "", "": - editor.setMode("") - # editor.selection = editor.selection.last.toSelection - addModelCommandBlock "", "": - editor.setMode("") - # editor.selection = editor.selection.last.toSelection - - addModelCommand "", "i", "set-mode", "insert" - addModelCommandBlock "", "I": - editor.moveCursorLineStart(false) - editor.setMode("insert") - addModelCommandBlock "", "a": - # editor.selections = editor.selections.mapIt(editor.doMoveCursorColumn(it.last, 1).toSelection) - editor.setMode("insert") - addModelCommandBlock "", "A": - editor.moveCursorLineEnd(false) - editor.setMode("insert") - - # Insert mode - setHandleInputs "editor.model.insert", true - setOption "editor.model.cursor.wide.insert", false - addModelCommand "insert", "", "insert-text-at-cursor", " " diff --git a/config/settings-vim.json b/config/settings-vim.json index a5aa50a17..12efe2f8a 100644 --- a/config/settings-vim.json +++ b/config/settings-vim.json @@ -19,9 +19,9 @@ "editor.text.handle-inputs": true, "vim.insert.handle-inputs": true, "vim.replace.handle-inputs": true, - "vim.replace.input-handler-command": "vim-replace-input-handler", + "vim.replace.input-handler-command": "vim.replace-input-handler", "vim.insert-register.handle-inputs": true, - "vim.insert-register.input-handler-command": "vim-insert-register-input-handler", + "vim.insert-register.input-handler-command": "vim.insert-register-input-handler", "editor.text.temp.choose-cursor.handle-actions": true, "editor.text.temp.choose-cursor.handle-inputs": true, @@ -38,7 +38,7 @@ "terminal.insert.handle-keys": true, }, - "text.mode-changed-handler-command": "vim-mode-changed-handler", + "text.mode-changed-handler-command": "vim.mode-changed-handler", "text.inclusive-selection": false, "editor.text.cursor.movement.": "last", diff --git a/config/settings.json b/config/settings.json index 16022e787..ee3c550cb 100644 --- a/config/settings.json +++ b/config/settings.json @@ -257,12 +257,12 @@ ], "line-comment": "#", "+search-regexes": { - "goto-definition": "((proc|method|func|template|macro|iterator|type|declare|declareSettings|^var|^let) [[0]]\\b)|(\\b[[0]]\\b.*?= (object|ref|ptr|array|set|tuple|enum|distinct|proc))|((type | +)\\b[[0]]\\b\\*?( \\{.*?)?:.+[^,;]$)", + "goto-definition": "((proc|method|func|converter|template|macro|iterator|type|declare|declareSettings|^var|^let) [[0]]\\b)|(\\b[[0]]\\b.*?= (object|ref|ptr|array|set|tuple|enum|distinct|proc))|((type | +)\\b[[0]]\\b\\*?( \\{.*?)?:.+[^,;]$)", "goto-implementation": "object of [[0]]", - "symbols": "((proc|method|func|template|macro|iterator|type|declare|declareSettings) (\\b([a-zA-Z0-9_]+\\b)|(`.+?`)))|((\\b([a-zA-Z0-9_]+)|(`.+?`)\\b).*?= (object|ref|ptr|array|set|tuple|enum|distinct|proc))", + "symbols": "((proc|method|func|converter|template|macro|iterator|type|declare|declareSettings) (\\b([a-zA-Z0-9_]+\\b)|(`.+?`)))|((\\b([a-zA-Z0-9_]+)|(`.+?`)\\b).*?= (object|ref|ptr|array|set|tuple|enum|distinct|proc))", "workspace-symbols-by-kind": { "Class": "(\\b([a-zA-Z0-9_]+)|(`.+?`)\\b).*?= (object|ref|ptr|array|set|tuple|distinct)", - "Function": "((proc|func|template|macro|iterator|type|declare|declareSettings) (\\b([a-zA-Z0-9_]+\\b)|(`.+?`)))|((\\b([a-zA-Z0-9_]+)|(`.+?`)\\b).*?= (proc))", + "Function": "((proc|func|converter|template|macro|iterator|type|declare|declareSettings) (\\b([a-zA-Z0-9_]+\\b)|(`.+?`)))|((\\b([a-zA-Z0-9_]+)|(`.+?`)\\b).*?= (proc))", "Method": "((method) (\\b([a-zA-Z0-9_]+\\b)|(`.+?`)))", "Enum": "(\\b([a-zA-Z0-9_]+)|(`.+?`)\\b).*?= (enum)" } diff --git a/config/wasm/keybindings_plugin.wasm b/config/wasm/keybindings_plugin.wasm index 588194d08..e934140fb 100644 Binary files a/config/wasm/keybindings_plugin.wasm and b/config/wasm/keybindings_plugin.wasm differ diff --git a/docs/settings.gen.md b/docs/settings.gen.md index 79ac635b6..97c42e8cf 100644 --- a/docs/settings.gen.md +++ b/docs/settings.gen.md @@ -74,8 +74,6 @@ For examples and default values see [here](../config/settings.json) | `text.indent-detection.samples` | int | 50 | How many indent characters to process when detecting the indent style. Increase this if it fails for files which start with many unindented lines. | | `text.indent-detection.timeout` | int | 20 | Max number of milliseconds to spend trying to detect the indent style. | | `text.inlay-hints-enabled` | bool | true | Whether inlay hints are enabled. | -| `text.inline-images.enable` | bool | false | Add colored inlay hints before any occurance of a string representing a color. Color detection is configured per language in `text.color-highlight.{language-id}.` | -| `text.inline-images.regex` | regex | "#([0-9a-fA-F]{6})\|#([0-9a-fA-F]{8})" | Regex used to find colors. Use capture groups to match one or more numbers within a color definition, depending on the kind. | | `text.line-comment` | string \| null | null | String which starts a line comment | | `text.mode-changed-handler-command` | string | "" | Command to execute when the mode of the text editor changes | | `text.modes` | string[] | ["editor.text"] | List of input modes text editors. | diff --git a/nev.nimble b/nev.nimble index 6e72d1217..351c5ec7e 100644 --- a/nev.nimble +++ b/nev.nimble @@ -34,12 +34,11 @@ requires "chronos >= 4.0.3" requires "https://github.com/Nimaoth/fsnotify >= 0.1.6" requires "https://github.com/Nimaoth/ws >= 0.5.0" requires "https://github.com/Nimaoth/windy >= 0.0.5" -requires "https://github.com/Nimaoth/wasm3 >= 0.1.17" requires "https://github.com/Nimaoth/lrucache.nim >= 1.1.4" requires "https://github.com/Nimaoth/boxy#bfc8665" requires "https://github.com/Nimaoth/nimtreesitter-api >= 0.1.21" requires "https://github.com/Nimaoth/nimwasmtime#415a252" -requires "https://github.com/Nimaoth/nimsumtree#47f7208" +requires "https://github.com/Nimaoth/nimsumtree#2a6e442" requires "https://github.com/Nimaoth/zippy >= 0.10.17" requires "libssh2 >= 0.1.9" requires "ssh2 >= 0.1.9" @@ -184,6 +183,10 @@ proc buildPlugin(name: string) = task buildWasmModule, "": buildPlugin("test_plugin") # buildPlugin("pong") + # buildPlugin("vim") + +task buildVimPlugin, "": + buildPlugin("vim") task buildWasmModule1, "": withDir "plugins/test_plugin_1": diff --git a/nimble.lock b/nimble.lock index b44d08573..b18205672 100644 --- a/nimble.lock +++ b/nimble.lock @@ -310,16 +310,6 @@ "sha1": "8bccb6b02295a85eab30aeb8c411927680ca9192" } }, - "micros": { - "version": "0.1.16", - "vcsRevision": "4dfeac6a47ba8b6287081b048158981a07832063", - "url": "https://github.com/beef331/micros/", - "downloadMethod": "git", - "dependencies": [], - "checksums": { - "sha1": "9452155bea9280923b9a5654037eb92513ec8e7c" - } - }, "nimgen": { "version": "0.5.4", "vcsRevision": "e6697aabbe36e42e4dd261cfd0b8a8be16f6f342", @@ -348,12 +338,12 @@ }, "nimsumtree": { "version": "0.5.6", - "vcsRevision": "47f7208faeeb8ee6a9c6913af7be40ba494857df", + "vcsRevision": "2a6e442a7fd3ad58975810ff266ddf2887b5d78c", "url": "https://github.com/Nimaoth/nimsumtree", "downloadMethod": "git", "dependencies": [], "checksums": { - "sha1": "83cdadd2e88aabc7e7edbc26dd0d9b7b370c612d" + "sha1": "3a62d7ebfac045adeda6cadfc883b8b96ff58a89" } }, "nimtreesitter": { @@ -432,18 +422,6 @@ "sha1": "fa636c9852fbf196df05baa1c9a0c976f533150d" } }, - "wasm3": { - "version": "0.1.17", - "vcsRevision": "e056b725ec1fad4e35e922d1602b41e970a06d3d", - "url": "https://github.com/Nimaoth/wasm3", - "downloadMethod": "git", - "dependencies": [ - "micros" - ], - "checksums": { - "sha1": "fd5cc6b4e8dc6cb1f6f2fe45cbc50cc0adc5363e" - } - }, "ws": { "version": "0.5.0", "vcsRevision": "7f39f987232cd839eb126488855da107c331f140", diff --git a/plugin_api/v0/api.nim b/plugin_api/v0/api.nim index 1b380fa80..8e2cdbb53 100644 --- a/plugin_api/v0/api.nim +++ b/plugin_api/v0/api.nim @@ -4,6 +4,9 @@ export wit_types, wit_runtime import async export async +# todo: remove this eventually +from "../../src/scripting_api.nim" as sca import nil + const pluginWorld {.strdefine.} = "plugin" when defined(witRebuild): @@ -28,10 +31,20 @@ proc emscripten_stack_init() {.importc.} proc NimMain() {.importc.} +######### todo: move these to wit_types + +proc `==`*(a, b: WitString): bool = + if a.len != b.len: + return false + return a.toOpenArray() == b.toOpenArray() + +template ws*(s: WitString): WitString = s + ############################ exported functions ############################ type CommandHandler = proc(data: uint32, args: WitString): WitString {.cdecl.} type ChannelUpdateHandler = proc(data: uint32, closed: bool): ChannelListenResponse {.cdecl, raises: [].} +type MoveHandler = proc(data: uint32, text: sink Rope, selections: openArray[Selection], count: int, includeEol: bool): seq[Selection] {.cdecl, raises: [].} proc initPlugin() = emscripten_stack_init() @@ -70,6 +83,11 @@ proc notifyTasksComplete(tasks: WitList[tuple[task: uint64, canceled: bool]]) = for (task, canceled) in tasks: notifyTaskComplete(task, canceled) +proc handleMove(fun: uint32; data: uint32; text: uint32; selections: WitList[Selection]; count: int32; eol: bool): WitList[Selection] = + var text = Rope(handle: text.int32 + 1) + let fun = cast[MoveHandler](fun) + return stackWitList(fun(data, text.ensureMove, selections.toOpenArray(), count.int, eol)) + ############################ nice wrappers around the raw api ############################ proc wl*[T](): WitList[T] = WitList[T].default() @@ -87,6 +105,95 @@ when pluginWorld == "plugin": except: return def + proc getSetting*(editor: TextEditor, name: string, T: typedesc): T = + try: + return getSettingRaw(editor, name).parseJson().jsonTo(T) + except: + return T.default + + proc getSetting*[T](editor: TextEditor, name: string, def: T): T = + try: + return ($getSettingRaw(editor, ws(name))).parseJson().jsonTo(T) + except: + return def + + proc setSetting*[T](name: string, value: T) = + try: + setSettingRaw(name.ws, stackWitString($value.toJson)) + except: + discard + + proc setSetting*[T](editor: TextEditor, name: string, value: T) = + try: + editor.setSettingRaw(name.ws, stackWitString($value.toJson)) + except: + discard + + func `$`*(cursor: Cursor): string = + return $cursor.line & ":" & $cursor.column + + func `$`*(selection: Selection): string = + return $selection.first & "-" & $selection.last + + func `<`*(a: Cursor, b: Cursor): bool = + ## Returns true if the cursor `a` comes before `b` + if a.line < b.line: + return true + elif a.line == b.line and a.column < b.column: + return true + else: + return false + + func `<=`*(a: Cursor, b: Cursor): bool = + return a == b or a < b + + func min*(a: Cursor, b: Cursor): Cursor = + if a < b: + return a + return b + + func max*(a: Cursor, b: Cursor): Cursor = + if a >= b: + return a + return b + + func isBackwards*(selection: Selection): bool = + ## Returns true if the first cursor of the selection is after the second cursor + return selection.first > selection.last + + func normalized*(selection: Selection): Selection = + ## Returns the normalized selection, i.e. where first < last. + ## Switches first and last if backwards. + if selection.isBackwards: + return Selection(first: selection.last, last: selection.first) + else: + return selection + + func `in`*(a: Cursor, b: Selection): bool = + ## Returns true if the cursor is contained within the selection + let b = b.normalized + return a >= b.first and a <= b.last + + func reverse*(selection: Selection): Selection = Selection(first: selection.last, last: selection.first) + + func isEmpty*(selection: Selection): bool = selection.first == selection.last + func allEmpty*(selections: openArray[Selection]): bool = selections.allIt(it.isEmpty) + + func contains*(selection: Selection, cursor: Cursor): bool = (cursor >= selection.first and cursor <= selection.last) + func contains*(selection: Selection, other: Selection): bool = (other.first >= selection.first and other.last <= selection.last) + + func contains*(self: openArray[Selection], cursor: Cursor): bool = self.`any` (s) => s.contains(cursor) + func contains*(self: openArray[Selection], other: Selection): bool = self.`any` (s) => s.contains(other) + + func `or`*(a: Selection, b: Selection): Selection = + let an = a.normalized + let bn = b.normalized + return Selection(first: min(an.first, bn.first), last: max(an.last, bn.last)) + + converter toCursor*(c: (int, int)): Cursor = Cursor(line: c[0].int32, column: c[1].int32) + converter toCursor*(c: (int32, int32)): Cursor = Cursor(line: c[0], column: c[1]) + converter toSelection*(c: tuple[line, column: int]): Selection = Selection(first: c.toCursor, last: c.toCursor) + converter toSelection*(c: tuple[first, last: Cursor]): Selection = Selection(first: c.first, last: c.last) proc toSelection*(c: Cursor): Selection = Selection(first: c, last: c) proc defineCommand*(name: WitString; active: bool; docs: WitString; params: WitList[(WitString, WitString)]; returntype: WitString; context: WitString; data: uint32; handler: CommandHandler) = @@ -95,6 +202,46 @@ when pluginWorld == "plugin": proc addModeChangedHandler*(fun: proc(old: WitString, new: WitString) {.cdecl.}) = discard addModeChangedHandler(cast[uint32](fun)) + proc selections*(editor: TextEditor): WitList[Selection] = + return editor.getSelections() + + proc setSelections*(editor: TextEditor, s: openArray[Selection]) = + editor.setSelections(@@s) + + proc lineCount*(editor: TextEditor): int = + editor.content.lines.int + + proc setMode*(editor: TextEditor, mode: string) = + editor.setMode(ws(mode), exclusive = true) + + proc applyMove*(editor: TextEditor, cursor: Cursor, move: string, count: int = 1, wrap: bool = true, includeEol: bool = true): Selection = + return editor.applyMove(cursor.toSelection, move.ws, count, wrap, includeEol)[0] + + proc scrollToCursor*(editor: TextEditor) = + editor.scrollToCursor(ScrollBehaviour.none, 0.5) + + proc addCustomTextMove*(name: string, move: MoveHandler) = + defineMove(name.ws, cast[uint32](move), 0) + + proc multiMove*(editor: TextEditor, selections: WitList[Selection], move: WitString|string): WitList[Selection] = + editor.multiMove(selections, ws(move), 0, false, true) + + proc multiMove*(editor: TextEditor, selections: openArray[Selection], move: WitString|string): WitList[Selection] = + editor.multiMove(@@selections, ws(move), 0, false, true) + +func toSelection*(cursor: Cursor, default: Selection, which: sca.SelectionCursor): Selection = + case which + of sca.SelectionCursor.Config: return default + of sca.SelectionCursor.Both: return (cursor, cursor).toSelection + of sca.SelectionCursor.First: return (cursor, default.last).toSelection + of sca.SelectionCursor.Last: return (default.first, cursor).toSelection + of sca.SelectionCursor.LastToFirst: return (default.last, cursor).toSelection + +proc charAt*(rope: Rope, cursor: Cursor): char = rope.byteAt(cursor).char +proc slice*(rope: Rope, a: Natural, b: Natural): Rope = rope.slice(a.int64, b.int64, inclusive = false) +proc `[]`*(rope: Rope, a: Natural, b: Natural): Rope = rope.slice(a.int64, b.int64, inclusive = false) +proc `[]`*(rope: Rope, s: Selection): Rope = rope.sliceSelection(s, inclusive = false) + proc asEditor*(editor: TextEditor): Editor = Editor(id: editor.id) proc asDocument*(document: TextDocument): Document = Document(id: document.id) diff --git a/plugin_api/v0/commands.nim b/plugin_api/v0/commands.nim index 7debb28e3..528d73f69 100644 --- a/plugin_api/v0/commands.nim +++ b/plugin_api/v0/commands.nim @@ -100,3 +100,9 @@ proc runCommand*(name: WitString; arguments: WitString): Result[WitString, var tempErr: CommandError tempErr = cast[CommandError](cast[ptr int32](retArea[4].addr)[]) result = results.Result[WitString, CommandError].err(tempErr) + +proc commandsExitCommandLineImported(): void {. + wasmimport("exit-command-line", "nev:plugins/commands").} +proc exitCommandLine*(): void {.nodestroy.} = + ## Close the command line. + commandsExitCommandLineImported() diff --git a/plugin_api/v0/editor.nim b/plugin_api/v0/editor.nim index 888a1048d..b42a76190 100644 --- a/plugin_api/v0/editor.nim +++ b/plugin_api/v0/editor.nim @@ -12,12 +12,15 @@ import import types -proc editorActiveEditorImported(a0: int32): void {. +proc editorActiveEditorImported(a0: uint8; a1: int32): void {. wasmimport("active-editor", "nev:plugins/editor").} -proc activeEditor*(): Option[Editor] {.nodestroy.} = +proc activeEditor*(options: ActiveEditorFlags): Option[Editor] {.nodestroy.} = ## Returns a handle for the currently active text editor. - var retArea: array[16, uint8] - editorActiveEditorImported(cast[int32](retArea[0].addr)) + var + retArea: array[16, uint8] + arg0: uint8 + arg0 = cast[uint8](options) + editorActiveEditorImported(arg0, cast[int32](retArea[0].addr)) if cast[ptr int64](retArea[0].addr)[] != 0: var temp: Editor temp.id = convert(cast[ptr uint64](retArea[8].addr)[], uint64) diff --git a/plugin_api/v0/layout.nim b/plugin_api/v0/layout.nim index aaddebba8..c3c01326a 100644 --- a/plugin_api/v0/layout.nim +++ b/plugin_api/v0/layout.nim @@ -62,3 +62,16 @@ proc focus*(slot: WitString): void {.nodestroy.} = arg0 = 0.int32 arg1 = cast[int32](slot.len) layoutFocusImported(arg0, arg1) + +proc layoutCloseActiveViewImported(a0: bool; a1: bool): void {. + wasmimport("close-active-view", "nev:plugins/layout").} +proc closeActiveView*(closeOpenPopup: bool; restoreHidden: bool): void {. + nodestroy.} = + ## Close the active view. If 'close-open-popup' is set and a popup is open then the popup will be closed. + ## If 'restore-hidden' is true then the view will be replaced by a hidden view, otherwise the slot will be removed from the layout.. + var + arg0: bool + arg1: bool + arg0 = closeOpenPopup + arg1 = restoreHidden + layoutCloseActiveViewImported(arg0, arg1) diff --git a/plugin_api/v0/plugin_api_guest.nim b/plugin_api/v0/plugin_api_guest.nim index 36a68034e..207aae7d1 100644 --- a/plugin_api/v0/plugin_api_guest.nim +++ b/plugin_api/v0/plugin_api_guest.nim @@ -27,6 +27,12 @@ import export types +import + registers + +export + registers + import text_document @@ -150,3 +156,31 @@ proc notifyTaskCompleteExported(a0: uint64; a1: bool): void {. task = convert(a0, uint64) canceled = a1.bool notifyTaskComplete(task, canceled) + +proc handleMove(fun: uint32; data: uint32; text: uint32; + selections: WitList[Selection]; count: int32; eol: bool): WitList[ + Selection] +var handleMoveRetArea: array[28, uint8] +proc handleMoveExported(a0: uint32; a1: uint32; a2: uint32; a3: int32; + a4: int32; a5: int32; a6: bool): int32 {. + wasmexport("handle-move", "nev:plugins/guest").} = + var + fun: uint32 + data: uint32 + text: uint32 + selections: WitList[Selection] + count: int32 + eol: bool + fun = convert(a0, uint32) + data = convert(a1, uint32) + text = convert(a2, uint32) + selections = wl(cast[ptr typeof(selections[0])](a3), a4) + count = convert(a5, int32) + eol = a6.bool + let res = handleMove(fun, data, text, selections, count, eol) + if res.len > 0: + cast[ptr int32](handleMoveRetArea[0].addr)[] = cast[int32](res[0].addr) + else: + cast[ptr int32](handleMoveRetArea[0].addr)[] = 0.int32 + cast[ptr int32](handleMoveRetArea[4].addr)[] = cast[int32](res.len) + cast[int32](handleMoveRetArea[0].addr) diff --git a/plugin_api/v0/registers.nim b/plugin_api/v0/registers.nim new file mode 100644 index 000000000..7713ef5ea --- /dev/null +++ b/plugin_api/v0/registers.nim @@ -0,0 +1,112 @@ + +{.push, hint[DuplicateModuleImport]: off.} +import + std / [options] + +from std / unicode import Rune + +import + results, wit_types, wit_runtime, wit_guest + +{.pop.} +proc registersIsReplayingCommandsImported(): bool {. + wasmimport("is-replaying-commands", "nev:plugins/registers").} +proc isReplayingCommands*(): bool {.nodestroy.} = + ## todo + let res = registersIsReplayingCommandsImported() + result = res.bool + +proc registersIsRecordingCommandsImported(a0: int32; a1: int32): bool {. + wasmimport("is-recording-commands", "nev:plugins/registers").} +proc isRecordingCommands*(register: WitString): bool {.nodestroy.} = + ## todo + var + arg0: int32 + arg1: int32 + if register.len > 0: + arg0 = cast[int32](register[0].addr) + else: + arg0 = 0.int32 + arg1 = cast[int32](register.len) + let res = registersIsRecordingCommandsImported(arg0, arg1) + result = res.bool + +proc registersSetRegisterTextImported(a0: int32; a1: int32; a2: int32; a3: int32): void {. + wasmimport("set-register-text", "nev:plugins/registers").} +proc setRegisterText*(text: WitString; register: WitString): void {.nodestroy.} = + ## todo + var + arg0: int32 + arg1: int32 + arg2: int32 + arg3: int32 + if text.len > 0: + arg0 = cast[int32](text[0].addr) + else: + arg0 = 0.int32 + arg1 = cast[int32](text.len) + if register.len > 0: + arg2 = cast[int32](register[0].addr) + else: + arg2 = 0.int32 + arg3 = cast[int32](register.len) + registersSetRegisterTextImported(arg0, arg1, arg2, arg3) + +proc registersGetRegisterTextImported(a0: int32; a1: int32; a2: int32): void {. + wasmimport("get-register-text", "nev:plugins/registers").} +proc getRegisterText*(register: WitString): WitString {.nodestroy.} = + ## todo + var + retArea: array[8, uint8] + arg0: int32 + arg1: int32 + if register.len > 0: + arg0 = cast[int32](register[0].addr) + else: + arg0 = 0.int32 + arg1 = cast[int32](register.len) + registersGetRegisterTextImported(arg0, arg1, cast[int32](retArea[0].addr)) + result = ws(cast[ptr char](cast[ptr int32](retArea[0].addr)[]), + cast[ptr int32](retArea[4].addr)[]) + +proc registersStartRecordingCommandsImported(a0: int32; a1: int32): void {. + wasmimport("start-recording-commands", "nev:plugins/registers").} +proc startRecordingCommands*(register: WitString): void {.nodestroy.} = + ## todo + var + arg0: int32 + arg1: int32 + if register.len > 0: + arg0 = cast[int32](register[0].addr) + else: + arg0 = 0.int32 + arg1 = cast[int32](register.len) + registersStartRecordingCommandsImported(arg0, arg1) + +proc registersStopRecordingCommandsImported(a0: int32; a1: int32): void {. + wasmimport("stop-recording-commands", "nev:plugins/registers").} +proc stopRecordingCommands*(register: WitString): void {.nodestroy.} = + ## todo + var + arg0: int32 + arg1: int32 + if register.len > 0: + arg0 = cast[int32](register[0].addr) + else: + arg0 = 0.int32 + arg1 = cast[int32](register.len) + registersStopRecordingCommandsImported(arg0, arg1) + +proc registersReplayCommandsImported(a0: int32; a1: int32): void {. + wasmimport("replay-commands", "nev:plugins/registers").} +proc replayCommands*(register: WitString): void {.nodestroy.} = + ## todo + var + arg0: int32 + arg1: int32 + if register.len > 0: + arg0 = cast[int32](register[0].addr) + else: + arg0 = 0.int32 + arg1 = cast[int32](register.len) + registersReplayCommandsImported(arg0, arg1) diff --git a/plugin_api/v0/text_editor.nim b/plugin_api/v0/text_editor.nim index f32a99591..e92b15986 100644 --- a/plugin_api/v0/text_editor.nim +++ b/plugin_api/v0/text_editor.nim @@ -15,12 +15,25 @@ import import commands -proc textEditorActiveTextEditorImported(a0: int32): void {. +type + ScrollBehaviour* = enum + CenterAlways = "center-always", CenterOffscreen = "center-offscreen", + CenterMargin = "center-margin", ScrollToMargin = "scroll-to-margin", + TopOfScreen = "top-of-screen" + ScrollSnapBehaviour* = enum + Never = "never", Always = "always", + MinDistanceOffscreen = "min-distance-offscreen", + MinDistanceCenter = "min-distance-center" +proc textEditorActiveTextEditorImported(a0: uint8; a1: int32): void {. wasmimport("active-text-editor", "nev:plugins/text-editor").} -proc activeTextEditor*(): Option[TextEditor] {.nodestroy.} = +proc activeTextEditor*(options: ActiveEditorFlags): Option[TextEditor] {. + nodestroy.} = ## Returns a handle for the currently active text editor. - var retArea: array[16, uint8] - textEditorActiveTextEditorImported(cast[int32](retArea[0].addr)) + var + retArea: array[16, uint8] + arg0: uint8 + arg0 = cast[uint8](options) + textEditorActiveTextEditorImported(arg0, cast[int32](retArea[0].addr)) if cast[ptr int64](retArea[0].addr)[] != 0: var temp: TextEditor temp.id = convert(cast[ptr uint64](retArea[8].addr)[], uint64) @@ -104,6 +117,479 @@ proc command*(editor: TextEditor; name: WitString; arguments: WitString): Result tempErr = cast[CommandError](cast[ptr int32](retArea[4].addr)[]) result = results.Result[WitString, CommandError].err(tempErr) +proc textEditorRecordCurrentCommandImported(a0: uint64; a1: int32; a2: int32): void {. + wasmimport("record-current-command", "nev:plugins/text-editor").} +proc recordCurrentCommand*(editor: TextEditor; registers: WitList[WitString]): void {. + nodestroy.} = + ## todo + var + arg0: uint64 + arg1: int32 + arg2: int32 + arg0 = editor.id + if registers.len > 0: + arg1 = cast[int32](registers[0].addr) + else: + arg1 = 0.int32 + arg2 = cast[int32](registers.len) + textEditorRecordCurrentCommandImported(arg0, arg1, arg2) + +proc textEditorClearCurrentCommandHistoryImported(a0: uint64; a1: bool): void {. + wasmimport("clear-current-command-history", "nev:plugins/text-editor").} +proc clearCurrentCommandHistory*(editor: TextEditor; retainLast: bool): void {. + nodestroy.} = + ## todo + var + arg0: uint64 + arg1: bool + arg0 = editor.id + arg1 = retainLast + textEditorClearCurrentCommandHistoryImported(arg0, arg1) + +proc textEditorSaveCurrentCommandHistoryImported(a0: uint64): void {. + wasmimport("save-current-command-history", "nev:plugins/text-editor").} +proc saveCurrentCommandHistory*(editor: TextEditor): void {.nodestroy.} = + ## todo + var arg0: uint64 + arg0 = editor.id + textEditorSaveCurrentCommandHistoryImported(arg0) + +proc textEditorHideCompletionsImported(a0: uint64): void {. + wasmimport("hide-completions", "nev:plugins/text-editor").} +proc hideCompletions*(editor: TextEditor): void {.nodestroy.} = + ## todo + var arg0: uint64 + arg0 = editor.id + textEditorHideCompletionsImported(arg0) + +proc textEditorScrollToCursorImported(a0: uint64; a1: int8; a2: int8; + a3: float32): void {. + wasmimport("scroll-to-cursor", "nev:plugins/text-editor").} +proc scrollToCursor*(editor: TextEditor; behaviour: Option[ScrollBehaviour]; + relativePosition: float32): void {.nodestroy.} = + ## todo + var + arg0: uint64 + arg1: int8 + arg2: int8 + arg3: float32 + arg0 = editor.id + arg1 = behaviour.isSome.int8 + if behaviour.isSome: + arg2 = cast[int8](behaviour.get) + arg3 = relativePosition + textEditorScrollToCursorImported(arg0, arg1, arg2, arg3) + +proc textEditorSetNextSnapBehaviourImported(a0: uint64; a1: int8): void {. + wasmimport("set-next-snap-behaviour", "nev:plugins/text-editor").} +proc setNextSnapBehaviour*(editor: TextEditor; behaviour: ScrollSnapBehaviour): void {. + nodestroy.} = + ## todo + var + arg0: uint64 + arg1: int8 + arg0 = editor.id + arg1 = cast[int8](behaviour) + textEditorSetNextSnapBehaviourImported(arg0, arg1) + +proc textEditorUpdateTargetColumnImported(a0: uint64): void {. + wasmimport("update-target-column", "nev:plugins/text-editor").} +proc updateTargetColumn*(editor: TextEditor): void {.nodestroy.} = + ## todo + var arg0: uint64 + arg0 = editor.id + textEditorUpdateTargetColumnImported(arg0) + +proc textEditorGetUsageImported(a0: uint64; a1: int32): void {. + wasmimport("get-usage", "nev:plugins/text-editor").} +proc getUsage*(editor: TextEditor): WitString {.nodestroy.} = + ## todo + var + retArea: array[8, uint8] + arg0: uint64 + arg0 = editor.id + textEditorGetUsageImported(arg0, cast[int32](retArea[0].addr)) + result = ws(cast[ptr char](cast[ptr int32](retArea[0].addr)[]), + cast[ptr int32](retArea[4].addr)[]) + +proc textEditorGetRevisionImported(a0: uint64): int32 {. + wasmimport("get-revision", "nev:plugins/text-editor").} +proc getRevision*(editor: TextEditor): int32 {.nodestroy.} = + ## todo + var arg0: uint64 + arg0 = editor.id + let res = textEditorGetRevisionImported(arg0) + result = convert(res, int32) + +proc textEditorSetModeImported(a0: uint64; a1: int32; a2: int32; a3: bool): void {. + wasmimport("set-mode", "nev:plugins/text-editor").} +proc setMode*(editor: TextEditor; mode: WitString; exclusive: bool): void {. + nodestroy.} = + ## todo + var + arg0: uint64 + arg1: int32 + arg2: int32 + arg3: bool + arg0 = editor.id + if mode.len > 0: + arg1 = cast[int32](mode[0].addr) + else: + arg1 = 0.int32 + arg2 = cast[int32](mode.len) + arg3 = exclusive + textEditorSetModeImported(arg0, arg1, arg2, arg3) + +proc textEditorModeImported(a0: uint64; a1: int32): void {. + wasmimport("mode", "nev:plugins/text-editor").} +proc mode*(editor: TextEditor): WitString {.nodestroy.} = + ## todo + var + retArea: array[8, uint8] + arg0: uint64 + arg0 = editor.id + textEditorModeImported(arg0, cast[int32](retArea[0].addr)) + result = ws(cast[ptr char](cast[ptr int32](retArea[0].addr)[]), + cast[ptr int32](retArea[4].addr)[]) + +proc textEditorModesImported(a0: uint64; a1: int32): void {. + wasmimport("modes", "nev:plugins/text-editor").} +proc modes*(editor: TextEditor): WitList[WitString] {.nodestroy.} = + ## todo + var + retArea: array[8, uint8] + arg0: uint64 + arg0 = editor.id + textEditorModesImported(arg0, cast[int32](retArea[0].addr)) + result = wl(cast[ptr typeof(result[0])](cast[ptr int32](retArea[0].addr)[]), + cast[ptr int32](retArea[4].addr)[]) + +proc textEditorClearTabStopsImported(a0: uint64): void {. + wasmimport("clear-tab-stops", "nev:plugins/text-editor").} +proc clearTabStops*(editor: TextEditor): void {.nodestroy.} = + ## todo + var arg0: uint64 + arg0 = editor.id + textEditorClearTabStopsImported(arg0) + +proc textEditorUndoImported(a0: uint64; a1: int32; a2: int32): void {. + wasmimport("undo", "nev:plugins/text-editor").} +proc undo*(editor: TextEditor; checkpoint: WitString): void {.nodestroy.} = + ## todo + var + arg0: uint64 + arg1: int32 + arg2: int32 + arg0 = editor.id + if checkpoint.len > 0: + arg1 = cast[int32](checkpoint[0].addr) + else: + arg1 = 0.int32 + arg2 = cast[int32](checkpoint.len) + textEditorUndoImported(arg0, arg1, arg2) + +proc textEditorRedoImported(a0: uint64; a1: int32; a2: int32): void {. + wasmimport("redo", "nev:plugins/text-editor").} +proc redo*(editor: TextEditor; checkpoint: WitString): void {.nodestroy.} = + ## todo + var + arg0: uint64 + arg1: int32 + arg2: int32 + arg0 = editor.id + if checkpoint.len > 0: + arg1 = cast[int32](checkpoint[0].addr) + else: + arg1 = 0.int32 + arg2 = cast[int32](checkpoint.len) + textEditorRedoImported(arg0, arg1, arg2) + +proc textEditorAddNextCheckpointImported(a0: uint64; a1: int32; a2: int32): void {. + wasmimport("add-next-checkpoint", "nev:plugins/text-editor").} +proc addNextCheckpoint*(editor: TextEditor; checkpoint: WitString): void {. + nodestroy.} = + ## todo + var + arg0: uint64 + arg1: int32 + arg2: int32 + arg0 = editor.id + if checkpoint.len > 0: + arg1 = cast[int32](checkpoint[0].addr) + else: + arg1 = 0.int32 + arg2 = cast[int32](checkpoint.len) + textEditorAddNextCheckpointImported(arg0, arg1, arg2) + +proc textEditorCopyImported(a0: uint64; a1: int32; a2: int32; a3: bool): void {. + wasmimport("copy", "nev:plugins/text-editor").} +proc copy*(editor: TextEditor; register: WitString; inclusiveEnd: bool): void {. + nodestroy.} = + ## todo + var + arg0: uint64 + arg1: int32 + arg2: int32 + arg3: bool + arg0 = editor.id + if register.len > 0: + arg1 = cast[int32](register[0].addr) + else: + arg1 = 0.int32 + arg2 = cast[int32](register.len) + arg3 = inclusiveEnd + textEditorCopyImported(arg0, arg1, arg2, arg3) + +proc textEditorPasteImported(a0: uint64; a1: int32; a2: int32; a3: int32; + a4: int32; a5: bool): void {. + wasmimport("paste", "nev:plugins/text-editor").} +proc paste*(editor: TextEditor; selections: WitList[Selection]; + register: WitString; inclusiveEnd: bool): void {.nodestroy.} = + ## todo + var + arg0: uint64 + arg1: int32 + arg2: int32 + arg3: int32 + arg4: int32 + arg5: bool + arg0 = editor.id + if selections.len > 0: + arg1 = cast[int32](selections[0].addr) + else: + arg1 = 0.int32 + arg2 = cast[int32](selections.len) + if register.len > 0: + arg3 = cast[int32](register[0].addr) + else: + arg3 = 0.int32 + arg4 = cast[int32](register.len) + arg5 = inclusiveEnd + textEditorPasteImported(arg0, arg1, arg2, arg3, arg4, arg5) + +proc textEditorAutoShowCompletionsImported(a0: uint64): void {. + wasmimport("auto-show-completions", "nev:plugins/text-editor").} +proc autoShowCompletions*(editor: TextEditor): void {.nodestroy.} = + ## todo + var arg0: uint64 + arg0 = editor.id + textEditorAutoShowCompletionsImported(arg0) + +proc textEditorToggleLineCommentImported(a0: uint64): void {. + wasmimport("toggle-line-comment", "nev:plugins/text-editor").} +proc toggleLineComment*(editor: TextEditor): void {.nodestroy.} = + ## todo + var arg0: uint64 + arg0 = editor.id + textEditorToggleLineCommentImported(arg0) + +proc textEditorInsertTextImported(a0: uint64; a1: int32; a2: int32; a3: bool): void {. + wasmimport("insert-text", "nev:plugins/text-editor").} +proc insertText*(editor: TextEditor; text: WitString; autoIndent: bool): void {. + nodestroy.} = + ## todo + var + arg0: uint64 + arg1: int32 + arg2: int32 + arg3: bool + arg0 = editor.id + if text.len > 0: + arg1 = cast[int32](text[0].addr) + else: + arg1 = 0.int32 + arg2 = cast[int32](text.len) + arg3 = autoIndent + textEditorInsertTextImported(arg0, arg1, arg2, arg3) + +proc textEditorOpenSearchBarImported(a0: uint64; a1: int32; a2: int32; a3: bool; + a4: bool): void {. + wasmimport("open-search-bar", "nev:plugins/text-editor").} +proc openSearchBar*(editor: TextEditor; query: WitString; scrollToPreview: bool; + selectResult: bool): void {.nodestroy.} = + ## todo + var + arg0: uint64 + arg1: int32 + arg2: int32 + arg3: bool + arg4: bool + arg0 = editor.id + if query.len > 0: + arg1 = cast[int32](query[0].addr) + else: + arg1 = 0.int32 + arg2 = cast[int32](query.len) + arg3 = scrollToPreview + arg4 = selectResult + textEditorOpenSearchBarImported(arg0, arg1, arg2, arg3, arg4) + +proc textEditorSetSearchQueryFromMoveImported(a0: uint64; a1: int32; a2: int32; + a3: int32; a4: int32; a5: int32; a6: int32; a7: int32; a8: int32): void {. + wasmimport("set-search-query-from-move", "nev:plugins/text-editor").} +proc setSearchQueryFromMove*(editor: TextEditor; move: WitString; count: int32; + prefix: WitString; suffix: WitString): Selection {. + nodestroy.} = + ## Set the search query by applying the given move to the current selection. + ## 'prefix' and 'suffix' are appended to the string after escaping. + var + retArea: array[40, uint8] + arg0: uint64 + arg1: int32 + arg2: int32 + arg3: int32 + arg4: int32 + arg5: int32 + arg6: int32 + arg7: int32 + arg0 = editor.id + if move.len > 0: + arg1 = cast[int32](move[0].addr) + else: + arg1 = 0.int32 + arg2 = cast[int32](move.len) + arg3 = count + if prefix.len > 0: + arg4 = cast[int32](prefix[0].addr) + else: + arg4 = 0.int32 + arg5 = cast[int32](prefix.len) + if suffix.len > 0: + arg6 = cast[int32](suffix[0].addr) + else: + arg6 = 0.int32 + arg7 = cast[int32](suffix.len) + textEditorSetSearchQueryFromMoveImported(arg0, arg1, arg2, arg3, arg4, arg5, + arg6, arg7, cast[int32](retArea[0].addr)) + result.first.line = convert(cast[ptr int32](retArea[0].addr)[], int32) + result.first.column = convert(cast[ptr int32](retArea[4].addr)[], int32) + result.last.line = convert(cast[ptr int32](retArea[8].addr)[], int32) + result.last.column = convert(cast[ptr int32](retArea[12].addr)[], int32) + +proc textEditorSetSearchQueryImported(a0: uint64; a1: int32; a2: int32; + a3: bool; a4: int32; a5: int32; a6: int32; + a7: int32): bool {. + wasmimport("set-search-query", "nev:plugins/text-editor").} +proc setSearchQuery*(editor: TextEditor; query: WitString; escapeRegex: bool; + prefix: WitString; suffix: WitString): bool {.nodestroy.} = + ## Set the search query to 'query'. If 'escape-regex' is true the the 'query' string is escaped so special characters + ## are searched for literally. 'prefix' and 'suffix' are appended to the string after escaping. + var + arg0: uint64 + arg1: int32 + arg2: int32 + arg3: bool + arg4: int32 + arg5: int32 + arg6: int32 + arg7: int32 + arg0 = editor.id + if query.len > 0: + arg1 = cast[int32](query[0].addr) + else: + arg1 = 0.int32 + arg2 = cast[int32](query.len) + arg3 = escapeRegex + if prefix.len > 0: + arg4 = cast[int32](prefix[0].addr) + else: + arg4 = 0.int32 + arg5 = cast[int32](prefix.len) + if suffix.len > 0: + arg6 = cast[int32](suffix[0].addr) + else: + arg6 = 0.int32 + arg7 = cast[int32](suffix.len) + let res = textEditorSetSearchQueryImported(arg0, arg1, arg2, arg3, arg4, arg5, + arg6, arg7) + result = res.bool + +proc textEditorGetSearchQueryImported(a0: uint64; a1: int32): void {. + wasmimport("get-search-query", "nev:plugins/text-editor").} +proc getSearchQuery*(editor: TextEditor): WitString {.nodestroy.} = + ## Returns the current search query. + var + retArea: array[8, uint8] + arg0: uint64 + arg0 = editor.id + textEditorGetSearchQueryImported(arg0, cast[int32](retArea[0].addr)) + result = ws(cast[ptr char](cast[ptr int32](retArea[0].addr)[]), + cast[ptr int32](retArea[4].addr)[]) + +proc textEditorApplyMoveImported(a0: uint64; a1: int32; a2: int32; a3: int32; + a4: int32; a5: int32; a6: int32; a7: int32; + a8: bool; a9: bool; a10: int32): void {. + wasmimport("apply-move", "nev:plugins/text-editor").} +proc applyMove*(editor: TextEditor; selection: Selection; move: WitString; + count: int32; wrap: bool; includeEol: bool): WitList[Selection] {. + nodestroy.} = + ## todo + var + retArea: array[48, uint8] + arg0: uint64 + arg1: int32 + arg2: int32 + arg3: int32 + arg4: int32 + arg5: int32 + arg6: int32 + arg7: int32 + arg8: bool + arg9: bool + arg0 = editor.id + arg1 = selection.first.line + arg2 = selection.first.column + arg3 = selection.last.line + arg4 = selection.last.column + if move.len > 0: + arg5 = cast[int32](move[0].addr) + else: + arg5 = 0.int32 + arg6 = cast[int32](move.len) + arg7 = count + arg8 = wrap + arg9 = includeEol + textEditorApplyMoveImported(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, + arg8, arg9, cast[int32](retArea[0].addr)) + result = wl(cast[ptr typeof(result[0])](cast[ptr int32](retArea[0].addr)[]), + cast[ptr int32](retArea[4].addr)[]) + +proc textEditorMultiMoveImported(a0: uint64; a1: int32; a2: int32; a3: int32; + a4: int32; a5: int32; a6: bool; a7: bool; + a8: int32): void {. + wasmimport("multi-move", "nev:plugins/text-editor").} +proc multiMove*(editor: TextEditor; selections: WitList[Selection]; + move: WitString; count: int32; wrap: bool; includeEol: bool): WitList[ + Selection] {.nodestroy.} = + var + retArea: array[40, uint8] + arg0: uint64 + arg1: int32 + arg2: int32 + arg3: int32 + arg4: int32 + arg5: int32 + arg6: bool + arg7: bool + arg0 = editor.id + if selections.len > 0: + arg1 = cast[int32](selections[0].addr) + else: + arg1 = 0.int32 + arg2 = cast[int32](selections.len) + if move.len > 0: + arg3 = cast[int32](move[0].addr) + else: + arg3 = 0.int32 + arg4 = cast[int32](move.len) + arg5 = count + arg6 = wrap + arg7 = includeEol + textEditorMultiMoveImported(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, + cast[int32](retArea[0].addr)) + result = wl(cast[ptr typeof(result[0])](cast[ptr int32](retArea[0].addr)[]), + cast[ptr int32](retArea[4].addr)[]) + proc textEditorSetSelectionImported(a0: uint64; a1: int32; a2: int32; a3: int32; a4: int32): void {. wasmimport("set-selection", "nev:plugins/text-editor").} @@ -122,6 +608,22 @@ proc setSelection*(editor: TextEditor; s: Selection): void {.nodestroy.} = arg4 = s.last.column textEditorSetSelectionImported(arg0, arg1, arg2, arg3, arg4) +proc textEditorSetSelectionsImported(a0: uint64; a1: int32; a2: int32): void {. + wasmimport("set-selections", "nev:plugins/text-editor").} +proc setSelections*(editor: TextEditor; s: WitList[Selection]): void {.nodestroy.} = + ## Sets the selections for the given editor. + var + arg0: uint64 + arg1: int32 + arg2: int32 + arg0 = editor.id + if s.len > 0: + arg1 = cast[int32](s[0].addr) + else: + arg1 = 0.int32 + arg2 = cast[int32](s.len) + textEditorSetSelectionsImported(arg0, arg1, arg2) + proc textEditorGetSelectionImported(a0: uint64; a1: int32): void {. wasmimport("get-selection", "nev:plugins/text-editor").} proc getSelection*(editor: TextEditor): Selection {.nodestroy.} = @@ -136,6 +638,30 @@ proc getSelection*(editor: TextEditor): Selection {.nodestroy.} = result.last.line = convert(cast[ptr int32](retArea[8].addr)[], int32) result.last.column = convert(cast[ptr int32](retArea[12].addr)[], int32) +proc textEditorGetSelectionsImported(a0: uint64; a1: int32): void {. + wasmimport("get-selections", "nev:plugins/text-editor").} +proc getSelections*(editor: TextEditor): WitList[Selection] {.nodestroy.} = + ## Returns the selections of the given editor. + var + retArea: array[8, uint8] + arg0: uint64 + arg0 = editor.id + textEditorGetSelectionsImported(arg0, cast[int32](retArea[0].addr)) + result = wl(cast[ptr typeof(result[0])](cast[ptr int32](retArea[0].addr)[]), + cast[ptr int32](retArea[4].addr)[]) + +proc textEditorLineLengthImported(a0: uint64; a1: int32): int32 {. + wasmimport("line-length", "nev:plugins/text-editor").} +proc lineLength*(editor: TextEditor; line: int32): int32 {.nodestroy.} = + ## Return the length of the given line (0 based) + var + arg0: uint64 + arg1: int32 + arg0 = editor.id + arg1 = line + let res = textEditorLineLengthImported(arg0, arg1) + result = convert(res, int32) + proc textEditorAddModeChangedHandlerImported(a0: uint32): int32 {. wasmimport("add-mode-changed-handler", "nev:plugins/text-editor").} proc addModeChangedHandler*(fun: uint32): int32 {.nodestroy.} = @@ -145,18 +671,193 @@ proc addModeChangedHandler*(fun: uint32): int32 {.nodestroy.} = let res = textEditorAddModeChangedHandlerImported(arg0) result = convert(res, int32) +proc textEditorGetSettingRawImported(a0: uint64; a1: int32; a2: int32; a3: int32): void {. + wasmimport("get-setting-raw", "nev:plugins/text-editor").} +proc getSettingRaw*(editor: TextEditor; name: WitString): WitString {.nodestroy.} = + ## Returns the value of the setting with the given path, encoded as JSON. + var + retArea: array[16, uint8] + arg0: uint64 + arg1: int32 + arg2: int32 + arg0 = editor.id + if name.len > 0: + arg1 = cast[int32](name[0].addr) + else: + arg1 = 0.int32 + arg2 = cast[int32](name.len) + textEditorGetSettingRawImported(arg0, arg1, arg2, + cast[int32](retArea[0].addr)) + result = ws(cast[ptr char](cast[ptr int32](retArea[0].addr)[]), + cast[ptr int32](retArea[4].addr)[]) + +proc textEditorSetSettingRawImported(a0: uint64; a1: int32; a2: int32; + a3: int32; a4: int32): void {. + wasmimport("set-setting-raw", "nev:plugins/text-editor").} +proc setSettingRaw*(editor: TextEditor; name: WitString; value: WitString): void {. + nodestroy.} = + ## Set the value of the setting with the given path. The value must be encoded as JSON. + var + arg0: uint64 + arg1: int32 + arg2: int32 + arg3: int32 + arg4: int32 + arg0 = editor.id + if name.len > 0: + arg1 = cast[int32](name[0].addr) + else: + arg1 = 0.int32 + arg2 = cast[int32](name.len) + if value.len > 0: + arg3 = cast[int32](value[0].addr) + else: + arg3 = 0.int32 + arg4 = cast[int32](value.len) + textEditorSetSettingRawImported(arg0, arg1, arg2, arg3, arg4) + +proc textEditorEvaluateExpressionsImported(a0: uint64; a1: int32; a2: int32; + a3: bool; a4: int32; a5: int32; a6: int32; a7: int32; a8: bool): void {. + wasmimport("evaluate-expressions", "nev:plugins/text-editor").} +proc evaluateExpressions*(editor: TextEditor; selections: WitList[Selection]; + inclusive: bool; prefix: WitString; suffix: WitString; + addSelectionIndex: bool): void {.nodestroy.} = + ## todo + var + arg0: uint64 + arg1: int32 + arg2: int32 + arg3: bool + arg4: int32 + arg5: int32 + arg6: int32 + arg7: int32 + arg8: bool + arg0 = editor.id + if selections.len > 0: + arg1 = cast[int32](selections[0].addr) + else: + arg1 = 0.int32 + arg2 = cast[int32](selections.len) + arg3 = inclusive + if prefix.len > 0: + arg4 = cast[int32](prefix[0].addr) + else: + arg4 = 0.int32 + arg5 = cast[int32](prefix.len) + if suffix.len > 0: + arg6 = cast[int32](suffix[0].addr) + else: + arg6 = 0.int32 + arg7 = cast[int32](suffix.len) + arg8 = addSelectionIndex + textEditorEvaluateExpressionsImported(arg0, arg1, arg2, arg3, arg4, arg5, + arg6, arg7, arg8) + +proc textEditorIndentImported(a0: uint64; a1: int32): void {. + wasmimport("indent", "nev:plugins/text-editor").} +proc indent*(editor: TextEditor; delta: int32): void {.nodestroy.} = + ## todo + var + arg0: uint64 + arg1: int32 + arg0 = editor.id + arg1 = delta + textEditorIndentImported(arg0, arg1) + +proc textEditorGetCommandCountImported(a0: uint64): int32 {. + wasmimport("get-command-count", "nev:plugins/text-editor").} +proc getCommandCount*(editor: TextEditor): int32 {.nodestroy.} = + ## todo + var arg0: uint64 + arg0 = editor.id + let res = textEditorGetCommandCountImported(arg0) + result = convert(res, int32) + +proc textEditorSetCursorScrollOffsetImported(a0: uint64; a1: int32; a2: int32; + a3: float32): void {.wasmimport("set-cursor-scroll-offset", + "nev:plugins/text-editor").} +proc setCursorScrollOffset*(editor: TextEditor; cursor: Cursor; + scrollOffset: float32): void {.nodestroy.} = + ## todo + var + arg0: uint64 + arg1: int32 + arg2: int32 + arg3: float32 + arg0 = editor.id + arg1 = cursor.line + arg2 = cursor.column + arg3 = scrollOffset + textEditorSetCursorScrollOffsetImported(arg0, arg1, arg2, arg3) + +proc textEditorGetVisibleLineCountImported(a0: uint64): int32 {. + wasmimport("get-visible-line-count", "nev:plugins/text-editor").} +proc getVisibleLineCount*(editor: TextEditor): int32 {.nodestroy.} = + ## Returns the number of lines that fit on the current screen size for this editor. + var arg0: uint64 + arg0 = editor.id + let res = textEditorGetVisibleLineCountImported(arg0) + result = convert(res, int32) + +proc textEditorCreateAnchorsImported(a0: uint64; a1: int32; a2: int32; a3: int32): void {. + wasmimport("create-anchors", "nev:plugins/text-editor").} +proc createAnchors*(editor: TextEditor; selections: WitList[Selection]): WitList[ + (Anchor, Anchor)] {.nodestroy.} = + ## todo + var + retArea: array[16, uint8] + arg0: uint64 + arg1: int32 + arg2: int32 + arg0 = editor.id + if selections.len > 0: + arg1 = cast[int32](selections[0].addr) + else: + arg1 = 0.int32 + arg2 = cast[int32](selections.len) + textEditorCreateAnchorsImported(arg0, arg1, arg2, + cast[int32](retArea[0].addr)) + result = wl(cast[ptr typeof(result[0])](cast[ptr int32](retArea[0].addr)[]), + cast[ptr int32](retArea[4].addr)[]) + +proc textEditorResolveAnchorsImported(a0: uint64; a1: int32; a2: int32; + a3: int32): void {. + wasmimport("resolve-anchors", "nev:plugins/text-editor").} +proc resolveAnchors*(editor: TextEditor; anchors: WitList[(Anchor, Anchor)]): WitList[ + Selection] {.nodestroy.} = + ## todo + var + retArea: array[16, uint8] + arg0: uint64 + arg1: int32 + arg2: int32 + arg0 = editor.id + if anchors.len > 0: + arg1 = cast[int32](anchors[0].addr) + else: + arg1 = 0.int32 + arg2 = cast[int32](anchors.len) + textEditorResolveAnchorsImported(arg0, arg1, arg2, + cast[int32](retArea[0].addr)) + result = wl(cast[ptr typeof(result[0])](cast[ptr int32](retArea[0].addr)[]), + cast[ptr int32](retArea[4].addr)[]) + proc textEditorEditImported(a0: uint64; a1: int32; a2: int32; a3: int32; - a4: int32; a5: int32): void {. + a4: int32; a5: bool; a6: int32): void {. wasmimport("edit", "nev:plugins/text-editor").} proc edit*(editor: TextEditor; selections: WitList[Selection]; - contents: WitList[WitString]): WitList[Selection] {.nodestroy.} = + contents: WitList[WitString]; inclusive: bool): WitList[Selection] {. + nodestroy.} = + ## todo var - retArea: array[24, uint8] + retArea: array[32, uint8] arg0: uint64 arg1: int32 arg2: int32 arg3: int32 arg4: int32 + arg5: bool arg0 = editor.id if selections.len > 0: arg1 = cast[int32](selections[0].addr) @@ -168,11 +869,29 @@ proc edit*(editor: TextEditor; selections: WitList[Selection]; else: arg3 = 0.int32 arg4 = cast[int32](contents.len) - textEditorEditImported(arg0, arg1, arg2, arg3, arg4, + arg5 = inclusive + textEditorEditImported(arg0, arg1, arg2, arg3, arg4, arg5, cast[int32](retArea[0].addr)) result = wl(cast[ptr typeof(result[0])](cast[ptr int32](retArea[0].addr)[]), cast[ptr int32](retArea[4].addr)[]) +proc textEditorDefineMoveImported(a0: int32; a1: int32; a2: uint32; a3: uint32): void {. + wasmimport("define-move", "nev:plugins/text-editor").} +proc defineMove*(move: WitString; fun: uint32; data: uint32): void {.nodestroy.} = + var + arg0: int32 + arg1: int32 + arg2: uint32 + arg3: uint32 + if move.len > 0: + arg0 = cast[int32](move[0].addr) + else: + arg0 = 0.int32 + arg1 = cast[int32](move.len) + arg2 = fun + arg3 = data + textEditorDefineMoveImported(arg0, arg1, arg2, arg3) + proc textEditorContentImported(a0: uint64): int32 {. wasmimport("content", "nev:plugins/text-editor").} proc content*(editor: TextEditor): Rope {.nodestroy.} = diff --git a/plugin_api/v0/types.nim b/plugin_api/v0/types.nim index d61db414e..2104ed56c 100644 --- a/plugin_api/v0/types.nim +++ b/plugin_api/v0/types.nim @@ -25,6 +25,19 @@ type Rect* = object pos*: Vec2f size*: Vec2f + ActiveEditorFlag* = enum + IncludeCommandLine = "include-command-line", + IncludePopups = "include-popups" + ActiveEditorFlags* = set[ActiveEditorFlag] + Lamport* = object + replicaId*: uint16 + value*: uint32 + Bias* = enum + Left = "left", Right = "right" + Anchor* = object + timestamp*: Lamport + offset*: uint32 + bias*: Bias ## Shared reference to a rope. The rope data is stored in the editor, not in the plugin, so ropes ## can be used to efficiently access any document content or share a string with another plugin. ## Ropes are reference counted internally, and this resource also affects that reference count. @@ -113,21 +126,69 @@ proc text*(self: Rope): WitString {.nodestroy.} = result = ws(cast[ptr char](cast[ptr int32](retArea[0].addr)[]), cast[ptr int32](retArea[4].addr)[]) -proc typesSliceImported(a0: int32; a1: int64; a2: int64): int32 {. +proc typesSliceImported(a0: int32; a1: int64; a2: int64; a3: bool): int32 {. wasmimport("[method]rope.slice", "nev:plugins/types").} -proc slice*(self: Rope; a: int64; b: int64): Rope {.nodestroy.} = - ## Returns a slice of the rope from 'a' to 'b'. 'a' and 'b' are byte indices, 'b' is exclusive. +proc slice*(self: Rope; a: int64; b: int64; inclusive: bool): Rope {.nodestroy.} = + ## Returns a slice of the rope from 'a' to 'b'. 'a' and 'b' are byte indices, 'b' is inclusive if `inclusive` is true. ## This operation is cheap because it doesn't create a copy of the text. var arg0: int32 arg1: int64 arg2: int64 + arg3: bool arg0 = cast[int32](self.handle - 1) arg1 = a arg2 = b - let res = typesSliceImported(arg0, arg1, arg2) + arg3 = inclusive + let res = typesSliceImported(arg0, arg1, arg2, arg3) result.handle = res + 1 +proc typesSliceSelectionImported(a0: int32; a1: int32; a2: int32; a3: int32; + a4: int32; a5: bool): int32 {. + wasmimport("[method]rope.slice-selection", "nev:plugins/types").} +proc sliceSelection*(self: Rope; s: Selection; inclusive: bool): Rope {. + nodestroy.} = + ## Returns a slice of the rope from the given selection. 's.last' is inclusive if `inclusive` is true. + ## This operation is cheap because it doesn't create a copy of the text. + var + arg0: int32 + arg1: int32 + arg2: int32 + arg3: int32 + arg4: int32 + arg5: bool + arg0 = cast[int32](self.handle - 1) + arg1 = s.first.line + arg2 = s.first.column + arg3 = s.last.line + arg4 = s.last.column + arg5 = inclusive + let res = typesSliceSelectionImported(arg0, arg1, arg2, arg3, arg4, arg5) + result.handle = res + 1 + +proc typesFindImported(a0: int32; a1: int32; a2: int32; a3: int64; a4: int32): void {. + wasmimport("[method]rope.find", "nev:plugins/types").} +proc find*(self: Rope; sub: WitString; start: int64): Option[int64] {.nodestroy.} = + ## Find the byte index of the sub string 'sub', starting the search at 'start'. The returned index is relative to the start of the rope, not 'start'. + var + retArea: array[24, uint8] + arg0: int32 + arg1: int32 + arg2: int32 + arg3: int64 + arg0 = cast[int32](self.handle - 1) + if sub.len > 0: + arg1 = cast[int32](sub[0].addr) + else: + arg1 = 0.int32 + arg2 = cast[int32](sub.len) + arg3 = start + typesFindImported(arg0, arg1, arg2, arg3, cast[int32](retArea[0].addr)) + if cast[ptr int64](retArea[0].addr)[] != 0: + var temp: int64 + temp = convert(cast[ptr int64](retArea[8].addr)[], int64) + result = temp.some + proc typesSlicePointsImported(a0: int32; a1: int32; a2: int32; a3: int32; a4: int32): int32 {. wasmimport("[method]rope.slice-points", "nev:plugins/types").} @@ -147,3 +208,44 @@ proc slicePoints*(self: Rope; a: Cursor; b: Cursor): Rope {.nodestroy.} = arg4 = b.column let res = typesSlicePointsImported(arg0, arg1, arg2, arg3, arg4) result.handle = res + 1 + +proc typesLineLengthImported(a0: int32; a1: int64): int64 {. + wasmimport("[method]rope.line-length", "nev:plugins/types").} +proc lineLength*(self: Rope; line: int64): int64 {.nodestroy.} = + ## Return the length in bytes of the given line (0 based). + var + arg0: int32 + arg1: int64 + arg0 = cast[int32](self.handle - 1) + arg1 = line + let res = typesLineLengthImported(arg0, arg1) + result = convert(res, int64) + +proc typesRuneAtImported(a0: int32; a1: int32; a2: int32): Rune {. + wasmimport("[method]rope.rune-at", "nev:plugins/types").} +proc runeAt*(self: Rope; a: Cursor): Rune {.nodestroy.} = + ## /// Returns a slice of the rope from line 'a' to 'b'. 'b' is inclusive. + ## /// This operation is cheap because it doesn't create a copy of the text. + ## slice-lines: func(a: s64, b: s64) -> rope; + var + arg0: int32 + arg1: int32 + arg2: int32 + arg0 = cast[int32](self.handle - 1) + arg1 = a.line + arg2 = a.column + let res = typesRuneAtImported(arg0, arg1, arg2) + result = res.Rune + +proc typesByteAtImported(a0: int32; a1: int32; a2: int32): uint8 {. + wasmimport("[method]rope.byte-at", "nev:plugins/types").} +proc byteAt*(self: Rope; a: Cursor): uint8 {.nodestroy.} = + var + arg0: int32 + arg1: int32 + arg2: int32 + arg0 = cast[int32](self.handle - 1) + arg1 = a.line + arg2 = a.column + let res = typesByteAtImported(arg0, arg1, arg2) + result = convert(res, uint8) diff --git a/plugins/test_plugin/test_plugin.nim b/plugins/test_plugin/test_plugin.nim index 92939271f..5146c88ed 100644 --- a/plugins/test_plugin/test_plugin.nim +++ b/plugins/test_plugin/test_plugin.nim @@ -217,7 +217,7 @@ defineCommand(ws"test-command-5", context = ws"", data = 0): proc(data: uint32, args: WitString): WitString {.cdecl.} = - if activeTextEditor().getSome(editor): + if activeTextEditor({}).getSome(editor): let s = editor.getSelection echo editor.id echo "========== ", s @@ -275,7 +275,7 @@ defineCommand(ws"test-start-process", context = ws"", data = 0): proc(data: uint32, args: WitString): WitString {.cdecl.} = - if activeTextEditor().getSome(editor): + if activeTextEditor({}).getSome(editor): var p = processStart(ws"powershell", @@[ws"-Command", ws"ls", ws"plugins"]) let stdout = p.stdout() @@ -286,7 +286,7 @@ defineCommand(ws"test-start-process", if stdout.atEnd: if buffer.endsWith("\0"): buffer.setLen(buffer.len - 1) - let selections = editor.edit(@@[editor.getSelection], @@[ws(buffer.replace("\r", ""))]) + let selections = editor.edit(@@[editor.getSelection], @@[ws(buffer.replace("\r", ""))], false) if selections.len > 0: editor.setSelection(selections[0].last.toSelection) return Stop diff --git a/plugins/vim/config.nims b/plugins/vim/config.nims new file mode 100644 index 000000000..ec5b26355 --- /dev/null +++ b/plugins/vim/config.nims @@ -0,0 +1,14 @@ +include "../wasm.config.nims" +switch("d", "pluginApiVersion=0") +switch("d", "witRebuild") +switch("nimcache", "../../nimcache/vim") + +# Put custom build configs which shouldn't be commited in local.nims +when withDir(thisDir(), fileExists("local.nims")): + include "local.nims" + +# begin Nimble config (version 2) +--noNimblePath +when withDir(thisDir(), system.fileExists("nimble.paths")): + include "nimble.paths" +# end Nimble config diff --git a/plugins/vim/manifest.json b/plugins/vim/manifest.json new file mode 100644 index 000000000..e7c6d2348 --- /dev/null +++ b/plugins/vim/manifest.json @@ -0,0 +1,13 @@ +{ + "name": "Vim Motions", + "version": "0.0.1", + "authors": ["Nimaoth"], + "repository": "https://github.com/Nimaoth/Nev/plugins/vim", + "wasm": "vim.m.wasm", + // "wasm": "vim.wat", + "autoLoad": true, + "commands": { + "test-command-1": {}, + }, + "permissions": {}, +} diff --git a/plugins/vim/nimble.lock b/plugins/vim/nimble.lock new file mode 100644 index 000000000..c9e57bb07 --- /dev/null +++ b/plugins/vim/nimble.lock @@ -0,0 +1,128 @@ +{ + "version": 2, + "packages": { + "vmath": { + "version": "2.0.0", + "vcsRevision": "661bdaac7546e16d087f066adfeb6ea7590106b4", + "url": "https://github.com/Nimaoth/vmath", + "downloadMethod": "git", + "dependencies": [], + "checksums": { + "sha1": "db421090319e1a0ef028535eedfdadae6f3d7294" + } + }, + "bumpy": { + "version": "1.1.2", + "vcsRevision": "d7eaf00c24820ad0317c9926737402e62431e931", + "url": "https://github.com/treeform/bumpy", + "downloadMethod": "git", + "dependencies": [ + "vmath" + ], + "checksums": { + "sha1": "acc789c4e31b3ee969a13dd0c238d808f39b19c7" + } + }, + "c2nim": { + "version": "0.9.19", + "vcsRevision": "5753fa7658ed50432ea6c2df84f0a45e36bcb2ea", + "url": "https://github.com/nim-lang/c2nim", + "downloadMethod": "git", + "dependencies": [], + "checksums": { + "sha1": "1954eb89cc353cf2a4e54804d38d5a1e72f3c98e" + } + }, + "chroma": { + "version": "0.2.7", + "vcsRevision": "b2e71179174e040884ebf6a16cbac711c84620b9", + "url": "https://github.com/treeform/chroma", + "downloadMethod": "git", + "dependencies": [], + "checksums": { + "sha1": "f873f4b97e87a82e27e0b85bf9130fe3e320a2b8" + } + }, + "fusion": { + "version": "1.2", + "vcsRevision": "0b0a0273b8df860cd54e3fcca7bb4c617244ac77", + "url": "https://github.com/nim-lang/fusion", + "downloadMethod": "git", + "dependencies": [], + "checksums": { + "sha1": "408bde8679bce63dfb6f424e107eb37c5eb31510" + } + }, + "unicodedb": { + "version": "0.12.0", + "vcsRevision": "b055310c08db8f879057b4fec15c8301ee93bb2a", + "url": "https://github.com/nitely/nim-unicodedb", + "downloadMethod": "git", + "dependencies": [], + "checksums": { + "sha1": "4452416471e2fe8726eb6070ed6ea7368171cc09" + } + }, + "regex": { + "version": "0.25.0", + "vcsRevision": "cb8b7bfdcdc2272aadf92153c668acd3c901bd6b", + "url": "https://github.com/nitely/nim-regex", + "downloadMethod": "git", + "dependencies": [ + "unicodedb" + ], + "checksums": { + "sha1": "cb2e24397c051e55ad5b72b3c0d4f270a90084df" + } + }, + "glob": { + "version": "0.11.2", + "vcsRevision": "64f71af2fa4572c2bdf8987a56a427c1d88fc34f", + "url": "https://github.com/haltcase/glob", + "downloadMethod": "git", + "dependencies": [ + "regex" + ], + "checksums": { + "sha1": "58fadfae8cb82cab1061dded8066c03b0460ad4d" + } + }, + "nimgen": { + "version": "0.5.4", + "vcsRevision": "e6697aabbe36e42e4dd261cfd0b8a8be16f6f342", + "url": "https://github.com/Nimaoth/nimgen", + "downloadMethod": "git", + "dependencies": [ + "c2nim", + "regex", + "unicodedb" + ], + "checksums": { + "sha1": "d563cc29937e4d2d66ebeb3eaacef95c6284fb4c" + } + }, + "nimwasmtime": { + "version": "0.2.1", + "vcsRevision": "415a252eb4cada08d7ced468d42c92b1b0d4ae72", + "url": "https://github.com/Nimaoth/nimwasmtime", + "downloadMethod": "git", + "dependencies": [ + "nimgen" + ], + "checksums": { + "sha1": "da3c2261fac93db812ac62808b606d45b4d25e0d" + } + }, + "results": { + "version": "0.5.0", + "vcsRevision": "57b2392ad69849e3e2d02b74a8a0feee2c3d9570", + "url": "https://github.com/arnetheduck/nim-results", + "downloadMethod": "git", + "dependencies": [], + "checksums": { + "sha1": "901e2ed088160fdcb8fdf3b315ce62baedc3f7ba" + } + } + }, + "tasks": {} +} diff --git a/plugins/vim/vim.nim b/plugins/vim/vim.nim new file mode 100644 index 000000000..a18beb9e5 --- /dev/null +++ b/plugins/vim/vim.nim @@ -0,0 +1,1387 @@ +# import std/[strutils, macros, genasts, sequtils, sets, algorithm, jsonutils] +import std/[strformat, json, jsonutils, strutils, tables, macros, genasts, streams, sequtils, sets, os, terminal, colors, algorithm, unicode] +import results +import util, custom_unicode, myjsonutils, id, wrap, sugar, custom_regex +# import input_api +import api +from "../../src/scripting_api.nim" as sca import nil +import "../../src/input_api.nim" + +proc last*[T](list: WitList[T]): lent T = + assert list.len > 0 + return list[list.len - 1] + +proc `==`*[T](a, b: WitList[T]): bool = + if a.len != b.len: + return false + return equalMem(a.data, b.data, a.len) + +proc `==`*(a, b: WitString): bool = + if a.len != b.len: + return false + return equalMem(a.data, b.data, a.len) + +var yankedLines: bool = false ## Whether the last thing we yanked was in a line mode + +type EditorVimState = object + ## Contains state which can vary per editor + selectLines: bool = false ## Whether entire lines should be selected (e.g. in visual-line mode/when using dd) + deleteInclusiveEnd: bool = true ## Whether the next time we delete some the selection end should be inclusive + cursorIncludeEol: bool = false ## Whether the cursor can be after the last character in a line (e.g. in insert mode) + currentUndoCheckpoint: string = "insert" ## Which checkpoint to undo to (depends on mode) + revisionBeforeImplicitInsertMacro: int + marks: Table[string, seq[(Anchor, Anchor)]] + unresolvedMarks: Table[string, seq[Selection]] + +var editorStates: Table[sca.EditorId, EditorVimState] + +const editorContext = "editor.text" + + +type IdentifierCase = enum Camel, Pascal, Kebab, Snake, ScreamingSnake + +proc moveCursorColumn(editor: TextEditor, amount: int, wrap: bool = false, includeEol: bool = true) = + editor.setSelections editor.multiMove(editor.selections, ws"column", 1, wrap, includeEol).mapIt(it.last.toSelection).stackWitList() + +proc moveCursorColumn(editor: TextEditor, selections: WitList[Selection], amount: int, wrap: bool = false, includeEol: bool = true): WitList[Selection] = + editor.multiMove(selections, ws"column", 1, wrap, includeEol).mapIt(it.last.toSelection).stackWitList() + +proc moveCursorLine(editor: TextEditor, amount: int, includeEol: bool = true) = + editor.setSelections editor.multiMove(editor.selections, ws"line-down", amount, false, includeEol).mapIt(it.last.toSelection).stackWitList() + +proc splitCase(s: string): tuple[cas: IdentifierCase, parts: seq[string]] = + if s == "": + return (IdentifierCase.Camel, @[]) + + if s.find('_') != -1: + result.cas = IdentifierCase.Snake + result.parts = s.split('_').mapIt(custom_unicode.toLower(it)) + for r in s.runes: + if r != '_'.Rune and not r.isLower: + result.cas = IdentifierCase.ScreamingSnake + break + + elif s.find('-') != -1: + result.cas = IdentifierCase.Kebab + result.parts = s.split('-').mapIt(custom_unicode.toLower(it)) + else: + if s[0].isUpperAscii: + result.cas = IdentifierCase.Pascal + else: + result.cas = IdentifierCase.Camel + + result.parts.add "" + for r in s.runes: + if not r.isLower and result.parts.last.len > 0: + result.parts.add "" + result.parts.last.add(custom_unicode.toLower(r)) + +proc joinCase(parts: seq[string], cas: IdentifierCase): string = + assert parts.len > 0 + case cas + of IdentifierCase.Camel: + parts[0] & parts[1..^1].mapIt(it.capitalize).join("") + of IdentifierCase.Pascal: + parts.mapIt(it.capitalize).join("") + of IdentifierCase.Kebab: + parts.join("-") + of IdentifierCase.Snake: + parts.join("_") + of IdentifierCase.ScreamingSnake: + parts.mapIt(custom_unicode.toUpper(it)).join("_") + +proc cycleCase(s: string): string = + if s.len == 0: + return s + let (cas, parts) = s.splitCase() + let nextCase = if cas == IdentifierCase.high: + IdentifierCase.low + else: + cas.succ + return parts.joinCase(nextCase) + +proc exposeImpl*(context: NimNode, name: string, fun: NimNode, active: bool): NimNode = + # defer: + # echo result.repr + + let def = if fun.kind == nnkProcDef: fun else: fun.getImpl + if def.kind != nnkProcDef: + error("expose can only be used on proc definitions", fun) + + let signature = def.copy + signature[6] = newEmptyNode() + + let signatureUntyped = parseExpr(signature.repr) + let jsonWrapperName = (def.name.repr & "Json").ident + let jsonWrapper = createJsonWrapper(signatureUntyped, jsonWrapperName) + + let documentation = def.getDocumentation() + let documentationStr = documentation.map((it) => it.strVal).get("").newLit + + let returnType = if def[3][0].kind == nnkEmpty: "" else: def[3][0].repr + var params: seq[(string, string)] = @[] + for param in def[3][1..^1]: + params.add (param[0].repr, param[1].repr) + + if def == fun: + return genAst(name, def, jsonWrapper, jsonWrapperName, documentationStr, inParams = params, inReturnType = returnType, inActive = active, inContext = context): + def + jsonWrapper + defineCommand(ws(name), + active = inActive, + docs = ws(documentationStr), + params = wl[(WitString, WitString)](nil, 0), + returnType = ws(inReturnType), + context = ws(inContext), + data = 0): + proc(data: uint32, argsString: WitString): WitString {.cdecl.} = + var args = newJArray() + try: + for a in newStringStream($argsString).parseJsonFragments(): + args.add a + let res = jsonWrapperName(args) + return stackWitString($res) + except CatchableError as e: + log lvlError, "Failed to run command '" & name & "': " & e.msg + + return ws"" + + else: + return genAst(name, jsonWrapper, jsonWrapperName, documentationStr, inParams = params, inReturnType = returnType, inAactive = active, inContext = context): + jsonWrapper + defineCommand(stackWitString(name), + active = inActive, + docs = ws(documentationStr), + params = wl[(WitString, WitString)](nil, 0), + returnType = ws(inReturnType), + context = ws(inContext), + data = 0): + proc(data: uint32, args: WitString): WitString {.cdecl.} = + var args = newJArray() + try: + for a in newStringStream($argsString).parseJsonFragments(): + args.add a + let res = jsonWrapperName(args) + return stackWitString($res) + except CatchableError as e: + log lvlError, "Failed to run command '" & name & "': " & e.msg + + return ws"" + +macro command*(fun: typed): untyped = + let name = fun.name.repr.splitCase.parts.joinCase(Kebab) + return exposeImpl(newLit(""), name, fun, active=false) + +macro exposeActive*(context: string, fun: typed): untyped = + let name = fun.name.repr.splitCase.parts.joinCase(Kebab) + return exposeImpl(context, name, fun, active=true) + +macro callJson*(fun: typed, args: JsonNode): JsonNode = + ## Calls a function with a json object as argument, converting the json object to nim types + let jsonWrapperName = genSym(nskProc, "jsonWrapper") + let jsonWrapper = createJsonWrapper(fun, fun.getType, jsonWrapperName) + jsonWrapper.addPragma("closure".ident) + return genAst(jsonWrapper, jsonWrapperName, args): + block: + jsonWrapper + jsonWrapperName(args) + +proc vimState(editor: TextEditor): var EditorVimState = + if not editorStates.contains(editor.id): + editorStates[editor.id] = EditorVimState() + return editorStates[editor.id] + +proc getContextWithMode(self: TextEditor, context: string): string = + ## Appends the current mode to context + return context & "." & $self.mode + +proc shouldRecortImplicitPeriodMacro(editor: TextEditor): bool = + case $editor.getUsage() + of "command-line", "search-bar": + return false + else: + return true + +proc recordCurrentCommandInPeriodMacro(editor: TextEditor) = + if not isReplayingCommands() and editor.shouldRecortImplicitPeriodMacro(): + setRegisterText(ws"", ws".") + editor.recordCurrentCommand(@@[ws"."]) + +proc startRecordingCurrentCommandInPeriodMacro(editor: TextEditor) = + if not isReplayingCommands() and editor.shouldRecortImplicitPeriodMacro(): + startRecordingCommands(ws".-temp") + setRegisterText(ws"", ws".-temp") + editor.recordCurrentCommand(@@[ws".-temp"]) + editor.vimState.revisionBeforeImplicitInsertMacro = editor.getRevision + +type VimTextObjectRange* = enum Inner, Outer, CurrentToEnd + +proc getVimLineMargin*(): float = getSetting("editor.text.vim.line-margin", 5.float) +proc getVimClipboard*(): string = getSetting("editor.text.vim.clipboard", "") +proc getVimDefaultRegister*(): string = + case getVimClipboard(): + of "unnamed": return "*" + of "unnamedplus": return "+" + else: return "\"" + +proc getCurrentMacroRegister*(): string = getSetting("editor.current-macro-register", "") + +proc getEnclosing(line: string, column: int, predicate: proc(c: char): bool): (int, int) = + var startColumn = column + var endColumn = column + while endColumn < line.high and predicate(line[endColumn + 1]): + inc endColumn + while startColumn > 0 and predicate(line[startColumn - 1]): + dec startColumn + return (startColumn, endColumn) + +proc handleSelectWord(editor: TextEditor, cursor: Cursor) {.exposeActive(editorContext).} = + editor.setSelection(cursor.toSelection) + +proc selectLine(editor: TextEditor) {.exposeActive(editorContext).} = + editor.setSelections stackWitList(editor.selections.mapIt (if it.isBackwards: + Selection(first: Cursor(line: it.first.line, column: editor.lineLength(it.first.line)), last: Cursor(line: it.last.line, column: 0)) + else: + Selection(first: Cursor(line: it.first.line, column: 0), last: Cursor(line: it.last.line, column: editor.lineLength(it.last.line))) + )) + +proc normalMode(editor: TextEditor) {.exposeActive(editorContext).} = + ## Exit to normal mode and clear things + if $editor.mode == "vim.normal": + editor.setSelection editor.getSelection.last.toSelection + editor.clearTabStops() + editor.setMode("vim.normal") + +proc visualLineMode(editor: TextEditor) {.exposeActive(editorContext).} = + editor.setMode "vim.visual-line" + editor.selectLine() + +proc applyVimMove(editor: TextEditor, move: string, suffix: string, count: int = 0): tuple[updateTargetColumn: bool] = + result.updateTargetColumn = true + if move.startsWith("("): + const targetColumnSuffix = "(dont-update-target-column)" + var adjustedMove = move + if adjustedMove.endsWith(targetColumnSuffix): + adjustedMove.removeSuffix(targetColumnSuffix) + result.updateTargetColumn = false + adjustedMove = adjustedMove & " " & suffix + # debugf"applyVimMove '{move}' -> '{adjustedMove}'" + for i in 0.. 0: + (it.first, editor.applyMove(it.last, "column", -1).last).toSelection + elif it.first.line + 1 < editor.lineCount: + (editor.applyMove(it.first, "column", 1).last, it.last).toSelection + else: + it + else: + if it.first.line > 0: + (editor.applyMove(it.first, "column", -1).last, it.last).toSelection + elif it.last.line + 1 < editor.lineCount: + (it.first, editor.applyMove(it.last, "column", 1).last).toSelection + else: + it + ) + + return selections.mapIt(it.normalized.first.toSelection) + +proc deleteSelection(editor: TextEditor, forceInclusiveEnd: bool, oldSelections: Option[seq[Selection]] = seq[Selection].none) {.exposeActive(editorContext).} = + let newSelections = editor.copySelection(getVimDefaultRegister()) + let selectionsToDelete = editor.selections + if oldSelections.isSome: + editor.setSelections oldSelections.get + editor.addNextCheckpoint(ws"insert") + let inclusiveEnd = (not editor.vimState.selectLines) and (editor.vimState.deleteInclusiveEnd or forceInclusiveEnd) + editor.setSelections editor.edit(selectionsToDelete, @@[ws""], inclusive = inclusiveEnd) + editor.scrollToCursor() + editor.vimState.deleteInclusiveEnd = true + editor.setMode "vim.normal" + +proc changeSelection*(editor: TextEditor, forceInclusiveEnd: bool, oldSelections: Option[seq[Selection]] = seq[Selection].none) {.exposeActive(editorContext).} = + let newSelections = editor.copySelection(getVimDefaultRegister()) + let selectionsToDelete = editor.selections + if oldSelections.isSome: + editor.setSelections oldSelections.get + editor.addNextCheckpoint(ws"insert") + let inclusive = editor.vimState.deleteInclusiveEnd or forceInclusiveEnd + editor.setSelections editor.edit(selectionsToDelete, @@[ws""], inclusive = inclusive) + editor.scrollToCursor() + editor.vimState.deleteInclusiveEnd = true + editor.setMode "vim.insert" + +proc yankSelection*(editor: TextEditor) {.exposeActive(editorContext).} = + let selections = editor.copySelection(getVimDefaultRegister()) + editor.setSelections selections + editor.setMode "vim.normal" + +proc yankSelectionClipboard*(editor: TextEditor) {.exposeActive(editorContext).} = + let selections = editor.copySelection() + editor.setSelections selections + editor.setMode "vim.normal" + +template mergeSelections*(a, b: WitList[Selection], body: untyped): seq[Selection] = + let aa = a + let bb = b + collect(newSeq): + for i in 0..min(aa.high, bb.high): + let it1 {.inject.} = aa[i] + let it2 {.inject.} = bb[i] + body + +proc vimReplace(editor: TextEditor, input: string) {.exposeActive(editorContext).} = + let content = editor.content + debugf"vimReplace '{input}'" + # let selections = mergeSelections(editor.selections, editor.multiMove(editor.selections, ws"column", 1, true, true)): + # (it1.first, it2.last).toSelection + let selections = editor.selections + + debugf"{selections}" + let texts = selections.mapIt(block: + let selection = it + debugf"slice selection {selection}" + let selectedText = content.sliceSelection(selection, inclusive=true) + debugf"'{selectedText.text}'" + var newText = newStringOfCap(selectedText.bytes.int * input.len.int) + var lastIndex = 0 + var index = selectedText.find(ws"\n", 0) + debugf"nl: {index}, {selectedText.runes.int}" + if index.isNone: + newText.add input.repeat(selectedText.runes.int) + else: + while index.isSome: + let lineLen = selectedText.slice(lastIndex, index.get).runes.int - 1 + newText.add input.repeat(lineLen) + newText.add "\n" + lastIndex = index.get.int + 1 + index = selectedText.find(ws"\n", index.get + 1) + + let lineLen = selectedText.slice(lastIndex, selectedText.bytes.int - 1).runes.int + newText.add input.repeat(lineLen) + debugf"'{newText}'" + + stackWitString(newText) + ) + + debugf"replace {editor.selections} with '{input}' -> {texts}" + + editor.addNextCheckpoint ws"insert" + editor.setSelections editor.edit(editor.selections, @@texts, inclusive=true).mapIt(it.first.toSelection) + editor.normalMode() + +proc selectMove(editor: TextEditor, move: string, count: int = 0) {.exposeActive(editorContext).} = + # debugf"selectMove {move}" + let res = editor.applyVimMove(move, "(merge)", count) + if res.updateTargetColumn: + editor.updateTargetColumn() + editor.scrollToCursor() + +proc deleteMove(editor: TextEditor, move: string, count: int = 0) {.exposeActive(editorContext).} = + editor.recordCurrentCommandInPeriodMacro() + let oldSelections = @(editor.selections) + let res = editor.applyVimMove(move, "(merge)", count) + editor.deleteSelection(false, oldSelections=oldSelections.some) + if res.updateTargetColumn: + editor.updateTargetColumn() + +proc changeMove(editor: TextEditor, move: string, count: int = 0) {.exposeActive(editorContext).} = + editor.recordCurrentCommandInPeriodMacro() + let oldSelections = @(editor.selections) + let res = editor.applyVimMove(move, "(merge)", count) + editor.changeSelection(false, oldSelections=oldSelections.some) + if res.updateTargetColumn: + editor.updateTargetColumn() + +proc yankMove(editor: TextEditor, move: string, count: int = 0) {.exposeActive(editorContext).} = + discard editor.applyVimMove(move, "(merge)", count) + editor.yankSelection() + +proc vimClamp*(editor: TextEditor, cursor: Cursor): Cursor = + var lineLen = editor.lineLength(cursor.line) + if not editor.vimState.cursorIncludeEol and lineLen > 0: lineLen.dec + result = (cursor.line, min(cursor.column, lineLen)) + +proc vimMotionParagraphInner*(data: uint32, text: sink Rope, selections: openArray[Selection], count: int, includeEol: bool): seq[Selection] {.cdecl.} = + debugf"vimMotionParagraphInner {data}, {selections}, {count}, {includeEol}" + selections.mapIt: + let isEmpty = text.lineLength(it.last.line) == 0 + + var res = ((it.last.line.int, 0).toCursor, it.last).toSelection + while res.first.line - 1 >= 0 and (text.lineLength(res.first.line - 1) == 0) == isEmpty: + dec res.first.line + while res.last.line + 1 < text.lines and (text.lineLength(res.last.line + 1) == 0) == isEmpty: + inc res.last.line + + res.last.column = text.lineLength(res.last.line).int32 + res + +proc vimMotionParagraphOuter*(data: uint32, text: sink Rope, selections: openArray[Selection], count: int, includeEol: bool): seq[Selection] {.cdecl.} = + result = vimMotionParagraphInner(data, text, selections, count, includeEol) + # todo + # if result.last.line + 1 < editor.lineCount: + # result = result or vimMotionParagraphInner(data, text, (result.last.line.int + 1, 0).toCursor, 1, includeEol) + +addCustomTextMove "vim.paragraph-inner", vimMotionParagraphInner +addCustomTextMove "vim.paragraph-outer", vimMotionParagraphOuter + +iterator iterateTextObjects*(editor: TextEditor, cursor: Cursor, move: string, backwards: bool = false): Selection = + var selection = editor.applyMove(cursor, move, 0) + # debugf"iterateTextObjects({cursor}, {move}, {backwards}), selection: {selection}" + yield selection + while true: + let lastSelection = selection + if not backwards and selection.last.column >= editor.lineLength(selection.last.line) - 1: + if selection.last.line == editor.lineCount - 1: + break + selection = (selection.last.line.int + 1, 0).toSelection + elif backwards and selection.first.column == 0: + if selection.first.line == 0: + break + selection = (selection.first.line - 1, editor.lineLength(selection.first.line - 1)).toSelection + if selection.first.column == 0: + yield selection + continue + + let nextCursor = if backwards: (selection.first.line, selection.first.column - 1) else: (selection.last.line, selection.last.column + 1) + let newSelection = editor.applyMove(nextCursor, move, 0) + # debugf"iterateTextObjects({cursor}, {move}, {backwards}) nextCursor: {nextCursor}, newSelection: {newSelection}" + if newSelection == lastSelection: + break + + selection = newSelection + yield selection + +iterator enumerateTextObjects*(editor: TextEditor, cursor: Cursor, move: string, backwards: bool = false): (int, Selection) = + var i = 0 + for selection in iterateTextObjects(editor, cursor, move, backwards): + yield (i, selection) + inc i + +proc selectTextObject(editor: TextEditor, textObject: string, count: int = 1, textObjectRange: VimTextObjectRange = Inner) {.exposeActive(editorContext).} = + debugf"selectTextObject({textObject}, {textObjectRange}, {count})" + + editor.setSelections editor.selections.mapIt(block: + var res = it.last + var resultSelection = it + # debugf"-> {resultSelection}" + + for i, selection in enumerateTextObjects(editor, res, textObject, false): + debugf"{i}: {res} -> {selection}" + resultSelection = resultSelection or selection + if i == max(count, 1) - 1: + break + + # debugf"selectTextObject({textObject}, {textObjectRange}, {count}): {resultSelection}" + if it.isBackwards: + resultSelection.reverse + else: + resultSelection + ) + + editor.scrollToCursor() + editor.updateTargetColumn() + +proc selectSurrounding(editor: TextEditor, textObject: string, count: int = 1, textObjectRange: VimTextObjectRange = Inner) {.exposeActive(editorContext).} = + debugf"selectSurrounding({textObject}, {textObjectRange}, {count})" + + let selections = editor.selections + let newSelections = mergeSelections(selections, editor.multiMove(selections, ws(textObject), count, wrap = false, includeEol = editor.vimState.cursorIncludeEol)): + if it1.isBackwards: + it2.reverse + else: + it2 + editor.setSelections newSelections + + editor.scrollToCursor() + editor.updateTargetColumn() + +proc moveSelectionNext(editor: TextEditor, move: string, backwards: bool = false, allowEmpty: bool = false, count: int = 1) {.exposeActive(editorContext).} = + # debugf"moveSelectionNext '{move}' {count} {backwards} {allowEmpty}" + let text = editor.content + editor.vimState.deleteInclusiveEnd = false + let which = getSetting[sca.SelectionCursor](editor.getContextWithMode("editor.text.cursor.movement"), sca.SelectionCursor.Both) + editor.setSelections editor.selections.mapIt(block: + var res = it.last + for k in 0..= editor.lineLength(selection.first.line) or text.charAt(selection.first) notin Whitespace: + res = cursor + break + # echo res, ", ", it, ", ", which + res.toSelection(it, which) + ) + + editor.scrollToCursor() + editor.updateTargetColumn() + +proc applyMove(editor: TextEditor, selections: openArray[Selection], move: string, backwards: bool = false, allowEmpty: bool = false, count: int = 1, which: Option[sca.SelectionCursor] = sca.SelectionCursor.none): seq[Selection] = + ## Applies the given move `count` times and returns the resulting selections + ## `allowEmpty` If true then the move can stop on empty lines + ## `backwards` Move backwards + ## `count` How often to apply the move + ## `which` How to assemble the final selection from the input and the move. If not set uses `editor.text.cursor.movement` + + # debugf"applyMove '{move}' {count} {backwards} {allowEmpty}" + let text = editor.content + let which = which.get(getSetting[sca.SelectionCursor](editor.getContextWithMode("editor.text.cursor.movement"), sca.SelectionCursor.Both)) + return selections.mapIt(block: + var res = it.last + for k in 0.. 1: + editor.moveCursorLine(count - 1) + editor.moveFirst "line-no-indent" + editor.scrollToCursor() + editor.updateTargetColumn() + +proc paste(editor: TextEditor, pasteRight: bool = false, inclusiveEnd: bool = false, register: string = "") {.exposeActive(editorContext).} = + # debugf"vimPaste {register}, lines: {yankedLines}, pasteRight: {pasteRight}" + let register = if register == "vim.default-register": + getVimDefaultRegister() + else: + register + + editor.addNextCheckpoint ws"insert" + + var selections = editor.getSelections + + if yankedLines and $editor.mode == "vim.normal": + selections = editor.multiMove(selections, ws"line", 1, wrap = false, includeEol = true).mapIt(it.last.toSelection).stackWitList() + selections = editor.edit(selections, @@[ws("\n")], inclusive=false).mapIt(it.last.toSelection).stackWitList() + elif pasteRight: + selections = editor.multiMove(selections, ws"column", 1, false, true).mapIt(it.last.toSelection).stackWitList() + + editor.setMode "vim.normal" + editor.paste selections, register.stackWitString, inclusiveEnd=inclusiveEnd + +proc toggleCase(editor: TextEditor, moveCursorRight: bool) {.exposeActive(editorContext).} = + var editTexts: seq[WitString] + + let content = editor.content + for s in editor.selections: + let text = content.sliceSelection(s, inclusive=true).text + var newText = newStringOfCap(text.len) + for r in text.toOpenArray.runes: + if r.isLower: + newText.add $r.toUpper + else: + newText.add $r.toLower + editTexts.add newText.stackWitString() + + editor.addNextCheckpoint ws"insert" + let oldSelections = editor.selections + discard editor.edit(editor.selections, editTexts.stackWitList(), inclusive=true) + editor.setSelections oldSelections.mapIt(it.first.toSelection).stackWitList() + + editor.setMode "vim.normal" + + if moveCursorRight: + editor.moveCursorColumn(1, wrap=false, includeEol=editor.vimState.cursorIncludeEol) + editor.updateTargetColumn() + +# todo +# proc vimCloseCurrentViewOrQuit() {.exposeActive(editorContext, "vim-close-current-view-or-quit").} = +# let openEditors = getNumVisibleViews() + getNumHiddenViews() +# if openEditors == 1: +# plugin_runtime.quit() +# else: +# closeActiveView() + +proc indent(editor: TextEditor) {.exposeActive(editorContext).} = + editor.addNextCheckpoint ws"insert" + editor.indent(1) + +proc unindent(editor: TextEditor) {.exposeActive(editorContext).} = + editor.addNextCheckpoint ws"insert" + editor.indent(-1) + +proc addCursorAbove(editor: TextEditor) {.exposeActive(editorContext).} = + var selections = @(editor.getSelections.toOpenArray) + let newSelections = editor.multiMove(@@[selections.last], ws"line-up", 0, wrap=false, includeEol=false).mapIt(it.last.toSelection) + selections.add newSelections + editor.setSelections selections + editor.scrollToCursor() + +proc addCursorBelow(editor: TextEditor) {.exposeActive(editorContext).} = + var selections = @(editor.getSelections.toOpenArray) + let newSelections = editor.multiMove(@@[selections.last], ws"line-down", 0, wrap=false, includeEol=false).mapIt(it.last.toSelection) + selections.add newSelections + editor.setSelections selections + editor.scrollToCursor() + +proc enter(editor: TextEditor) {.exposeActive(editorContext).} = + debugf"vim.enter" + editor.addNextCheckpoint ws"insert" + editor.insertText ws("\n"), autoIndent=true + +proc yankLine(editor: TextEditor) {.exposeActive(editorContext).} = + editor.vimState.selectLines = true + editor.selectLine() + editor.yankSelection() + editor.vimState.selectLines = false + +proc deleteLine(editor: TextEditor) {.exposeActive(editorContext).} = + editor.vimState.selectLines = true + let oldSelections = editor.getSelections + editor.selectLine() + editor.deleteSelection(true, oldSelections=some(@oldSelections)) + editor.vimState.selectLines = false + +proc changeLine(editor: TextEditor) {.exposeActive(editorContext).} = + let oldSelections = editor.getSelections + editor.selectLine() + editor.changeSelection(true, oldSelections=some(@oldSelections)) + +proc deleteToLineEnd(editor: TextEditor) {.exposeActive(editorContext).} = + let oldSelections = editor.getSelections + let selections = mergeSelections(editor.selections, editor.multiMove(editor.selections, ws"line", 1, wrap = false, includeEol = true)): + (it1.last, it2.last).toSelection + editor.setSelections selections + editor.deleteSelection(true, oldSelections=some(@oldSelections)) + editor.vimState.selectLines = false + +proc changeToLineEnd(editor: TextEditor) {.exposeActive(editorContext).} = + let oldSelections = editor.getSelections + let selections = mergeSelections(editor.selections, editor.multiMove(editor.selections, ws"line", 1, wrap = false, includeEol = true)): + (it1.last, it2.last).toSelection + editor.setSelections selections + editor.changeSelection(true, oldSelections=some(@oldSelections)) + editor.vimState.selectLines = false + +proc yankToLineEnd(editor: TextEditor) {.exposeActive(editorContext).} = + let selections = mergeSelections(editor.selections, editor.multiMove(editor.selections, ws"line", 1, wrap = false, includeEol = true)): + (it1.last, it2.last).toSelection + editor.setSelections selections + editor.yankSelection() + +proc moveFileStart(editor: TextEditor, count: int = 1) {.exposeActive(editorContext).} = + let which = getSetting[sca.SelectionCursor](editor.getContextWithMode("editor.text.cursor.movement"), sca.SelectionCursor.Both) + editor.setSelection (count - 1, 0).toSelection(editor.getSelection, which) + editor.moveFirst "line-no-indent" + editor.scrollToCursor() + editor.setNextSnapBehaviour(MinDistanceOffscreen) + +proc moveFileEnd(editor: TextEditor, count: int = 1) {.exposeActive(editorContext).} = + let line = if count == 0: editor.content.lines.int - 1 else: count - 1 + let which = getSetting[sca.SelectionCursor](editor.getContextWithMode("editor.text.cursor.movement"), sca.SelectionCursor.Both) + var newSelection = (line, 0).toSelection(editor.getSelection, which) + if newSelection == editor.getSelection: + let lineLen = editor.lineLength(line.int32).int + editor.setSelection (line, lineLen).toSelection(editor.getSelection, which) + else: + editor.setSelection newSelection + editor.moveFirst "line-no-indent" + editor.scrollToCursor() + editor.setNextSnapBehaviour(MinDistanceOffscreen) + +proc scrollLineToTopAndMoveLineStart(editor: TextEditor, count: int = 1) {.exposeActive(editorContext).} = + if editor.getCommandCount != 0: + editor.setSelection (editor.getCommandCount.int, 0).toCursor.toSelection + editor.setSelections editor.multiMove(editor.selections, ws"line-no-indent", 1, wrap = false, includeEol = editor.vimState.cursorIncludeEol).mapIt(it.first.toSelection).stackWitList() + editor.setCursorScrollOffset editor.selections.last.last, getVimLineMargin() + +proc scrollLineToTop(editor: TextEditor, count: int = 1) {.exposeActive(editorContext).} = + if editor.getCommandCount != 0: + editor.setSelection (editor.getCommandCount, editor.selections.last.last.column).toSelection + editor.setCursorScrollOffset editor.selections.last.last, getVimLineMargin() + +proc centerLineAndMoveLineStart(editor: TextEditor, count: int = 1) {.exposeActive(editorContext).} = + if editor.getCommandCount != 0: + editor.setSelection (editor.getCommandCount.int, 0).toCursor.toSelection + editor.setSelections editor.multiMove(editor.selections, ws"line-no-indent", 1, wrap = false, includeEol = editor.vimState.cursorIncludeEol).mapIt(it.first.toSelection).stackWitList() + editor.scrollToCursor(ScrollBehaviour.CenterAlways.some, 0.5) + +proc centerLine(editor: TextEditor, count: int = 1) {.exposeActive(editorContext).} = + editor.scrollToCursor(ScrollBehaviour.CenterAlways.some, 0.5) + +proc scrollLineToBottomAndMoveLineStart(editor: TextEditor, count: int = 1) {.exposeActive(editorContext).} = + if editor.getCommandCount != 0: + editor.setSelection (editor.getCommandCount.int, 0).toCursor.toSelection + editor.setSelections editor.multiMove(editor.selections, ws"line-no-indent", 1, wrap = false, includeEol = editor.vimState.cursorIncludeEol).mapIt(it.first.toSelection).stackWitList() + editor.setCursorScrollOffset editor.selections.last.last, (editor.getVisibleLineCount().float - getVimLineMargin()) + +proc scrollLineToBottom(editor: TextEditor, count: int = 1) {.exposeActive(editorContext).} = + if editor.getCommandCount != 0: + editor.setSelection (editor.getCommandCount, editor.selections.last.last.column).toSelection + editor.setCursorScrollOffset editor.selections.last.last, (editor.getVisibleLineCount().float - getVimLineMargin()) + +proc insertMode(editor: TextEditor, move: string = "") {.exposeActive(editorContext).} = + # debugf"insertMode '{move}'" + case move + of "right": + editor.setSelections editor.multiMove(editor.selections, ws"column", 1, wrap = false, includeEol = true).mapIt(it.last.toSelection).stackWitList() + of "line-end": + editor.setSelections editor.selections.mapIt(editor.applyMove(it.last, "line", 1).last.toSelection) + of "line-no-indent": + editor.setSelections editor.selections.mapIt(editor.applyMove(it.last, "line-no-indent", 1).first.toSelection) + of "first": + editor.setSelections editor.selections.mapIt(it.normalized.first.toSelection) + of "line-start": + editor.setSelections editor.selections.mapIt(editor.applyMove(it.last, "line", 1).first.toSelection) + else: + discard + editor.setMode "vim.insert" + editor.addNextCheckpoint ws"insert" + +proc insertLineBelow(editor: TextEditor) {.exposeActive(editorContext).} = + editor.setSelections editor.multiMove(editor.getSelections, ws"line", 0, wrap=false, includeEol=true).mapIt(it.last.toSelection) + editor.addNextCheckpoint ws"insert" + editor.insertText ws("\n"), autoIndent=true + editor.setMode "vim.insert" + +proc insertLineAbove(editor: TextEditor, move: string = "") {.exposeActive(editorContext).} = + editor.setSelections editor.multiMove(editor.getSelections, ws"line", 0, wrap=false, includeEol=true).mapIt(it.first.toSelection) + editor.addNextCheckpoint ws"insert" + editor.insertText ws("\n"), autoIndent=false + editor.moveDirection("line-up", 1, 1, false, false) + editor.setMode "vim.insert" + +proc setSearchQueryFromWord(editor: TextEditor) {.exposeActive(editorContext).} = + editor.setSelection editor.setSearchQueryFromMove(ws"word", 1, prefix=ws(r"\b"), suffix=ws(r"\b")).first.toSelection + +proc setSearchQueryFromSelection(editor: TextEditor) {.exposeActive(editorContext).} = + let content = editor.content.sliceSelection(editor.getSelection, inclusive=true) + discard editor.setSearchQuery(content.text, escapeRegex=true, prefix=ws"", suffix=ws"") + editor.setSelection editor.getSelection.first.toSelection + editor.normalMode() + +proc openSearchBar(editor: TextEditor) {.exposeActive(editorContext).} = + editor.openSearchBar(ws"", scrollToPreview=true, selectResult=true) + +proc exitCommandLine() {.command.} = + if activeTextEditor({IncludeCommandLine}).getSome(editor): + let mode = $editor.mode + if mode == "vim.normal": + commands.exitCommandLine() + return + + editor.setMode("vim.normal") + +proc exitPopup() {.command.} = + if activeTextEditor({IncludePopups}).getSome(editor) and $editor.mode != "vim.normal": + editor.setMode("vim.normal") + return + + discard runCommand(ws"close-active-view", ws"") + +proc selectWordOrAddCursor(editor: TextEditor) {.exposeActive(editorContext).} = + let selections = editor.selections + if selections.len == 1: + var selection = editor.setSearchQueryFromMove(ws"(word)", 1, prefix=ws(r"\b"), suffix=ws(r"\b")) + editor.setSelection editor.multiMove([selection], ws"(inclusive)").last + else: + let next = editor.multiMove(@@[selections.last], ws"(next-search-result) (inclusive)", 0, wrap = true, includeEol=false).last + let newSelections = @selections & next + editor.setSelections @@newSelections + editor.scrollToCursor() + editor.setNextSnapBehaviour(MinDistanceOffscreen) + editor.updateTargetColumn() + + editor.setMode("vim.visual") + +proc moveLastSelectionToNextSearchResult(editor: TextEditor) {.exposeActive(editorContext).} = + let selections = editor.selections + if selections.len == 1: + var selection = editor.setSearchQueryFromMove(ws"(word)", 1, prefix=ws(r"\b"), suffix=ws(r"\b")) + editor.setSelection editor.multiMove([selection], "(inclusive)").last + editor.setSelection selection + else: + let next = editor.multiMove(@@[selections.last], ws"(next-search-result) (inclusive)", 0, wrap = true, includeEol=false).last + let newSelections = selections.toOpenArray[0..^2] & next + editor.setSelections @@newSelections + editor.scrollToCursor() + editor.setNextSnapBehaviour(MinDistanceOffscreen) + editor.updateTargetColumn() + + editor.setMode("vim.visual") + +proc setSearchQueryOrAddCursor(editor: TextEditor) {.exposeActive(editorContext).} = + let selections = editor.selections + debugf"setSearchQueryOrAddCursor {selections}, {selections.last}" + if selections.len == 1: + let selectedText = editor.content.sliceSelection(selections.last, inclusive=true) + let textEscaped = ($selectedText.text).escapeRegex + let currentSearchQuery = $editor.getSearchQuery() + debugf"{selectedText.bytes}, '{selectedText.text}' -> '{textEscaped}' -> '{currentSearchQuery}'" + if textEscaped != currentSearchQuery and r"\b" & textEscaped & r"\b" != currentSearchQuery: + if editor.setSearchQuery(selectedText.text, escapeRegex=true, prefix=ws"", suffix=ws""): + return + + let next = editor.multiMove(@@[selections.last], ws"(next-search-result) (inclusive)", 0, wrap = true, includeEol=false).last + let newSelections = @selections & next + editor.setSelections @@newSelections + editor.scrollToCursor() + editor.updateTargetColumn() + +# todo +# proc vimSaveState() {.expose("vim-save-state").} = +# try: +# var states = initTable[string, JsonNode]() + +# for id, state in editorStates: +# if id.isTextEditor(editor): +# let filename = editor.getFileName() +# if filename == "": +# continue + +# var marks = initTable[string, seq[Selection]]() +# for name, anchors in editor.vimState.marks: +# let selections = editor.resolveAnchors(anchors) +# marks[name] = selections +# for name, selections in editor.vimState.unresolvedMarks: +# marks[name] = selections + +# if marks.len > 0: +# states[filename] = %*{ +# "marks": marks.toJson, +# } + +# setSessionData("vim.states", states) +# except: +# debugf"Failed to save vim editor states" + +proc resolveMarks(editor: TextEditor) = + let unresolvedMarks = editor.vimState.unresolvedMarks + for name, selections in unresolvedMarks: + let anchors = @(editor.createAnchors(selections.stackWitList())) + if anchors.len > 0: + editor.vimState.marks[name] = anchors + editor.vimState.unresolvedMarks.del(name) + +proc addMark(editor: TextEditor, name: string) {.exposeActive(editorContext).} = + editor.resolveMarks() + editor.vimState.marks[name] = @(editor.createAnchors(editor.selections)) + +proc gotoMark(editor: TextEditor, name: string) {.exposeActive(editorContext).} = + editor.resolveMarks() + + if name in editor.vimState.marks: + let newSelections = editor.resolveAnchors(editor.vimState.marks[name].stackWitList()) + if newSelections.len == 0: + return + + case $editor.mode + of "vim.visual", "vim.visual-line": + let oldSelections = editor.selections + if newSelections.len == oldSelections.len: + editor.setSelections stackWitList(collect(block: + for i in 0..newSelections.high: + oldSelections[i] or newSelections[i] + )) + else: + editor.setSelections newSelections + else: + editor.setSelections newSelections + + editor.updateTargetColumn() + editor.scrollToCursor() + editor.setNextSnapBehaviour(MinDistanceOffscreen) + +proc deleteWordBack(editor: TextEditor) {.exposeActive(editorContext).} = + let wordSelections = editor.multiMove(editor.selections, ws"vim.word-back", 1, wrap = false, includeEol = true) + let selectionsToDelete = mergeSelections(wordSelections, editor.selections, (it1.first, it2.last).toSelection) + editor.setSelections editor.edit(selectionsToDelete.stackWitList(), @@[ws""], inclusive = false) + editor.autoShowCompletions() + +proc deleteLineBack(editor: TextEditor) {.exposeActive(editorContext).} = + let lineSelections = editor.selections.mapIt ((it.last.line.int, 0).toCursor, it.last).toSelection + editor.setSelections editor.edit(lineSelections.stackWitList(), @@[ws""], inclusive = false) + editor.autoShowCompletions() + +proc includeSelectionEnd*(self: TextEditor, res: Selection, includeAfter: bool = true): Selection = + result = res + if not includeAfter: + result = (res.first, self.applyMove(res.last, "column", -1, wrap = false, includeEol = true).last).toSelection + +proc surround(editor: TextEditor, text: string) {.exposeActive(editorContext).} = + let (left, right) = case text + of "(", ")": (ws"(", ws")") + of "{", "}": (ws"{", ws"}") + of "[", "]": (ws"[", ws"]") + of "<", ">": (ws"<", ws">") + else: + let text = text.stackWitString() + (text, text) + + let selections = editor.selections.mapIt(it.normalized).stackWitList() + let rightCursors = editor.multiMove(selections, ws"column", 1, wrap = false, includeEol = true) + + var insertSelections = newSeq[Selection](selections.len * 2) + var insertTexts = newSeq[WitString](selections.len * 2) + for i, s in selections: + insertSelections[i * 2 + 0] = s.first.toSelection + insertSelections[i * 2 + 1] = rightCursors[i].last.toSelection + insertTexts[i * 2 + 0] = left + insertTexts[i * 2 + 1] = right + + editor.addNextCheckpoint ws"insert" + let newSelections = editor.edit(insertSelections.stackWitList(), insertTexts.stackWitList(), inclusive = false) + if newSelections.len mod 2 != 0: + return + + let newSelectionsInclusive = collect: + for i in 0.. {newModes}" + + let oldMode = if oldModes.len > 0: + oldModes[0] + else: + "" + + if newModes.len == 0: + return + + let newMode = newModes[0] + + if not editor.modes().toOpenArray.contains(ws"vim"): + return + + if newMode == "": + editor.setMode "vim.normal" + return + + if not newMode.startsWith("vim"): + return + + let recordModes = [ + "vim.visual", + "vim.visual-line", + "vim.insert", + ].toHashSet + + # debugf"vim: handle mode change {oldMode} -> {newMode}" + if newMode == "vim.normal": + if not isReplayingCommands() and isRecordingCommands(ws".-temp"): + stopRecordingCommands(ws".-temp") + + if editor.getRevision > editor.vimState.revisionBeforeImplicitInsertMacro: + # debugf"Record implicit macro because document was modified" + let text = getRegisterText(ws".-temp") + setRegisterText(text, ws".") + else: + if oldMode == "vim.normal" and newMode in recordModes: + editor.startRecordingCurrentCommandInPeriodMacro() + + editor.clearCurrentCommandHistory(retainLast=true) + + editor.vimState.selectLines = newMode == "vim.visual-line" + editor.vimState.cursorIncludeEol = newMode == "vim.insert" + editor.vimState.currentUndoCheckpoint = if newMode == "vim.insert": "word" else: "insert" + + case newMode + of "vim.normal": + editor.setSetting "text.inclusive-selection", false + editor.setSelections editor.selections.mapIt(editor.vimClamp(it.last).toSelection) + editor.saveCurrentCommandHistory() + editor.hideCompletions() + + of "vim.insert": + editor.setSetting "text.inclusive-selection", false + + of "vim.visual": + editor.setSetting "text.inclusive-selection", true + + of "vim.visual-line": + editor.setSetting "text.inclusive-selection", false + + else: + editor.setSetting "text.inclusive-selection", false + +# todo +# proc loadVimKeybindings*() {.expose("load-vim-keybindings").} = +# let afterRestoreSessionHandle = addCallback proc(args: JsonNode): JsonNode = +# let states = getSessionData[Table[string, JsonNode]]("vim.states") +# for id in getAllEditors(): +# if id.isTextEditor(editor): +# try: +# let filename = editor.getFileName() +# if states.hasKey(filename): +# let editorState = states[filename] +# if editorState.hasKey("marks"): +# let marks = editorState["marks"].jsonTo(Table[string, seq[Selection]]) +# for name, selections in marks: +# editor.vimState.unresolvedMarks[name] = selections +# except: +# debugf"Failed to restore marks for {editor}" +# scriptSetCallback("after-restore-session", afterRestoreSessionHandle) + +# let beforeSaveAppStateHandle = addCallback proc(args: JsonNode): JsonNode = +# vimSaveState() +# scriptSetCallback("before-save-app-state", beforeSaveAppStateHandle) \ No newline at end of file diff --git a/plugins/vim/vim.nimble b/plugins/vim/vim.nimble new file mode 100644 index 000000000..934766a7f --- /dev/null +++ b/plugins/vim/vim.nimble @@ -0,0 +1,10 @@ +requires "nim >= 2.0.0" +requires "https://github.com/Nimaoth/vmath#661bdaa" +requires "bumpy >= 1.1.2" +requires "chroma >= 0.2.7" +requires "fusion >= 1.2" +requires "regex >= 0.25.0" +requires "results >= 0.5.0" +requires "https://github.com/Nimaoth/nimwasmtime#415a252" +requires "glob#64f71af" # "glob >= 0.11.2" # the newest version of glob doesn't have a version but is required for Nim 2.0 + diff --git a/scripting/collab_api_wasm.nim b/scripting/collab_api_wasm.nim deleted file mode 100644 index ca9dbd19b..000000000 --- a/scripting/collab_api_wasm.nim +++ /dev/null @@ -1,23 +0,0 @@ -import std/[json, options] -import scripting_api, misc/myjsonutils - -## This file is auto generated, don't modify. - - -proc collab_connectCollaborator_void_int_wasm(arg: cstring): cstring {.importc.} -proc connectCollaborator*(port: int = 6969) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add port.toJson() - let argsJsonString = $argsJson - let res {.used.} = collab_connectCollaborator_void_int_wasm( - argsJsonString.cstring) - - -proc collab_hostCollaborator_void_int_wasm(arg: cstring): cstring {.importc.} -proc hostCollaborator*(port: int = 6969) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add port.toJson() - let argsJsonString = $argsJson - let res {.used.} = collab_hostCollaborator_void_int_wasm( - argsJsonString.cstring) - diff --git a/scripting/commands_api_wasm.nim b/scripting/commands_api_wasm.nim deleted file mode 100644 index 8310d209e..000000000 --- a/scripting/commands_api_wasm.nim +++ /dev/null @@ -1,93 +0,0 @@ -import std/[json, options] -import scripting_api, misc/myjsonutils - -## This file is auto generated, don't modify. - - -proc commands_commandLine_void_CommandService_string_string_wasm(arg: cstring): cstring {. - importc.} -proc commandLine*(initialValue: string = ""; prefix: string = "") {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add initialValue.toJson() - argsJson.add prefix.toJson() - let argsJsonString = $argsJson - let res {.used.} = commands_commandLine_void_CommandService_string_string_wasm( - argsJsonString.cstring) - - -proc commands_exitCommandLine_void_CommandService_wasm(arg: cstring): cstring {. - importc.} -proc exitCommandLine*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = commands_exitCommandLine_void_CommandService_wasm( - argsJsonString.cstring) - - -proc commands_commandLineResult_void_CommandService_string_bool_bool_string_wasm( - arg: cstring): cstring {.importc.} -proc commandLineResult*(value: string; showInCommandLine: bool = false; - appendAndShowInFile: bool = false; - filename: string = "ed://.shell-command-results") {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add value.toJson() - argsJson.add showInCommandLine.toJson() - argsJson.add appendAndShowInFile.toJson() - argsJson.add filename.toJson() - let argsJsonString = $argsJson - let res {.used.} = commands_commandLineResult_void_CommandService_string_bool_bool_string_wasm( - argsJsonString.cstring) - - -proc commands_clearCommandLineResults_void_CommandService_wasm(arg: cstring): cstring {. - importc.} -proc clearCommandLineResults*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = commands_clearCommandLineResults_void_CommandService_wasm( - argsJsonString.cstring) - - -proc commands_executeCommandLine_bool_CommandService_wasm(arg: cstring): cstring {. - importc.} -proc executeCommandLine*(): bool {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = commands_executeCommandLine_bool_CommandService_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc commands_selectPreviousCommandInHistory_void_CommandService_wasm( - arg: cstring): cstring {.importc.} -proc selectPreviousCommandInHistory*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = commands_selectPreviousCommandInHistory_void_CommandService_wasm( - argsJsonString.cstring) - - -proc commands_selectNextCommandInHistory_void_CommandService_wasm(arg: cstring): cstring {. - importc.} -proc selectNextCommandInHistory*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = commands_selectNextCommandInHistory_void_CommandService_wasm( - argsJsonString.cstring) - - -proc commands_runShellCommand_void_CommandService_RunShellCommandOptions_wasm( - arg: cstring): cstring {.importc.} -proc runShellCommand*(options: RunShellCommandOptions = RunShellCommandOptions()) {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add options.toJson() - let argsJsonString = $argsJson - let res {.used.} = commands_runShellCommand_void_CommandService_RunShellCommandOptions_wasm( - argsJsonString.cstring) - diff --git a/scripting/config_api_wasm.nim b/scripting/config_api_wasm.nim deleted file mode 100644 index fd450e94a..000000000 --- a/scripting/config_api_wasm.nim +++ /dev/null @@ -1,62 +0,0 @@ -import std/[json, options] -import scripting_api, misc/myjsonutils - -## This file is auto generated, don't modify. - - -proc config_logOptions_void_ConfigService_wasm(arg: cstring): cstring {.importc.} -proc logOptions*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = config_logOptions_void_ConfigService_wasm( - argsJsonString.cstring) - - -proc config_setOption_void_ConfigService_string_JsonNode_bool_wasm(arg: cstring): cstring {. - importc.} -proc setOption*(option: string; value: JsonNode; override: bool = true) {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add option.toJson() - argsJson.add value.toJson() - argsJson.add override.toJson() - let argsJsonString = $argsJson - let res {.used.} = config_setOption_void_ConfigService_string_JsonNode_bool_wasm( - argsJsonString.cstring) - - -proc config_getFlag_bool_ConfigService_string_bool_wasm(arg: cstring): cstring {. - importc.} -proc getFlag*(flag: string; default: bool = false): bool {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add flag.toJson() - argsJson.add default.toJson() - let argsJsonString = $argsJson - let res {.used.} = config_getFlag_bool_ConfigService_string_bool_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc config_setFlag_void_ConfigService_string_bool_wasm(arg: cstring): cstring {. - importc.} -proc setFlag*(flag: string; value: bool) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add flag.toJson() - argsJson.add value.toJson() - let argsJsonString = $argsJson - let res {.used.} = config_setFlag_void_ConfigService_string_bool_wasm( - argsJsonString.cstring) - - -proc config_toggleFlag_void_ConfigService_string_wasm(arg: cstring): cstring {. - importc.} -proc toggleFlag*(flag: string) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add flag.toJson() - let argsJsonString = $argsJson - let res {.used.} = config_toggleFlag_void_ConfigService_string_wasm( - argsJsonString.cstring) - diff --git a/scripting/debugger_api_wasm.nim b/scripting/debugger_api_wasm.nim deleted file mode 100644 index 8393dc569..000000000 --- a/scripting/debugger_api_wasm.nim +++ /dev/null @@ -1,281 +0,0 @@ -import std/[json, options] -import scripting_api, misc/myjsonutils - -## This file is auto generated, don't modify. - - -proc debugger_prevDebuggerView_void_Debugger_wasm(arg: cstring): cstring {. - importc.} -proc prevDebuggerView*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = debugger_prevDebuggerView_void_Debugger_wasm( - argsJsonString.cstring) - - -proc debugger_nextDebuggerView_void_Debugger_wasm(arg: cstring): cstring {. - importc.} -proc nextDebuggerView*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = debugger_nextDebuggerView_void_Debugger_wasm( - argsJsonString.cstring) - - -proc debugger_setDebuggerView_void_Debugger_string_wasm(arg: cstring): cstring {. - importc.} -proc setDebuggerView*(view: string) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add view.toJson() - let argsJsonString = $argsJson - let res {.used.} = debugger_setDebuggerView_void_Debugger_string_wasm( - argsJsonString.cstring) - - -proc debugger_selectFirstVariable_void_Debugger_wasm(arg: cstring): cstring {. - importc.} -proc selectFirstVariable*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = debugger_selectFirstVariable_void_Debugger_wasm( - argsJsonString.cstring) - - -proc debugger_selectLastVariable_void_Debugger_wasm(arg: cstring): cstring {. - importc.} -proc selectLastVariable*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = debugger_selectLastVariable_void_Debugger_wasm( - argsJsonString.cstring) - - -proc debugger_prevThread_void_Debugger_wasm(arg: cstring): cstring {.importc.} -proc prevThread*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = debugger_prevThread_void_Debugger_wasm( - argsJsonString.cstring) - - -proc debugger_nextThread_void_Debugger_wasm(arg: cstring): cstring {.importc.} -proc nextThread*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = debugger_nextThread_void_Debugger_wasm( - argsJsonString.cstring) - - -proc debugger_prevStackFrame_void_Debugger_wasm(arg: cstring): cstring {.importc.} -proc prevStackFrame*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = debugger_prevStackFrame_void_Debugger_wasm( - argsJsonString.cstring) - - -proc debugger_nextStackFrame_void_Debugger_wasm(arg: cstring): cstring {.importc.} -proc nextStackFrame*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = debugger_nextStackFrame_void_Debugger_wasm( - argsJsonString.cstring) - - -proc debugger_openFileForCurrentFrame_void_Debugger_string_wasm(arg: cstring): cstring {. - importc.} -proc openFileForCurrentFrame*(slot: string = "") {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add slot.toJson() - let argsJsonString = $argsJson - let res {.used.} = debugger_openFileForCurrentFrame_void_Debugger_string_wasm( - argsJsonString.cstring) - - -proc debugger_prevVariable_void_Debugger_wasm(arg: cstring): cstring {.importc.} -proc prevVariable*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = debugger_prevVariable_void_Debugger_wasm( - argsJsonString.cstring) - - -proc debugger_nextVariable_void_Debugger_wasm(arg: cstring): cstring {.importc.} -proc nextVariable*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = debugger_nextVariable_void_Debugger_wasm( - argsJsonString.cstring) - - -proc debugger_expandVariable_void_Debugger_wasm(arg: cstring): cstring {.importc.} -proc expandVariable*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = debugger_expandVariable_void_Debugger_wasm( - argsJsonString.cstring) - - -proc debugger_collapseVariable_void_Debugger_wasm(arg: cstring): cstring {. - importc.} -proc collapseVariable*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = debugger_collapseVariable_void_Debugger_wasm( - argsJsonString.cstring) - - -proc debugger_stopDebugSession_void_Debugger_wasm(arg: cstring): cstring {. - importc.} -proc stopDebugSession*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = debugger_stopDebugSession_void_Debugger_wasm( - argsJsonString.cstring) - - -proc debugger_stopDebugSessionDelayed_void_Debugger_wasm(arg: cstring): cstring {. - importc.} -proc stopDebugSessionDelayed*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = debugger_stopDebugSessionDelayed_void_Debugger_wasm( - argsJsonString.cstring) - - -proc debugger_runConfiguration_void_Debugger_string_wasm(arg: cstring): cstring {. - importc.} -proc runConfiguration*(name: string) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add name.toJson() - let argsJsonString = $argsJson - let res {.used.} = debugger_runConfiguration_void_Debugger_string_wasm( - argsJsonString.cstring) - - -proc debugger_chooseRunConfiguration_void_Debugger_wasm(arg: cstring): cstring {. - importc.} -proc chooseRunConfiguration*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = debugger_chooseRunConfiguration_void_Debugger_wasm( - argsJsonString.cstring) - - -proc debugger_runLastConfiguration_void_Debugger_wasm(arg: cstring): cstring {. - importc.} -proc runLastConfiguration*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = debugger_runLastConfiguration_void_Debugger_wasm( - argsJsonString.cstring) - - -proc debugger_toggleBreakpointAt_void_Debugger_EditorId_int_wasm(arg: cstring): cstring {. - importc.} -proc toggleBreakpointAt*(editorId: EditorId; line: int) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add editorId.toJson() - argsJson.add line.toJson() - let argsJsonString = $argsJson - let res {.used.} = debugger_toggleBreakpointAt_void_Debugger_EditorId_int_wasm( - argsJsonString.cstring) - - -proc debugger_toggleBreakpoint_void_Debugger_wasm(arg: cstring): cstring {. - importc.} -proc toggleBreakpoint*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = debugger_toggleBreakpoint_void_Debugger_wasm( - argsJsonString.cstring) - - -proc debugger_removeBreakpoint_void_Debugger_string_int_wasm(arg: cstring): cstring {. - importc.} -proc removeBreakpoint*(path: string; line: int) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add path.toJson() - argsJson.add line.toJson() - let argsJsonString = $argsJson - let res {.used.} = debugger_removeBreakpoint_void_Debugger_string_int_wasm( - argsJsonString.cstring) - - -proc debugger_toggleBreakpointEnabled_void_Debugger_string_int_wasm(arg: cstring): cstring {. - importc.} -proc toggleBreakpointEnabled*(path: string; line: int) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add path.toJson() - argsJson.add line.toJson() - let argsJsonString = $argsJson - let res {.used.} = debugger_toggleBreakpointEnabled_void_Debugger_string_int_wasm( - argsJsonString.cstring) - - -proc debugger_toggleAllBreakpointsEnabled_void_Debugger_wasm(arg: cstring): cstring {. - importc.} -proc toggleAllBreakpointsEnabled*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = debugger_toggleAllBreakpointsEnabled_void_Debugger_wasm( - argsJsonString.cstring) - - -proc debugger_toggleBreakpointsEnabled_void_Debugger_wasm(arg: cstring): cstring {. - importc.} -proc toggleBreakpointsEnabled*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = debugger_toggleBreakpointsEnabled_void_Debugger_wasm( - argsJsonString.cstring) - - -proc debugger_editBreakpoints_void_Debugger_wasm(arg: cstring): cstring {. - importc.} -proc editBreakpoints*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = debugger_editBreakpoints_void_Debugger_wasm( - argsJsonString.cstring) - - -proc debugger_continueExecution_void_Debugger_wasm(arg: cstring): cstring {. - importc.} -proc continueExecution*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = debugger_continueExecution_void_Debugger_wasm( - argsJsonString.cstring) - - -proc debugger_stepOver_void_Debugger_wasm(arg: cstring): cstring {.importc.} -proc stepOver*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = debugger_stepOver_void_Debugger_wasm(argsJsonString.cstring) - - -proc debugger_stepIn_void_Debugger_wasm(arg: cstring): cstring {.importc.} -proc stepIn*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = debugger_stepIn_void_Debugger_wasm(argsJsonString.cstring) - - -proc debugger_stepOut_void_Debugger_wasm(arg: cstring): cstring {.importc.} -proc stepOut*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = debugger_stepOut_void_Debugger_wasm(argsJsonString.cstring) - - -proc debugger_showDebuggerView_void_Debugger_string_wasm(arg: cstring): cstring {. - importc.} -proc showDebuggerView*(slot: string = "#debugger") {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add slot.toJson() - let argsJsonString = $argsJson - let res {.used.} = debugger_showDebuggerView_void_Debugger_string_wasm( - argsJsonString.cstring) - diff --git a/scripting/editor_api_wasm.nim b/scripting/editor_api_wasm.nim deleted file mode 100644 index 81192660d..000000000 --- a/scripting/editor_api_wasm.nim +++ /dev/null @@ -1,813 +0,0 @@ -import std/[json, options] -import scripting_api, misc/myjsonutils - -## This file is auto generated, don't modify. - - -proc editor_getOptionJson_JsonNode_ConfigService_string_JsonNode_wasm( - arg: cstring): cstring {.importc.} -proc getOptionJson*(path: string; default: JsonNode = newJNull()): JsonNode {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add path.toJson() - argsJson.add default.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_getOptionJson_JsonNode_ConfigService_string_JsonNode_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_reapplyConfigKeybindings_void_App_bool_bool_bool_bool_wasm( - arg: cstring): cstring {.importc.} -proc reapplyConfigKeybindings*(app: bool = false; home: bool = false; - workspace: bool = false; wait: bool = false) {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add app.toJson() - argsJson.add home.toJson() - argsJson.add workspace.toJson() - argsJson.add wait.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_reapplyConfigKeybindings_void_App_bool_bool_bool_bool_wasm( - argsJsonString.cstring) - - -proc editor_runExternalCommand_void_App_string_seq_string_string_wasm( - arg: cstring): cstring {.importc.} -proc runExternalCommand*(command: string; args: seq[string] = @[]; - workingDir: string = "") {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add command.toJson() - argsJson.add args.toJson() - argsJson.add workingDir.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_runExternalCommand_void_App_string_seq_string_string_wasm( - argsJsonString.cstring) - - -proc editor_disableLogFrameTime_void_App_bool_wasm(arg: cstring): cstring {. - importc.} -proc disableLogFrameTime*(disable: bool) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add disable.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_disableLogFrameTime_void_App_bool_wasm( - argsJsonString.cstring) - - -proc editor_enableDebugPrintAsyncAwaitStackTrace_void_App_bool_wasm(arg: cstring): cstring {. - importc.} -proc enableDebugPrintAsyncAwaitStackTrace*(enable: bool) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add enable.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_enableDebugPrintAsyncAwaitStackTrace_void_App_bool_wasm( - argsJsonString.cstring) - - -proc editor_setLocationListFromCurrentPopup_void_App_wasm(arg: cstring): cstring {. - importc.} -proc setLocationListFromCurrentPopup*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = editor_setLocationListFromCurrentPopup_void_App_wasm( - argsJsonString.cstring) - - -proc editor_getBackend_Backend_App_wasm(arg: cstring): cstring {.importc.} -proc getBackend*(): Backend {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = editor_getBackend_Backend_App_wasm(argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_getHostOs_string_App_wasm(arg: cstring): cstring {.importc.} -proc getHostOs*(): string {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = editor_getHostOs_string_App_wasm(argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_toggleShowDrawnNodes_void_App_wasm(arg: cstring): cstring {.importc.} -proc toggleShowDrawnNodes*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = editor_toggleShowDrawnNodes_void_App_wasm( - argsJsonString.cstring) - - -proc editor_saveAppState_void_App_wasm(arg: cstring): cstring {.importc.} -proc saveAppState*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = editor_saveAppState_void_App_wasm(argsJsonString.cstring) - - -proc editor_requestRender_void_App_bool_wasm(arg: cstring): cstring {.importc.} -proc requestRender*(redrawEverything: bool = false) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add redrawEverything.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_requestRender_void_App_bool_wasm( - argsJsonString.cstring) - - -proc editor_clearWorkspaceCaches_void_App_wasm(arg: cstring): cstring {.importc.} -proc clearWorkspaceCaches*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = editor_clearWorkspaceCaches_void_App_wasm( - argsJsonString.cstring) - - -proc editor_quit_void_App_wasm(arg: cstring): cstring {.importc.} -proc quit*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = editor_quit_void_App_wasm(argsJsonString.cstring) - - -proc editor_quitImmediately_void_App_int_wasm(arg: cstring): cstring {.importc.} -proc quitImmediately*(exitCode: int = 0) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add exitCode.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_quitImmediately_void_App_int_wasm( - argsJsonString.cstring) - - -proc editor_help_void_App_string_wasm(arg: cstring): cstring {.importc.} -proc help*(about: string = "") {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add about.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_help_void_App_string_wasm(argsJsonString.cstring) - - -proc editor_loadWorkspaceFile_void_App_string_string_wasm(arg: cstring): cstring {. - importc.} -proc loadWorkspaceFile*(path: string; callback: string) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add path.toJson() - argsJson.add callback.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_loadWorkspaceFile_void_App_string_string_wasm( - argsJsonString.cstring) - - -proc editor_writeWorkspaceFile_void_App_string_string_wasm(arg: cstring): cstring {. - importc.} -proc writeWorkspaceFile*(path: string; content: string) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add path.toJson() - argsJson.add content.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_writeWorkspaceFile_void_App_string_string_wasm( - argsJsonString.cstring) - - -proc editor_changeFontSize_void_App_float32_wasm(arg: cstring): cstring {. - importc.} -proc changeFontSize*(amount: float32) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add amount.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_changeFontSize_void_App_float32_wasm( - argsJsonString.cstring) - - -proc editor_changeLineDistance_void_App_float32_wasm(arg: cstring): cstring {. - importc.} -proc changeLineDistance*(amount: float32) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add amount.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_changeLineDistance_void_App_float32_wasm( - argsJsonString.cstring) - - -proc editor_platformTotalLineHeight_float32_App_wasm(arg: cstring): cstring {. - importc.} -proc platformTotalLineHeight*(): float32 {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = editor_platformTotalLineHeight_float32_App_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_platformLineHeight_float32_App_wasm(arg: cstring): cstring {.importc.} -proc platformLineHeight*(): float32 {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = editor_platformLineHeight_float32_App_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_platformLineDistance_float32_App_wasm(arg: cstring): cstring {. - importc.} -proc platformLineDistance*(): float32 {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = editor_platformLineDistance_float32_App_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_toggleStatusBarLocation_void_App_wasm(arg: cstring): cstring {. - importc.} -proc toggleStatusBarLocation*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = editor_toggleStatusBarLocation_void_App_wasm( - argsJsonString.cstring) - - -proc editor_logs_void_App_string_bool_bool_wasm(arg: cstring): cstring {.importc.} -proc logs*(slot: string = ""; focus: bool = true; scrollToBottom: bool = false) {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add slot.toJson() - argsJson.add focus.toJson() - argsJson.add scrollToBottom.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_logs_void_App_string_bool_bool_wasm( - argsJsonString.cstring) - - -proc editor_toggleConsoleLogger_void_App_wasm(arg: cstring): cstring {.importc.} -proc toggleConsoleLogger*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = editor_toggleConsoleLogger_void_App_wasm( - argsJsonString.cstring) - - -proc editor_writeFile_void_App_string_bool_wasm(arg: cstring): cstring {.importc.} -proc writeFile*(path: string = ""; appFile: bool = false) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add path.toJson() - argsJson.add appFile.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_writeFile_void_App_string_bool_wasm( - argsJsonString.cstring) - - -proc editor_loadFile_void_App_string_wasm(arg: cstring): cstring {.importc.} -proc loadFile*(path: string = "") {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add path.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_loadFile_void_App_string_wasm(argsJsonString.cstring) - - -proc editor_loadTheme_void_App_string_bool_wasm(arg: cstring): cstring {.importc.} -proc loadTheme*(name: string; force: bool = false) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add name.toJson() - argsJson.add force.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_loadTheme_void_App_string_bool_wasm( - argsJsonString.cstring) - - -proc editor_openSession_void_App_bool_string_bool_float_float_float_wasm( - arg: cstring): cstring {.importc.} -proc openSession*(newWindow: bool = false; root: string = "home://"; - preview: bool = true; scaleX: float = 0.9; - scaleY: float = 0.8; previewScale: float = 0.4) {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add newWindow.toJson() - argsJson.add root.toJson() - argsJson.add preview.toJson() - argsJson.add scaleX.toJson() - argsJson.add scaleY.toJson() - argsJson.add previewScale.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_openSession_void_App_bool_string_bool_float_float_float_wasm( - argsJsonString.cstring) - - -proc editor_openRecentSession_void_App_bool_float_float_float_wasm(arg: cstring): cstring {. - importc.} -proc openRecentSession*(preview: bool = true; scaleX: float = 0.9; - scaleY: float = 0.8; previewScale: float = 0.4) {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add preview.toJson() - argsJson.add scaleX.toJson() - argsJson.add scaleY.toJson() - argsJson.add previewScale.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_openRecentSession_void_App_bool_float_float_float_wasm( - argsJsonString.cstring) - - -proc editor_chooseTheme_void_App_wasm(arg: cstring): cstring {.importc.} -proc chooseTheme*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = editor_chooseTheme_void_App_wasm(argsJsonString.cstring) - - -proc editor_crash_void_App_string_wasm(arg: cstring): cstring {.importc.} -proc crash*(message: string = "") {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add message.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_crash_void_App_string_wasm(argsJsonString.cstring) - - -proc editor_crash2_void_App_wasm(arg: cstring): cstring {.importc.} -proc crash2*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = editor_crash2_void_App_wasm(argsJsonString.cstring) - - -proc editor_createFile_void_App_string_wasm(arg: cstring): cstring {.importc.} -proc createFile*(path: string) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add path.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_createFile_void_App_string_wasm( - argsJsonString.cstring) - - -proc editor_browseKeybinds_void_App_bool_float_float_float_wasm(arg: cstring): cstring {. - importc.} -proc browseKeybinds*(preview: bool = true; scaleX: float = 0.9; - scaleY: float = 0.8; previewScale: float = 0.4) {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add preview.toJson() - argsJson.add scaleX.toJson() - argsJson.add scaleY.toJson() - argsJson.add previewScale.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_browseKeybinds_void_App_bool_float_float_float_wasm( - argsJsonString.cstring) - - -proc editor_browseSettings_void_App_bool_float_float_float_wasm(arg: cstring): cstring {. - importc.} -proc browseSettings*(includeActiveEditor: bool = false; scaleX: float = 0.8; - scaleY: float = 0.8; previewScale: float = 0.5) {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add includeActiveEditor.toJson() - argsJson.add scaleX.toJson() - argsJson.add scaleY.toJson() - argsJson.add previewScale.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_browseSettings_void_App_bool_float_float_float_wasm( - argsJsonString.cstring) - - -proc editor_chooseFile_void_App_bool_float_float_float_wasm(arg: cstring): cstring {. - importc.} -proc chooseFile*(preview: bool = true; scaleX: float = 0.8; scaleY: float = 0.8; - previewScale: float = 0.5) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add preview.toJson() - argsJson.add scaleX.toJson() - argsJson.add scaleY.toJson() - argsJson.add previewScale.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_chooseFile_void_App_bool_float_float_float_wasm( - argsJsonString.cstring) - - -proc editor_chooseOpen_void_App_bool_float_float_float_wasm(arg: cstring): cstring {. - importc.} -proc chooseOpen*(preview: bool = true; scaleX: float = 0.8; scaleY: float = 0.8; - previewScale: float = 0.6) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add preview.toJson() - argsJson.add scaleX.toJson() - argsJson.add scaleY.toJson() - argsJson.add previewScale.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_chooseOpen_void_App_bool_float_float_float_wasm( - argsJsonString.cstring) - - -proc editor_chooseOpenDocument_void_App_wasm(arg: cstring): cstring {.importc.} -proc chooseOpenDocument*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = editor_chooseOpenDocument_void_App_wasm( - argsJsonString.cstring) - - -proc editor_showPlugins_void_App_float_float_float_wasm(arg: cstring): cstring {. - importc.} -proc showPlugins*(scaleX: float = 0.9; scaleY: float = 0.9; - previewScale: float = 0.6) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add scaleX.toJson() - argsJson.add scaleY.toJson() - argsJson.add previewScale.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_showPlugins_void_App_float_float_float_wasm( - argsJsonString.cstring) - - -proc editor_gotoNextLocation_void_App_wasm(arg: cstring): cstring {.importc.} -proc gotoNextLocation*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = editor_gotoNextLocation_void_App_wasm( - argsJsonString.cstring) - - -proc editor_gotoPrevLocation_void_App_wasm(arg: cstring): cstring {.importc.} -proc gotoPrevLocation*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = editor_gotoPrevLocation_void_App_wasm( - argsJsonString.cstring) - - -proc editor_chooseLocation_void_App_wasm(arg: cstring): cstring {.importc.} -proc chooseLocation*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = editor_chooseLocation_void_App_wasm(argsJsonString.cstring) - - -proc editor_searchGlobalInteractive_void_App_wasm(arg: cstring): cstring {. - importc.} -proc searchGlobalInteractive*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = editor_searchGlobalInteractive_void_App_wasm( - argsJsonString.cstring) - - -proc editor_searchGlobal_void_App_string_wasm(arg: cstring): cstring {.importc.} -proc searchGlobal*(query: string) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add query.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_searchGlobal_void_App_string_wasm( - argsJsonString.cstring) - - -proc editor_installTreesitterParser_void_App_string_string_wasm(arg: cstring): cstring {. - importc.} -proc installTreesitterParser*(language: string; host: string = "github.com") {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add language.toJson() - argsJson.add host.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_installTreesitterParser_void_App_string_string_wasm( - argsJsonString.cstring) - - -proc editor_exploreFiles_void_App_string_bool_bool_wasm(arg: cstring): cstring {. - importc.} -proc exploreFiles*(root: string = ""; showVFS: bool = false; - normalize: bool = true) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add root.toJson() - argsJson.add showVFS.toJson() - argsJson.add normalize.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_exploreFiles_void_App_string_bool_bool_wasm( - argsJsonString.cstring) - - -proc editor_exploreWorkspacePrimary_void_App_wasm(arg: cstring): cstring {. - importc.} -proc exploreWorkspacePrimary*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = editor_exploreWorkspacePrimary_void_App_wasm( - argsJsonString.cstring) - - -proc editor_exploreCurrentFileDirectory_void_App_wasm(arg: cstring): cstring {. - importc.} -proc exploreCurrentFileDirectory*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = editor_exploreCurrentFileDirectory_void_App_wasm( - argsJsonString.cstring) - - -proc editor_reloadConfig_void_App_bool_wasm(arg: cstring): cstring {.importc.} -proc reloadConfig*(clearOptions: bool = false) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add clearOptions.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_reloadConfig_void_App_bool_wasm( - argsJsonString.cstring) - - -proc editor_reloadPlugin_void_App_wasm(arg: cstring): cstring {.importc.} -proc reloadPlugin*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = editor_reloadPlugin_void_App_wasm(argsJsonString.cstring) - - -proc editor_reloadTheme_void_App_wasm(arg: cstring): cstring {.importc.} -proc reloadTheme*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = editor_reloadTheme_void_App_wasm(argsJsonString.cstring) - - -proc editor_saveSession_void_App_string_wasm(arg: cstring): cstring {.importc.} -proc saveSession*(sessionFile: string = "") {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add sessionFile.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_saveSession_void_App_string_wasm( - argsJsonString.cstring) - - -proc editor_dumpKeymapGraphViz_void_App_string_wasm(arg: cstring): cstring {. - importc.} -proc dumpKeymapGraphViz*(context: string = "") {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add context.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_dumpKeymapGraphViz_void_App_string_wasm( - argsJsonString.cstring) - - -proc editor_setMode_void_App_string_wasm(arg: cstring): cstring {.importc.} -proc setMode*(mode: string) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add mode.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_setMode_void_App_string_wasm(argsJsonString.cstring) - - -proc editor_mode_string_App_wasm(arg: cstring): cstring {.importc.} -proc mode*(): string {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = editor_mode_string_App_wasm(argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_getContextWithMode_string_App_string_wasm(arg: cstring): cstring {. - importc.} -proc getContextWithMode*(context: string): string {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add context.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_getContextWithMode_string_App_string_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_scriptRunAction_JsonNode_string_string_wasm(arg: cstring): cstring {. - importc.} -proc scriptRunAction*(action: string; arg: string): JsonNode {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add action.toJson() - argsJson.add arg.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_scriptRunAction_JsonNode_string_string_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_scriptLog_void_string_wasm(arg: cstring): cstring {.importc.} -proc scriptLog*(message: string) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add message.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_scriptLog_void_string_wasm(argsJsonString.cstring) - - -proc editor_changeAnimationSpeed_void_App_float_wasm(arg: cstring): cstring {. - importc.} -proc changeAnimationSpeed*(factor: float) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add factor.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_changeAnimationSpeed_void_App_float_wasm( - argsJsonString.cstring) - - -proc editor_registerPluginSourceCode_void_App_string_string_wasm(arg: cstring): cstring {. - importc.} -proc registerPluginSourceCode*(path: string; content: string) {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add path.toJson() - argsJson.add content.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_registerPluginSourceCode_void_App_string_string_wasm( - argsJsonString.cstring) - - -proc editor_addCommandScript_void_App_string_string_string_string_string_string_tuple_filename_string_line_int_column_int_wasm( - arg: cstring): cstring {.importc.} -proc addCommandScript*(context: string; subContext: string; keys: string; - action: string; arg: string = ""; - description: string = ""; source: tuple[filename: string, - line: int, column: int] = ("", 0, 0)) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add context.toJson() - argsJson.add subContext.toJson() - argsJson.add keys.toJson() - argsJson.add action.toJson() - argsJson.add arg.toJson() - argsJson.add description.toJson() - argsJson.add source.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_addCommandScript_void_App_string_string_string_string_string_string_tuple_filename_string_line_int_column_int_wasm( - argsJsonString.cstring) - - -proc editor_getActivePopup_EditorId_wasm(arg: cstring): cstring {.importc.} -proc getActivePopup*(): EditorId {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = editor_getActivePopup_EditorId_wasm(argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_getActiveEditor_EditorId_wasm(arg: cstring): cstring {.importc.} -proc getActiveEditor*(): EditorId {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = editor_getActiveEditor_EditorId_wasm(argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_logRootNode_void_App_wasm(arg: cstring): cstring {.importc.} -proc logRootNode*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = editor_logRootNode_void_App_wasm(argsJsonString.cstring) - - -proc editor_scriptIsSelectorPopup_bool_EditorId_wasm(arg: cstring): cstring {. - importc.} -proc scriptIsSelectorPopup*(editorId: EditorId): bool {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add editorId.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_scriptIsSelectorPopup_bool_EditorId_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_scriptIsTextEditor_bool_EditorId_wasm(arg: cstring): cstring {. - importc.} -proc scriptIsTextEditor*(editorId: EditorId): bool {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add editorId.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_scriptIsTextEditor_bool_EditorId_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_scriptIsModelEditor_bool_EditorId_wasm(arg: cstring): cstring {. - importc.} -proc scriptIsModelEditor*(editorId: EditorId): bool {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add editorId.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_scriptIsModelEditor_bool_EditorId_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_scriptRunActionFor_void_EditorId_string_string_wasm(arg: cstring): cstring {. - importc.} -proc scriptRunActionFor*(editorId: EditorId; action: string; arg: string) {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add editorId.toJson() - argsJson.add action.toJson() - argsJson.add arg.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_scriptRunActionFor_void_EditorId_string_string_wasm( - argsJsonString.cstring) - - -proc editor_scriptSetCallback_void_string_int_wasm(arg: cstring): cstring {. - importc.} -proc scriptSetCallback*(path: string; id: int) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add path.toJson() - argsJson.add id.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_scriptSetCallback_void_string_int_wasm( - argsJsonString.cstring) - - -proc editor_replayCommands_void_App_string_wasm(arg: cstring): cstring {.importc.} -proc replayCommands*(register: string) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add register.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_replayCommands_void_App_string_wasm( - argsJsonString.cstring) - - -proc editor_replayKeys_void_App_string_wasm(arg: cstring): cstring {.importc.} -proc replayKeys*(register: string) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add register.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_replayKeys_void_App_string_wasm( - argsJsonString.cstring) - - -proc editor_inputKeys_void_App_string_wasm(arg: cstring): cstring {.importc.} -proc inputKeys*(input: string) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add input.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_inputKeys_void_App_string_wasm( - argsJsonString.cstring) - - -proc editor_collectGarbage_void_App_wasm(arg: cstring): cstring {.importc.} -proc collectGarbage*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = editor_collectGarbage_void_App_wasm(argsJsonString.cstring) - - -proc editor_echoArgs_void_App_JsonNode_wasm(arg: cstring): cstring {.importc.} -proc echoArgs*(args: JsonNode) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add args.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_echoArgs_void_App_JsonNode_wasm( - argsJsonString.cstring) - - -proc editor_all_void_App_JsonNode_wasm(arg: cstring): cstring {.importc.} -proc all*(args: JsonNode) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add args.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_all_void_App_JsonNode_wasm(argsJsonString.cstring) - - -proc editor_printStatistics_void_App_wasm(arg: cstring): cstring {.importc.} -proc printStatistics*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = editor_printStatistics_void_App_wasm(argsJsonString.cstring) - diff --git a/scripting/editor_model_api_wasm.nim b/scripting/editor_model_api_wasm.nim deleted file mode 100644 index e5ccd9e86..000000000 --- a/scripting/editor_model_api_wasm.nim +++ /dev/null @@ -1,709 +0,0 @@ -import std/[json, options] -import scripting_api, misc/myjsonutils - -## This file is auto generated, don't modify. - - -proc editor_model_scrollPixels_void_ModelDocumentEditor_float32_wasm( - arg: cstring): cstring {.importc.} -proc scrollPixels*(self: ModelDocumentEditor; amount: float32) {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add amount.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_scrollPixels_void_ModelDocumentEditor_float32_wasm( - argsJsonString.cstring) - - -proc editor_model_scrollLines_void_ModelDocumentEditor_float32_wasm(arg: cstring): cstring {. - importc.} -proc scrollLines*(self: ModelDocumentEditor; lines: float32) {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add lines.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_scrollLines_void_ModelDocumentEditor_float32_wasm( - argsJsonString.cstring) - - -proc editor_model_setMode_void_ModelDocumentEditor_string_wasm(arg: cstring): cstring {. - importc.} -proc setMode*(self: ModelDocumentEditor; mode: string) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add mode.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_setMode_void_ModelDocumentEditor_string_wasm( - argsJsonString.cstring) - - -proc editor_model_mode_string_ModelDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc mode*(self: ModelDocumentEditor): string {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_mode_string_ModelDocumentEditor_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_model_getContextWithMode_string_ModelDocumentEditor_string_wasm( - arg: cstring): cstring {.importc.} -proc getContextWithMode*(self: ModelDocumentEditor; context: string): string {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add context.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_getContextWithMode_string_ModelDocumentEditor_string_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_model_isThickCursor_bool_ModelDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc isThickCursor*(self: ModelDocumentEditor): bool {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_isThickCursor_bool_ModelDocumentEditor_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_model_gotoDefinition_void_ModelDocumentEditor_bool_wasm(arg: cstring): cstring {. - importc.} -proc gotoDefinition*(self: ModelDocumentEditor; select: bool = false) {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add select.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_gotoDefinition_void_ModelDocumentEditor_bool_wasm( - argsJsonString.cstring) - - -proc editor_model_gotoPrevReference_void_ModelDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc gotoPrevReference*(self: ModelDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_gotoPrevReference_void_ModelDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_model_gotoNextReference_void_ModelDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc gotoNextReference*(self: ModelDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_gotoNextReference_void_ModelDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_model_gotoPrevInvalidNode_void_ModelDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc gotoPrevInvalidNode*(self: ModelDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_gotoPrevInvalidNode_void_ModelDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_model_gotoNextInvalidNode_void_ModelDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc gotoNextInvalidNode*(self: ModelDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_gotoNextInvalidNode_void_ModelDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_model_gotoPrevNodeOfClass_void_ModelDocumentEditor_string_bool_wasm( - arg: cstring): cstring {.importc.} -proc gotoPrevNodeOfClass*(self: ModelDocumentEditor; className: string; - select: bool = false) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add className.toJson() - argsJson.add select.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_gotoPrevNodeOfClass_void_ModelDocumentEditor_string_bool_wasm( - argsJsonString.cstring) - - -proc editor_model_gotoNextNodeOfClass_void_ModelDocumentEditor_string_bool_wasm( - arg: cstring): cstring {.importc.} -proc gotoNextNodeOfClass*(self: ModelDocumentEditor; className: string; - select: bool = false) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add className.toJson() - argsJson.add select.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_gotoNextNodeOfClass_void_ModelDocumentEditor_string_bool_wasm( - argsJsonString.cstring) - - -proc editor_model_toggleBoolCell_void_ModelDocumentEditor_bool_wasm(arg: cstring): cstring {. - importc.} -proc toggleBoolCell*(self: ModelDocumentEditor; select: bool = false) {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add select.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_toggleBoolCell_void_ModelDocumentEditor_bool_wasm( - argsJsonString.cstring) - - -proc editor_model_invertSelection_void_ModelDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc invertSelection*(self: ModelDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_invertSelection_void_ModelDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_model_selectPrev_void_ModelDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc selectPrev*(self: ModelDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_selectPrev_void_ModelDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_model_selectNext_void_ModelDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc selectNext*(self: ModelDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_selectNext_void_ModelDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_model_moveCursorLeft_void_ModelDocumentEditor_bool_wasm(arg: cstring): cstring {. - importc.} -proc moveCursorLeft*(self: ModelDocumentEditor; select: bool = false) {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add select.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_moveCursorLeft_void_ModelDocumentEditor_bool_wasm( - argsJsonString.cstring) - - -proc editor_model_moveCursorRight_void_ModelDocumentEditor_bool_wasm( - arg: cstring): cstring {.importc.} -proc moveCursorRight*(self: ModelDocumentEditor; select: bool = false) {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add select.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_moveCursorRight_void_ModelDocumentEditor_bool_wasm( - argsJsonString.cstring) - - -proc editor_model_moveCursorLeftLine_void_ModelDocumentEditor_bool_wasm( - arg: cstring): cstring {.importc.} -proc moveCursorLeftLine*(self: ModelDocumentEditor; select: bool = false) {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add select.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_moveCursorLeftLine_void_ModelDocumentEditor_bool_wasm( - argsJsonString.cstring) - - -proc editor_model_moveCursorRightLine_void_ModelDocumentEditor_bool_wasm( - arg: cstring): cstring {.importc.} -proc moveCursorRightLine*(self: ModelDocumentEditor; select: bool = false) {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add select.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_moveCursorRightLine_void_ModelDocumentEditor_bool_wasm( - argsJsonString.cstring) - - -proc editor_model_moveCursorLineStart_void_ModelDocumentEditor_bool_wasm( - arg: cstring): cstring {.importc.} -proc moveCursorLineStart*(self: ModelDocumentEditor; select: bool = false) {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add select.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_moveCursorLineStart_void_ModelDocumentEditor_bool_wasm( - argsJsonString.cstring) - - -proc editor_model_moveCursorLineEnd_void_ModelDocumentEditor_bool_wasm( - arg: cstring): cstring {.importc.} -proc moveCursorLineEnd*(self: ModelDocumentEditor; select: bool = false) {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add select.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_moveCursorLineEnd_void_ModelDocumentEditor_bool_wasm( - argsJsonString.cstring) - - -proc editor_model_moveCursorLineStartInline_void_ModelDocumentEditor_bool_wasm( - arg: cstring): cstring {.importc.} -proc moveCursorLineStartInline*(self: ModelDocumentEditor; select: bool = false) {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add select.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_moveCursorLineStartInline_void_ModelDocumentEditor_bool_wasm( - argsJsonString.cstring) - - -proc editor_model_moveCursorLineEndInline_void_ModelDocumentEditor_bool_wasm( - arg: cstring): cstring {.importc.} -proc moveCursorLineEndInline*(self: ModelDocumentEditor; select: bool = false) {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add select.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_moveCursorLineEndInline_void_ModelDocumentEditor_bool_wasm( - argsJsonString.cstring) - - -proc editor_model_moveCursorUp_void_ModelDocumentEditor_bool_wasm(arg: cstring): cstring {. - importc.} -proc moveCursorUp*(self: ModelDocumentEditor; select: bool = false) {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add select.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_moveCursorUp_void_ModelDocumentEditor_bool_wasm( - argsJsonString.cstring) - - -proc editor_model_moveCursorDown_void_ModelDocumentEditor_bool_wasm(arg: cstring): cstring {. - importc.} -proc moveCursorDown*(self: ModelDocumentEditor; select: bool = false) {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add select.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_moveCursorDown_void_ModelDocumentEditor_bool_wasm( - argsJsonString.cstring) - - -proc editor_model_moveCursorLeftCell_void_ModelDocumentEditor_bool_wasm( - arg: cstring): cstring {.importc.} -proc moveCursorLeftCell*(self: ModelDocumentEditor; select: bool = false) {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add select.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_moveCursorLeftCell_void_ModelDocumentEditor_bool_wasm( - argsJsonString.cstring) - - -proc editor_model_moveCursorRightCell_void_ModelDocumentEditor_bool_wasm( - arg: cstring): cstring {.importc.} -proc moveCursorRightCell*(self: ModelDocumentEditor; select: bool = false) {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add select.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_moveCursorRightCell_void_ModelDocumentEditor_bool_wasm( - argsJsonString.cstring) - - -proc editor_model_selectNode_void_ModelDocumentEditor_bool_wasm(arg: cstring): cstring {. - importc.} -proc selectNode*(self: ModelDocumentEditor; select: bool = false) {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add select.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_selectNode_void_ModelDocumentEditor_bool_wasm( - argsJsonString.cstring) - - -proc editor_model_selectPrevNeighbor_void_ModelDocumentEditor_bool_wasm( - arg: cstring): cstring {.importc.} -proc selectPrevNeighbor*(self: ModelDocumentEditor; select: bool = false) {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add select.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_selectPrevNeighbor_void_ModelDocumentEditor_bool_wasm( - argsJsonString.cstring) - - -proc editor_model_selectNextNeighbor_void_ModelDocumentEditor_bool_wasm( - arg: cstring): cstring {.importc.} -proc selectNextNeighbor*(self: ModelDocumentEditor; select: bool = false) {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add select.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_selectNextNeighbor_void_ModelDocumentEditor_bool_wasm( - argsJsonString.cstring) - - -proc editor_model_selectPrevPlaceholder_void_ModelDocumentEditor_bool_wasm( - arg: cstring): cstring {.importc.} -proc selectPrevPlaceholder*(self: ModelDocumentEditor; select: bool = false) {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add select.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_selectPrevPlaceholder_void_ModelDocumentEditor_bool_wasm( - argsJsonString.cstring) - - -proc editor_model_selectNextPlaceholder_void_ModelDocumentEditor_bool_wasm( - arg: cstring): cstring {.importc.} -proc selectNextPlaceholder*(self: ModelDocumentEditor; select: bool = false) {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add select.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_selectNextPlaceholder_void_ModelDocumentEditor_bool_wasm( - argsJsonString.cstring) - - -proc editor_model_deleteLeft_void_ModelDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc deleteLeft*(self: ModelDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_deleteLeft_void_ModelDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_model_deleteRight_void_ModelDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc deleteRight*(self: ModelDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_deleteRight_void_ModelDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_model_replaceLeft_void_ModelDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc replaceLeft*(self: ModelDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_replaceLeft_void_ModelDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_model_replaceRight_void_ModelDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc replaceRight*(self: ModelDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_replaceRight_void_ModelDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_model_createNewNode_void_ModelDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc createNewNode*(self: ModelDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_createNewNode_void_ModelDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_model_insertTextAtCursor_bool_ModelDocumentEditor_string_wasm( - arg: cstring): cstring {.importc.} -proc insertTextAtCursor*(self: ModelDocumentEditor; input: string): bool {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add input.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_insertTextAtCursor_bool_ModelDocumentEditor_string_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_model_undo_void_ModelDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc undo*(self: ModelDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_undo_void_ModelDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_model_redo_void_ModelDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc redo*(self: ModelDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_redo_void_ModelDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_model_toggleUseDefaultCellBuilder_void_ModelDocumentEditor_wasm( - arg: cstring): cstring {.importc.} -proc toggleUseDefaultCellBuilder*(self: ModelDocumentEditor) {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_toggleUseDefaultCellBuilder_void_ModelDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_model_showCompletions_void_ModelDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc showCompletions*(self: ModelDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_showCompletions_void_ModelDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_model_showCompletionWindow_void_ModelDocumentEditor_wasm( - arg: cstring): cstring {.importc.} -proc showCompletionWindow*(self: ModelDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_showCompletionWindow_void_ModelDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_model_hideCompletions_void_ModelDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc hideCompletions*(self: ModelDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_hideCompletions_void_ModelDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_model_selectPrevCompletion_void_ModelDocumentEditor_wasm( - arg: cstring): cstring {.importc.} -proc selectPrevCompletion*(self: ModelDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_selectPrevCompletion_void_ModelDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_model_selectNextCompletion_void_ModelDocumentEditor_wasm( - arg: cstring): cstring {.importc.} -proc selectNextCompletion*(self: ModelDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_selectNextCompletion_void_ModelDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_model_applySelectedCompletion_void_ModelDocumentEditor_wasm( - arg: cstring): cstring {.importc.} -proc applySelectedCompletion*(self: ModelDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_applySelectedCompletion_void_ModelDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_model_printSelectionInfo_void_ModelDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc printSelectionInfo*(self: ModelDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_printSelectionInfo_void_ModelDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_model_clearModelCache_void_ModelDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc clearModelCache*(self: ModelDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_clearModelCache_void_ModelDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_model_runSelectedFunction_void_ModelDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc runSelectedFunction*(self: ModelDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_runSelectedFunction_void_ModelDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_model_copyNode_void_ModelDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc copyNode*(self: ModelDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_copyNode_void_ModelDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_model_pasteNode_void_ModelDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc pasteNode*(self: ModelDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_pasteNode_void_ModelDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_model_addLanguage_void_ModelDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc addLanguage*(self: ModelDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_addLanguage_void_ModelDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_model_createNewModel_void_ModelDocumentEditor_string_wasm( - arg: cstring): cstring {.importc.} -proc createNewModel*(self: ModelDocumentEditor; name: string) {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add name.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_createNewModel_void_ModelDocumentEditor_string_wasm( - argsJsonString.cstring) - - -proc editor_model_addModelToProject_void_ModelDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc addModelToProject*(self: ModelDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_addModelToProject_void_ModelDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_model_importModel_void_ModelDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc importModel*(self: ModelDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_importModel_void_ModelDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_model_compileLanguage_void_ModelDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc compileLanguage*(self: ModelDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_compileLanguage_void_ModelDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_model_addRootNode_void_ModelDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc addRootNode*(self: ModelDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_addRootNode_void_ModelDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_model_saveProject_void_ModelDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc saveProject*(self: ModelDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_saveProject_void_ModelDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_model_loadLanguageModel_void_ModelDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc loadLanguageModel*(self: ModelDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_loadLanguageModel_void_ModelDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_model_findDeclaration_void_ModelDocumentEditor_bool_wasm( - arg: cstring): cstring {.importc.} -proc findDeclaration*(self: ModelDocumentEditor; global: bool) {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add global.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_model_findDeclaration_void_ModelDocumentEditor_bool_wasm( - argsJsonString.cstring) - diff --git a/scripting/editor_text_api_wasm.nim b/scripting/editor_text_api_wasm.nim deleted file mode 100644 index 72b3abb21..000000000 --- a/scripting/editor_text_api_wasm.nim +++ /dev/null @@ -1,2751 +0,0 @@ -import std/[json, options] -import scripting_api, misc/myjsonutils - -## This file is auto generated, don't modify. - - -proc editor_text_enableAutoReload_void_TextDocumentEditor_bool_wasm(arg: cstring): cstring {. - importc.} -proc enableAutoReload*(self: TextDocumentEditor; enabled: bool) {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add enabled.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_enableAutoReload_void_TextDocumentEditor_bool_wasm( - argsJsonString.cstring) - - -proc editor_text_setLanguage_void_TextDocumentEditor_string_wasm(arg: cstring): cstring {. - importc.} -proc setLanguage*(self: TextDocumentEditor; language: string) {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add language.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_setLanguage_void_TextDocumentEditor_string_wasm( - argsJsonString.cstring) - - -proc editor_text_getFileName_string_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc getFileName*(self: TextDocumentEditor): string {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_getFileName_string_TextDocumentEditor_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_lineCount_int_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc lineCount*(self: TextDocumentEditor): int {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_lineCount_int_TextDocumentEditor_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_lineLength_int_TextDocumentEditor_int_wasm(arg: cstring): cstring {. - importc.} -proc lineLength*(self: TextDocumentEditor; line: int): int {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add line.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_lineLength_int_TextDocumentEditor_int_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_numDisplayLines_int_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc numDisplayLines*(self: TextDocumentEditor): int {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_numDisplayLines_int_TextDocumentEditor_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_numWrapLines_int_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc numWrapLines*(self: TextDocumentEditor): int {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_numWrapLines_int_TextDocumentEditor_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_screenLineCount_int_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc screenLineCount*(self: TextDocumentEditor): int {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_screenLineCount_int_TextDocumentEditor_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_evaluateExpressions_void_TextDocumentEditor_Selections_bool_string_string_bool_wasm( - arg: cstring): cstring {.importc.} -proc evaluateExpressions*(self: TextDocumentEditor; selections: Selections; - inclusiveEnd: bool = false; prefix: string = ""; - suffix: string = ""; addSelectionIndex: bool = false) {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add selections.toJson() - argsJson.add inclusiveEnd.toJson() - argsJson.add prefix.toJson() - argsJson.add suffix.toJson() - argsJson.add addSelectionIndex.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_evaluateExpressions_void_TextDocumentEditor_Selections_bool_string_string_bool_wasm( - argsJsonString.cstring) - - -proc editor_text_doMoveCursorLine_Cursor_TextDocumentEditor_Cursor_int_bool_bool_wasm( - arg: cstring): cstring {.importc.} -proc doMoveCursorLine*(self: TextDocumentEditor; cursor: Cursor; offset: int; - wrap: bool = false; includeAfter: bool = false): Cursor {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add cursor.toJson() - argsJson.add offset.toJson() - argsJson.add wrap.toJson() - argsJson.add includeAfter.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_doMoveCursorLine_Cursor_TextDocumentEditor_Cursor_int_bool_bool_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_getDefaultScrollBehaviour_ScrollBehaviour_TextDocumentEditor_wasm( - arg: cstring): cstring {.importc.} -proc getDefaultScrollBehaviour*(self: TextDocumentEditor): ScrollBehaviour {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_getDefaultScrollBehaviour_ScrollBehaviour_TextDocumentEditor_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_setDefaultScrollBehaviour_void_TextDocumentEditor_ScrollBehaviour_wasm( - arg: cstring): cstring {.importc.} -proc setDefaultScrollBehaviour*(self: TextDocumentEditor; - scrollBehaviour: ScrollBehaviour) {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add scrollBehaviour.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_setDefaultScrollBehaviour_void_TextDocumentEditor_ScrollBehaviour_wasm( - argsJsonString.cstring) - - -proc editor_text_doMoveCursorVisualLine_Cursor_TextDocumentEditor_Cursor_int_bool_bool_Option_int_wasm( - arg: cstring): cstring {.importc.} -proc doMoveCursorVisualLine*(self: TextDocumentEditor; cursor: Cursor; - offset: int; wrap: bool = false; - includeAfter: bool = false; - targetColumn: Option[int] = int.none): Cursor {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add cursor.toJson() - argsJson.add offset.toJson() - argsJson.add wrap.toJson() - argsJson.add includeAfter.toJson() - argsJson.add targetColumn.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_doMoveCursorVisualLine_Cursor_TextDocumentEditor_Cursor_int_bool_bool_Option_int_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_doMoveCursorHome_Cursor_TextDocumentEditor_Cursor_int_bool_bool_wasm( - arg: cstring): cstring {.importc.} -proc doMoveCursorHome*(self: TextDocumentEditor; cursor: Cursor; offset: int; - wrap: bool; includeAfter: bool): Cursor {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add cursor.toJson() - argsJson.add offset.toJson() - argsJson.add wrap.toJson() - argsJson.add includeAfter.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_doMoveCursorHome_Cursor_TextDocumentEditor_Cursor_int_bool_bool_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_doMoveCursorEnd_Cursor_TextDocumentEditor_Cursor_int_bool_bool_wasm( - arg: cstring): cstring {.importc.} -proc doMoveCursorEnd*(self: TextDocumentEditor; cursor: Cursor; offset: int; - wrap: bool; includeAfter: bool): Cursor {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add cursor.toJson() - argsJson.add offset.toJson() - argsJson.add wrap.toJson() - argsJson.add includeAfter.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_doMoveCursorEnd_Cursor_TextDocumentEditor_Cursor_int_bool_bool_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_doMoveCursorPrevFindResult_Cursor_TextDocumentEditor_Cursor_int_bool_bool_wasm( - arg: cstring): cstring {.importc.} -proc doMoveCursorPrevFindResult*(self: TextDocumentEditor; cursor: Cursor; - offset: int; wrap: bool; includeAfter: bool): Cursor {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add cursor.toJson() - argsJson.add offset.toJson() - argsJson.add wrap.toJson() - argsJson.add includeAfter.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_doMoveCursorPrevFindResult_Cursor_TextDocumentEditor_Cursor_int_bool_bool_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_doMoveCursorNextFindResult_Cursor_TextDocumentEditor_Cursor_int_bool_bool_wasm( - arg: cstring): cstring {.importc.} -proc doMoveCursorNextFindResult*(self: TextDocumentEditor; cursor: Cursor; - offset: int; wrap: bool; includeAfter: bool): Cursor {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add cursor.toJson() - argsJson.add offset.toJson() - argsJson.add wrap.toJson() - argsJson.add includeAfter.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_doMoveCursorNextFindResult_Cursor_TextDocumentEditor_Cursor_int_bool_bool_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_doMoveCursorLineCenter_Cursor_TextDocumentEditor_Cursor_int_bool_bool_wasm( - arg: cstring): cstring {.importc.} -proc doMoveCursorLineCenter*(self: TextDocumentEditor; cursor: Cursor; - offset: int; wrap: bool; includeAfter: bool): Cursor {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add cursor.toJson() - argsJson.add offset.toJson() - argsJson.add wrap.toJson() - argsJson.add includeAfter.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_doMoveCursorLineCenter_Cursor_TextDocumentEditor_Cursor_int_bool_bool_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_doMoveCursorCenter_Cursor_TextDocumentEditor_Cursor_int_bool_bool_wasm( - arg: cstring): cstring {.importc.} -proc doMoveCursorCenter*(self: TextDocumentEditor; cursor: Cursor; offset: int; - wrap: bool; includeAfter: bool): Cursor {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add cursor.toJson() - argsJson.add offset.toJson() - argsJson.add wrap.toJson() - argsJson.add includeAfter.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_doMoveCursorCenter_Cursor_TextDocumentEditor_Cursor_int_bool_bool_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_doMoveCursorColumn_Cursor_TextDocumentEditor_Cursor_int_bool_bool_wasm( - arg: cstring): cstring {.importc.} -proc doMoveCursorColumn*(self: TextDocumentEditor; cursor: Cursor; offset: int; - wrap: bool = true; includeAfter: bool = true): Cursor {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add cursor.toJson() - argsJson.add offset.toJson() - argsJson.add wrap.toJson() - argsJson.add includeAfter.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_doMoveCursorColumn_Cursor_TextDocumentEditor_Cursor_int_bool_bool_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_includeSelectionEnd_Selection_TextDocumentEditor_Selection_bool_wasm( - arg: cstring): cstring {.importc.} -proc includeSelectionEnd*(self: TextDocumentEditor; res: Selection; - includeAfter: bool = true): Selection {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add res.toJson() - argsJson.add includeAfter.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_includeSelectionEnd_Selection_TextDocumentEditor_Selection_bool_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_findSurroundStart_Option_Cursor_TextDocumentEditor_Cursor_int_char_char_int_wasm( - arg: cstring): cstring {.importc.} -proc findSurroundStart*(editor: TextDocumentEditor; cursor: Cursor; count: int; - c0: char; c1: char; depth: int = 1): Option[Cursor] {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add editor.toJson() - argsJson.add cursor.toJson() - argsJson.add count.toJson() - argsJson.add c0.toJson() - argsJson.add c1.toJson() - argsJson.add depth.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_findSurroundStart_Option_Cursor_TextDocumentEditor_Cursor_int_char_char_int_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_findSurroundEnd_Option_Cursor_TextDocumentEditor_Cursor_int_char_char_int_wasm( - arg: cstring): cstring {.importc.} -proc findSurroundEnd*(editor: TextDocumentEditor; cursor: Cursor; count: int; - c0: char; c1: char; depth: int = 1): Option[Cursor] {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add editor.toJson() - argsJson.add cursor.toJson() - argsJson.add count.toJson() - argsJson.add c0.toJson() - argsJson.add c1.toJson() - argsJson.add depth.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_findSurroundEnd_Option_Cursor_TextDocumentEditor_Cursor_int_char_char_int_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_toggleFlag_void_TextDocumentEditor_string_wasm(arg: cstring): cstring {. - importc.} -proc toggleFlag*(self: TextDocumentEditor; key: string) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add key.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_toggleFlag_void_TextDocumentEditor_string_wasm( - argsJsonString.cstring) - - -proc editor_text_setConfig_void_TextDocumentEditor_string_JsonNode_wasm( - arg: cstring): cstring {.importc.} -proc setConfig*(self: TextDocumentEditor; key: string; value: JsonNode) {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add key.toJson() - argsJson.add value.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_setConfig_void_TextDocumentEditor_string_JsonNode_wasm( - argsJsonString.cstring) - - -proc editor_text_getConfig_JsonNode_TextDocumentEditor_string_wasm(arg: cstring): cstring {. - importc.} -proc getConfig*(self: TextDocumentEditor; key: string): JsonNode {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add key.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_getConfig_JsonNode_TextDocumentEditor_string_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_removeMode_void_TextDocumentEditor_string_wasm(arg: cstring): cstring {. - importc.} -proc removeMode*(self: TextDocumentEditor; mode: string) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add mode.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_removeMode_void_TextDocumentEditor_string_wasm( - argsJsonString.cstring) - - -proc editor_text_setMode_void_TextDocumentEditor_string_bool_wasm(arg: cstring): cstring {. - importc.} -proc setMode*(self: TextDocumentEditor; mode: string; exclusive: bool = true) {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add mode.toJson() - argsJson.add exclusive.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_setMode_void_TextDocumentEditor_string_bool_wasm( - argsJsonString.cstring) - - -proc editor_text_setDefaultMode_void_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc setDefaultMode*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_setDefaultMode_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_mode_string_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc mode*(self: TextDocumentEditor): string {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_mode_string_TextDocumentEditor_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_getContextWithMode_string_TextDocumentEditor_string_wasm( - arg: cstring): cstring {.importc.} -proc getContextWithMode*(self: TextDocumentEditor; context: string): string {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add context.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_getContextWithMode_string_TextDocumentEditor_string_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_updateTargetColumn_void_TextDocumentEditor_SelectionCursor_wasm( - arg: cstring): cstring {.importc.} -proc updateTargetColumn*(self: TextDocumentEditor; - cursor: SelectionCursor = Last) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add cursor.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_updateTargetColumn_void_TextDocumentEditor_SelectionCursor_wasm( - argsJsonString.cstring) - - -proc editor_text_invertSelection_void_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc invertSelection*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_invertSelection_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_getRevision_int_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc getRevision*(self: TextDocumentEditor): int {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_getRevision_int_TextDocumentEditor_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_getUsage_string_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc getUsage*(self: TextDocumentEditor): string {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_getUsage_string_TextDocumentEditor_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_getChar_char_TextDocumentEditor_Cursor_wasm(arg: cstring): cstring {. - importc.} -proc getChar*(self: TextDocumentEditor; cursor: Cursor): char {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add cursor.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_getChar_char_TextDocumentEditor_Cursor_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_getText_string_TextDocumentEditor_Selection_bool_wasm( - arg: cstring): cstring {.importc.} -proc getText*(self: TextDocumentEditor; selection: Selection; - inclusiveEnd: bool = false): string {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add selection.toJson() - argsJson.add inclusiveEnd.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_getText_string_TextDocumentEditor_Selection_bool_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_getLine_string_TextDocumentEditor_int_wasm(arg: cstring): cstring {. - importc.} -proc getLine*(self: TextDocumentEditor; line: int): string {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add line.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_getLine_string_TextDocumentEditor_int_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_insert_seq_Selection_TextDocumentEditor_seq_Selection_string_bool_bool_wasm( - arg: cstring): cstring {.importc.} -proc insert*(self: TextDocumentEditor; selections: seq[Selection]; text: string; - notify: bool = true; record: bool = true): seq[Selection] {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add selections.toJson() - argsJson.add text.toJson() - argsJson.add notify.toJson() - argsJson.add record.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_insert_seq_Selection_TextDocumentEditor_seq_Selection_string_bool_bool_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_insertMulti_seq_Selection_TextDocumentEditor_seq_Selection_seq_string_bool_bool_wasm( - arg: cstring): cstring {.importc.} -proc insertMulti*(self: TextDocumentEditor; selections: seq[Selection]; - texts: seq[string]; notify: bool = true; record: bool = true): seq[ - Selection] {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add selections.toJson() - argsJson.add texts.toJson() - argsJson.add notify.toJson() - argsJson.add record.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_insertMulti_seq_Selection_TextDocumentEditor_seq_Selection_seq_string_bool_bool_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_delete_seq_Selection_TextDocumentEditor_seq_Selection_bool_bool_bool_wasm( - arg: cstring): cstring {.importc.} -proc delete*(self: TextDocumentEditor; selections: seq[Selection]; - notify: bool = true; record: bool = true; - inclusiveEnd: bool = false): seq[Selection] {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add selections.toJson() - argsJson.add notify.toJson() - argsJson.add record.toJson() - argsJson.add inclusiveEnd.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_delete_seq_Selection_TextDocumentEditor_seq_Selection_bool_bool_bool_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_edit_seq_Selection_TextDocumentEditor_seq_Selection_seq_string_bool_bool_bool_wasm( - arg: cstring): cstring {.importc.} -proc edit*(self: TextDocumentEditor; selections: seq[Selection]; - texts: seq[string]; notify: bool = true; record: bool = true; - inclusiveEnd: bool = false): seq[Selection] {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add selections.toJson() - argsJson.add texts.toJson() - argsJson.add notify.toJson() - argsJson.add record.toJson() - argsJson.add inclusiveEnd.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_edit_seq_Selection_TextDocumentEditor_seq_Selection_seq_string_bool_bool_bool_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_deleteLines_void_TextDocumentEditor_Slice_int_Selections_wasm( - arg: cstring): cstring {.importc.} -proc deleteLines*(self: TextDocumentEditor; slice: Slice[int]; - oldSelections: Selections) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add slice.toJson() - argsJson.add oldSelections.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_deleteLines_void_TextDocumentEditor_Slice_int_Selections_wasm( - argsJsonString.cstring) - - -proc editor_text_selectPrev_void_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc selectPrev*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_selectPrev_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_selectNext_void_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc selectNext*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_selectNext_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_selectInside_void_TextDocumentEditor_Cursor_wasm(arg: cstring): cstring {. - importc.} -proc selectInside*(self: TextDocumentEditor; cursor: Cursor) {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add cursor.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_selectInside_void_TextDocumentEditor_Cursor_wasm( - argsJsonString.cstring) - - -proc editor_text_selectInsideCurrent_void_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc selectInsideCurrent*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_selectInsideCurrent_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_selectLine_void_TextDocumentEditor_int_wasm(arg: cstring): cstring {. - importc.} -proc selectLine*(self: TextDocumentEditor; line: int) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add line.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_selectLine_void_TextDocumentEditor_int_wasm( - argsJsonString.cstring) - - -proc editor_text_selectLineCurrent_void_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc selectLineCurrent*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_selectLineCurrent_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_getParentNodeSelection_Selection_TextDocumentEditor_Selection_bool_wasm( - arg: cstring): cstring {.importc.} -proc getParentNodeSelection*(self: TextDocumentEditor; selection: Selection; - includeAfter: bool = true): Selection {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add selection.toJson() - argsJson.add includeAfter.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_getParentNodeSelection_Selection_TextDocumentEditor_Selection_bool_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_getNextNamedSiblingNodeSelection_Option_Selection_TextDocumentEditor_Selection_bool_wasm( - arg: cstring): cstring {.importc.} -proc getNextNamedSiblingNodeSelection*(self: TextDocumentEditor; - selection: Selection; - includeAfter: bool = true): Option[ - Selection] {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add selection.toJson() - argsJson.add includeAfter.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_getNextNamedSiblingNodeSelection_Option_Selection_TextDocumentEditor_Selection_bool_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_getNextSiblingNodeSelection_Option_Selection_TextDocumentEditor_Selection_bool_wasm( - arg: cstring): cstring {.importc.} -proc getNextSiblingNodeSelection*(self: TextDocumentEditor; - selection: Selection; - includeAfter: bool = true): Option[Selection] {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add selection.toJson() - argsJson.add includeAfter.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_getNextSiblingNodeSelection_Option_Selection_TextDocumentEditor_Selection_bool_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_getParentNodeSelections_Selections_TextDocumentEditor_Selections_bool_wasm( - arg: cstring): cstring {.importc.} -proc getParentNodeSelections*(self: TextDocumentEditor; selections: Selections; - includeAfter: bool = true): Selections {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add selections.toJson() - argsJson.add includeAfter.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_getParentNodeSelections_Selections_TextDocumentEditor_Selections_bool_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_selectParentTs_void_TextDocumentEditor_Selection_bool_wasm( - arg: cstring): cstring {.importc.} -proc selectParentTs*(self: TextDocumentEditor; selection: Selection; - includeAfter: bool = true) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add selection.toJson() - argsJson.add includeAfter.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_selectParentTs_void_TextDocumentEditor_Selection_bool_wasm( - argsJsonString.cstring) - - -proc editor_text_printTreesitterMemoryUsage_void_TextDocumentEditor_wasm( - arg: cstring): cstring {.importc.} -proc printTreesitterMemoryUsage*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_printTreesitterMemoryUsage_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_printTreesitterTree_void_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc printTreesitterTree*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_printTreesitterTree_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_printTreesitterTreeUnderCursor_void_TextDocumentEditor_wasm( - arg: cstring): cstring {.importc.} -proc printTreesitterTreeUnderCursor*(self: TextDocumentEditor) {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_printTreesitterTreeUnderCursor_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_selectParentCurrentTs_void_TextDocumentEditor_bool_wasm( - arg: cstring): cstring {.importc.} -proc selectParentCurrentTs*(self: TextDocumentEditor; includeAfter: bool = true) {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add includeAfter.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_selectParentCurrentTs_void_TextDocumentEditor_bool_wasm( - argsJsonString.cstring) - - -proc editor_text_getNextNodeWithSameType_Option_Selection_TextDocumentEditor_Selection_int_bool_bool_bool_bool_wasm( - arg: cstring): cstring {.importc.} -proc getNextNodeWithSameType*(self: TextDocumentEditor; selection: Selection; - offset: int = 0; includeAfter: bool = true; - wrap: bool = true; stepIn: bool = true; - stepOut: bool = true): Option[Selection] {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add selection.toJson() - argsJson.add offset.toJson() - argsJson.add includeAfter.toJson() - argsJson.add wrap.toJson() - argsJson.add stepIn.toJson() - argsJson.add stepOut.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_getNextNodeWithSameType_Option_Selection_TextDocumentEditor_Selection_int_bool_bool_bool_bool_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_shouldShowCompletionsAt_bool_TextDocumentEditor_Cursor_wasm( - arg: cstring): cstring {.importc.} -proc shouldShowCompletionsAt*(self: TextDocumentEditor; cursor: Cursor): bool {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add cursor.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_shouldShowCompletionsAt_bool_TextDocumentEditor_Cursor_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_autoShowCompletions_void_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc autoShowCompletions*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_autoShowCompletions_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_insertText_void_TextDocumentEditor_string_bool_wasm( - arg: cstring): cstring {.importc.} -proc insertText*(self: TextDocumentEditor; text: string; autoIndent: bool = true) {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add text.toJson() - argsJson.add autoIndent.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_insertText_void_TextDocumentEditor_string_bool_wasm( - argsJsonString.cstring) - - -proc editor_text_insertRaw_void_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc insertRaw*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_insertRaw_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_indent_void_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc indent*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_indent_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_unindent_void_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc unindent*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_unindent_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_insertIndent_void_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc insertIndent*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_insertIndent_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_undo_void_TextDocumentEditor_string_wasm(arg: cstring): cstring {. - importc.} -proc undo*(self: TextDocumentEditor; checkpoint: string = "word") {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add checkpoint.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_undo_void_TextDocumentEditor_string_wasm( - argsJsonString.cstring) - - -proc editor_text_redo_void_TextDocumentEditor_string_wasm(arg: cstring): cstring {. - importc.} -proc redo*(self: TextDocumentEditor; checkpoint: string = "word") {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add checkpoint.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_redo_void_TextDocumentEditor_string_wasm( - argsJsonString.cstring) - - -proc editor_text_addNextCheckpoint_void_TextDocumentEditor_string_wasm( - arg: cstring): cstring {.importc.} -proc addNextCheckpoint*(self: TextDocumentEditor; checkpoint: string) {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add checkpoint.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_addNextCheckpoint_void_TextDocumentEditor_string_wasm( - argsJsonString.cstring) - - -proc editor_text_copy_void_TextDocumentEditor_string_bool_wasm(arg: cstring): cstring {. - importc.} -proc copy*(self: TextDocumentEditor; register: string = ""; - inclusiveEnd: bool = false) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add register.toJson() - argsJson.add inclusiveEnd.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_copy_void_TextDocumentEditor_string_bool_wasm( - argsJsonString.cstring) - - -proc editor_text_paste_void_TextDocumentEditor_string_bool_wasm(arg: cstring): cstring {. - importc.} -proc paste*(self: TextDocumentEditor; registerName: string = ""; - inclusiveEnd: bool = false) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add registerName.toJson() - argsJson.add inclusiveEnd.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_paste_void_TextDocumentEditor_string_bool_wasm( - argsJsonString.cstring) - - -proc editor_text_scrollText_void_TextDocumentEditor_float32_wasm(arg: cstring): cstring {. - importc.} -proc scrollText*(self: TextDocumentEditor; amount: float32) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add amount.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_scrollText_void_TextDocumentEditor_float32_wasm( - argsJsonString.cstring) - - -proc editor_text_scrollTextHorizontal_void_TextDocumentEditor_float32_wasm( - arg: cstring): cstring {.importc.} -proc scrollTextHorizontal*(self: TextDocumentEditor; amount: float32) {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add amount.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_scrollTextHorizontal_void_TextDocumentEditor_float32_wasm( - argsJsonString.cstring) - - -proc editor_text_scrollLines_void_TextDocumentEditor_int_wasm(arg: cstring): cstring {. - importc.} -proc scrollLines*(self: TextDocumentEditor; amount: int) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add amount.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_scrollLines_void_TextDocumentEditor_int_wasm( - argsJsonString.cstring) - - -proc editor_text_duplicateLastSelection_void_TextDocumentEditor_wasm( - arg: cstring): cstring {.importc.} -proc duplicateLastSelection*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_duplicateLastSelection_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_addCursorBelow_void_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc addCursorBelow*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_addCursorBelow_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_addCursorAbove_void_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc addCursorAbove*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_addCursorAbove_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_getPrevFindResult_Selection_TextDocumentEditor_Cursor_int_bool_bool_wasm( - arg: cstring): cstring {.importc.} -proc getPrevFindResult*(self: TextDocumentEditor; cursor: Cursor; - offset: int = 0; includeAfter: bool = true; - wrap: bool = true): Selection {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add cursor.toJson() - argsJson.add offset.toJson() - argsJson.add includeAfter.toJson() - argsJson.add wrap.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_getPrevFindResult_Selection_TextDocumentEditor_Cursor_int_bool_bool_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_getNextFindResult_Selection_TextDocumentEditor_Cursor_int_bool_bool_wasm( - arg: cstring): cstring {.importc.} -proc getNextFindResult*(self: TextDocumentEditor; cursor: Cursor; - offset: int = 0; includeAfter: bool = true; - wrap: bool = true): Selection {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add cursor.toJson() - argsJson.add offset.toJson() - argsJson.add includeAfter.toJson() - argsJson.add wrap.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_getNextFindResult_Selection_TextDocumentEditor_Cursor_int_bool_bool_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_createAnchors_seq_Anchor_Anchor_TextDocumentEditor_Selections_wasm( - arg: cstring): cstring {.importc.} -proc createAnchors*(self: TextDocumentEditor; selections: Selections): seq[ - (Anchor, Anchor)] {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add selections.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_createAnchors_seq_Anchor_Anchor_TextDocumentEditor_Selections_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_resolveAnchors_Selections_TextDocumentEditor_seq_Anchor_Anchor_wasm( - arg: cstring): cstring {.importc.} -proc resolveAnchors*(self: TextDocumentEditor; anchors: seq[(Anchor, Anchor)]): Selections {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add anchors.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_resolveAnchors_Selections_TextDocumentEditor_seq_Anchor_Anchor_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_getPrevDiagnostic_Selection_TextDocumentEditor_Cursor_int_int_bool_bool_wasm( - arg: cstring): cstring {.importc.} -proc getPrevDiagnostic*(self: TextDocumentEditor; cursor: Cursor; - severity: int = 0; offset: int = 0; - includeAfter: bool = true; wrap: bool = true): Selection {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add cursor.toJson() - argsJson.add severity.toJson() - argsJson.add offset.toJson() - argsJson.add includeAfter.toJson() - argsJson.add wrap.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_getPrevDiagnostic_Selection_TextDocumentEditor_Cursor_int_int_bool_bool_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_getNextDiagnostic_Selection_TextDocumentEditor_Cursor_int_int_bool_bool_wasm( - arg: cstring): cstring {.importc.} -proc getNextDiagnostic*(self: TextDocumentEditor; cursor: Cursor; - severity: int = 0; offset: int = 0; - includeAfter: bool = true; wrap: bool = true): Selection {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add cursor.toJson() - argsJson.add severity.toJson() - argsJson.add offset.toJson() - argsJson.add includeAfter.toJson() - argsJson.add wrap.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_getNextDiagnostic_Selection_TextDocumentEditor_Cursor_int_int_bool_bool_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_closeDiff_void_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc closeDiff*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_closeDiff_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_getPrevChange_Selection_TextDocumentEditor_Cursor_wasm( - arg: cstring): cstring {.importc.} -proc getPrevChange*(self: TextDocumentEditor; cursor: Cursor): Selection {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add cursor.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_getPrevChange_Selection_TextDocumentEditor_Cursor_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_getNextChange_Selection_TextDocumentEditor_Cursor_wasm( - arg: cstring): cstring {.importc.} -proc getNextChange*(self: TextDocumentEditor; cursor: Cursor): Selection {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add cursor.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_getNextChange_Selection_TextDocumentEditor_Cursor_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_clearOverlays_void_TextDocumentEditor_int_wasm(arg: cstring): cstring {. - importc.} -proc clearOverlays*(self: TextDocumentEditor; id: int = -1) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add id.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_clearOverlays_void_TextDocumentEditor_int_wasm( - argsJsonString.cstring) - - -proc editor_text_addOverlay_void_TextDocumentEditor_Selection_string_int_string_Bias_wasm( - arg: cstring): cstring {.importc.} -proc addOverlay*(self: TextDocumentEditor; selection: Selection; text: string; - id: int; scope: string; bias: Bias) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add selection.toJson() - argsJson.add text.toJson() - argsJson.add id.toJson() - argsJson.add scope.toJson() - argsJson.add bias.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_addOverlay_void_TextDocumentEditor_Selection_string_int_string_Bias_wasm( - argsJsonString.cstring) - - -proc editor_text_updateDiff_void_TextDocumentEditor_bool_wasm(arg: cstring): cstring {. - importc.} -proc updateDiff*(self: TextDocumentEditor; gotoFirstDiff: bool = false) {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add gotoFirstDiff.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_updateDiff_void_TextDocumentEditor_bool_wasm( - argsJsonString.cstring) - - -proc editor_text_revertSelected_void_TextDocumentEditor_bool_wasm(arg: cstring): cstring {. - importc.} -proc revertSelected*(self: TextDocumentEditor; inclusiveEnd: bool = false) {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add inclusiveEnd.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_revertSelected_void_TextDocumentEditor_bool_wasm( - argsJsonString.cstring) - - -proc editor_text_stageSelected_void_TextDocumentEditor_bool_wasm(arg: cstring): cstring {. - importc.} -proc stageSelected*(self: TextDocumentEditor; inclusiveEnd: bool = false) {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add inclusiveEnd.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_stageSelected_void_TextDocumentEditor_bool_wasm( - argsJsonString.cstring) - - -proc editor_text_stageFile_void_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc stageFile*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_stageFile_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_format_void_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc format*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_format_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_checkoutFile_void_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc checkoutFile*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_checkoutFile_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_addNextFindResultToSelection_void_TextDocumentEditor_bool_bool_wasm( - arg: cstring): cstring {.importc.} -proc addNextFindResultToSelection*(self: TextDocumentEditor; - includeAfter: bool = true; wrap: bool = true) {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add includeAfter.toJson() - argsJson.add wrap.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_addNextFindResultToSelection_void_TextDocumentEditor_bool_bool_wasm( - argsJsonString.cstring) - - -proc editor_text_addPrevFindResultToSelection_void_TextDocumentEditor_bool_bool_wasm( - arg: cstring): cstring {.importc.} -proc addPrevFindResultToSelection*(self: TextDocumentEditor; - includeAfter: bool = true; wrap: bool = true) {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add includeAfter.toJson() - argsJson.add wrap.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_addPrevFindResultToSelection_void_TextDocumentEditor_bool_bool_wasm( - argsJsonString.cstring) - - -proc editor_text_setAllFindResultToSelection_void_TextDocumentEditor_wasm( - arg: cstring): cstring {.importc.} -proc setAllFindResultToSelection*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_setAllFindResultToSelection_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_clearSelections_void_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc clearSelections*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_clearSelections_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_moveCursorColumn_void_TextDocumentEditor_int_SelectionCursor_bool_bool_bool_wasm( - arg: cstring): cstring {.importc.} -proc moveCursorColumn*(self: TextDocumentEditor; distance: int; - cursor: SelectionCursor = SelectionCursor.Config; - all: bool = true; wrap: bool = true; - includeAfter: bool = true) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add distance.toJson() - argsJson.add cursor.toJson() - argsJson.add all.toJson() - argsJson.add wrap.toJson() - argsJson.add includeAfter.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_moveCursorColumn_void_TextDocumentEditor_int_SelectionCursor_bool_bool_bool_wasm( - argsJsonString.cstring) - - -proc editor_text_moveCursorLine_void_TextDocumentEditor_int_SelectionCursor_bool_bool_bool_wasm( - arg: cstring): cstring {.importc.} -proc moveCursorLine*(self: TextDocumentEditor; distance: int; - cursor: SelectionCursor = SelectionCursor.Config; - all: bool = true; wrap: bool = true; - includeAfter: bool = true) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add distance.toJson() - argsJson.add cursor.toJson() - argsJson.add all.toJson() - argsJson.add wrap.toJson() - argsJson.add includeAfter.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_moveCursorLine_void_TextDocumentEditor_int_SelectionCursor_bool_bool_bool_wasm( - argsJsonString.cstring) - - -proc editor_text_moveCursorVisualLine_void_TextDocumentEditor_int_SelectionCursor_bool_bool_bool_wasm( - arg: cstring): cstring {.importc.} -proc moveCursorVisualLine*(self: TextDocumentEditor; distance: int; - cursor: SelectionCursor = SelectionCursor.Config; - all: bool = true; wrap: bool = true; - includeAfter: bool = true) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add distance.toJson() - argsJson.add cursor.toJson() - argsJson.add all.toJson() - argsJson.add wrap.toJson() - argsJson.add includeAfter.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_moveCursorVisualLine_void_TextDocumentEditor_int_SelectionCursor_bool_bool_bool_wasm( - argsJsonString.cstring) - - -proc editor_text_moveCursorPage_void_TextDocumentEditor_float_SelectionCursor_bool_bool_bool_wasm( - arg: cstring): cstring {.importc.} -proc moveCursorPage*(self: TextDocumentEditor; distance: float; - cursor: SelectionCursor = SelectionCursor.Config; - all: bool = true; wrap: bool = true; - includeAfter: bool = true) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add distance.toJson() - argsJson.add cursor.toJson() - argsJson.add all.toJson() - argsJson.add wrap.toJson() - argsJson.add includeAfter.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_moveCursorPage_void_TextDocumentEditor_float_SelectionCursor_bool_bool_bool_wasm( - argsJsonString.cstring) - - -proc editor_text_moveCursorVisualPage_void_TextDocumentEditor_float_SelectionCursor_bool_bool_bool_wasm( - arg: cstring): cstring {.importc.} -proc moveCursorVisualPage*(self: TextDocumentEditor; distance: float; - cursor: SelectionCursor = SelectionCursor.Config; - all: bool = true; wrap: bool = true; - includeAfter: bool = true) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add distance.toJson() - argsJson.add cursor.toJson() - argsJson.add all.toJson() - argsJson.add wrap.toJson() - argsJson.add includeAfter.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_moveCursorVisualPage_void_TextDocumentEditor_float_SelectionCursor_bool_bool_bool_wasm( - argsJsonString.cstring) - - -proc editor_text_moveCursorHome_void_TextDocumentEditor_SelectionCursor_bool_wasm( - arg: cstring): cstring {.importc.} -proc moveCursorHome*(self: TextDocumentEditor; - cursor: SelectionCursor = SelectionCursor.Config; - all: bool = true) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add cursor.toJson() - argsJson.add all.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_moveCursorHome_void_TextDocumentEditor_SelectionCursor_bool_wasm( - argsJsonString.cstring) - - -proc editor_text_moveCursorEnd_void_TextDocumentEditor_SelectionCursor_bool_bool_wasm( - arg: cstring): cstring {.importc.} -proc moveCursorEnd*(self: TextDocumentEditor; - cursor: SelectionCursor = SelectionCursor.Config; - all: bool = true; includeAfter: bool = true) {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add cursor.toJson() - argsJson.add all.toJson() - argsJson.add includeAfter.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_moveCursorEnd_void_TextDocumentEditor_SelectionCursor_bool_bool_wasm( - argsJsonString.cstring) - - -proc editor_text_moveCursorTo_void_TextDocumentEditor_string_SelectionCursor_bool_wasm( - arg: cstring): cstring {.importc.} -proc moveCursorTo*(self: TextDocumentEditor; str: string; - cursor: SelectionCursor = SelectionCursor.Config; - all: bool = true) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add str.toJson() - argsJson.add cursor.toJson() - argsJson.add all.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_moveCursorTo_void_TextDocumentEditor_string_SelectionCursor_bool_wasm( - argsJsonString.cstring) - - -proc editor_text_moveCursorBefore_void_TextDocumentEditor_string_SelectionCursor_bool_wasm( - arg: cstring): cstring {.importc.} -proc moveCursorBefore*(self: TextDocumentEditor; str: string; - cursor: SelectionCursor = SelectionCursor.Config; - all: bool = true) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add str.toJson() - argsJson.add cursor.toJson() - argsJson.add all.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_moveCursorBefore_void_TextDocumentEditor_string_SelectionCursor_bool_wasm( - argsJsonString.cstring) - - -proc editor_text_moveCursorNextFindResult_void_TextDocumentEditor_SelectionCursor_bool_bool_wasm( - arg: cstring): cstring {.importc.} -proc moveCursorNextFindResult*(self: TextDocumentEditor; cursor: SelectionCursor = SelectionCursor.Config; - all: bool = true; wrap: bool = true) {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add cursor.toJson() - argsJson.add all.toJson() - argsJson.add wrap.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_moveCursorNextFindResult_void_TextDocumentEditor_SelectionCursor_bool_bool_wasm( - argsJsonString.cstring) - - -proc editor_text_moveCursorPrevFindResult_void_TextDocumentEditor_SelectionCursor_bool_bool_wasm( - arg: cstring): cstring {.importc.} -proc moveCursorPrevFindResult*(self: TextDocumentEditor; cursor: SelectionCursor = SelectionCursor.Config; - all: bool = true; wrap: bool = true) {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add cursor.toJson() - argsJson.add all.toJson() - argsJson.add wrap.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_moveCursorPrevFindResult_void_TextDocumentEditor_SelectionCursor_bool_bool_wasm( - argsJsonString.cstring) - - -proc editor_text_moveCursorLineCenter_void_TextDocumentEditor_SelectionCursor_bool_wasm( - arg: cstring): cstring {.importc.} -proc moveCursorLineCenter*(self: TextDocumentEditor; - cursor: SelectionCursor = SelectionCursor.Config; - all: bool = true) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add cursor.toJson() - argsJson.add all.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_moveCursorLineCenter_void_TextDocumentEditor_SelectionCursor_bool_wasm( - argsJsonString.cstring) - - -proc editor_text_moveCursorCenter_void_TextDocumentEditor_SelectionCursor_bool_wasm( - arg: cstring): cstring {.importc.} -proc moveCursorCenter*(self: TextDocumentEditor; - cursor: SelectionCursor = SelectionCursor.Config; - all: bool = true) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add cursor.toJson() - argsJson.add all.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_moveCursorCenter_void_TextDocumentEditor_SelectionCursor_bool_wasm( - argsJsonString.cstring) - - -proc editor_text_scrollToCursor_void_TextDocumentEditor_SelectionCursor_Option_float_Option_ScrollBehaviour_float_wasm( - arg: cstring): cstring {.importc.} -proc scrollToCursor*(self: TextDocumentEditor; - cursor: SelectionCursor = SelectionCursor.Config; - margin: Option[float] = float.none; scrollBehaviour: Option[ - ScrollBehaviour] = ScrollBehaviour.none; relativePosition: float = 0.5) {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add cursor.toJson() - argsJson.add margin.toJson() - argsJson.add scrollBehaviour.toJson() - argsJson.add relativePosition.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_scrollToCursor_void_TextDocumentEditor_SelectionCursor_Option_float_Option_ScrollBehaviour_float_wasm( - argsJsonString.cstring) - - -proc editor_text_setNextScrollBehaviour_void_TextDocumentEditor_ScrollBehaviour_wasm( - arg: cstring): cstring {.importc.} -proc setNextScrollBehaviour*(self: TextDocumentEditor; - scrollBehaviour: ScrollBehaviour) {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add scrollBehaviour.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_setNextScrollBehaviour_void_TextDocumentEditor_ScrollBehaviour_wasm( - argsJsonString.cstring) - - -proc editor_text_setDefaultSnapBehaviour_void_TextDocumentEditor_ScrollSnapBehaviour_wasm( - arg: cstring): cstring {.importc.} -proc setDefaultSnapBehaviour*(self: TextDocumentEditor; - snapBehaviour: ScrollSnapBehaviour) {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add snapBehaviour.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_setDefaultSnapBehaviour_void_TextDocumentEditor_ScrollSnapBehaviour_wasm( - argsJsonString.cstring) - - -proc editor_text_setNextSnapBehaviour_void_TextDocumentEditor_ScrollSnapBehaviour_wasm( - arg: cstring): cstring {.importc.} -proc setNextSnapBehaviour*(self: TextDocumentEditor; - snapBehaviour: ScrollSnapBehaviour) {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add snapBehaviour.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_setNextSnapBehaviour_void_TextDocumentEditor_ScrollSnapBehaviour_wasm( - argsJsonString.cstring) - - -proc editor_text_setCursorScrollOffset_void_TextDocumentEditor_float_SelectionCursor_wasm( - arg: cstring): cstring {.importc.} -proc setCursorScrollOffset*(self: TextDocumentEditor; offset: float; - cursor: SelectionCursor = SelectionCursor.Config) {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add offset.toJson() - argsJson.add cursor.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_setCursorScrollOffset_void_TextDocumentEditor_float_SelectionCursor_wasm( - argsJsonString.cstring) - - -proc editor_text_getContentBounds_Vec2_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc getContentBounds*(self: TextDocumentEditor): Vec2 {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_getContentBounds_Vec2_TextDocumentEditor_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_centerCursor_void_TextDocumentEditor_SelectionCursor_wasm( - arg: cstring): cstring {.importc.} -proc centerCursor*(self: TextDocumentEditor; - cursor: SelectionCursor = SelectionCursor.Config) {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add cursor.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_centerCursor_void_TextDocumentEditor_SelectionCursor_wasm( - argsJsonString.cstring) - - -proc editor_text_reloadTreesitter_void_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc reloadTreesitter*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_reloadTreesitter_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_deleteLeft_void_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc deleteLeft*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_deleteLeft_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_deleteRight_void_TextDocumentEditor_bool_wasm(arg: cstring): cstring {. - importc.} -proc deleteRight*(self: TextDocumentEditor; includeAfter: bool = true) {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add includeAfter.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_deleteRight_void_TextDocumentEditor_bool_wasm( - argsJsonString.cstring) - - -proc editor_text_getCommandCount_int_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc getCommandCount*(self: TextDocumentEditor): int {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_getCommandCount_int_TextDocumentEditor_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_setCommandCount_void_TextDocumentEditor_int_wasm(arg: cstring): cstring {. - importc.} -proc setCommandCount*(self: TextDocumentEditor; count: int) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add count.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_setCommandCount_void_TextDocumentEditor_int_wasm( - argsJsonString.cstring) - - -proc editor_text_setCommandCountRestore_void_TextDocumentEditor_int_wasm( - arg: cstring): cstring {.importc.} -proc setCommandCountRestore*(self: TextDocumentEditor; count: int) {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add count.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_setCommandCountRestore_void_TextDocumentEditor_int_wasm( - argsJsonString.cstring) - - -proc editor_text_updateCommandCount_void_TextDocumentEditor_int_wasm( - arg: cstring): cstring {.importc.} -proc updateCommandCount*(self: TextDocumentEditor; digit: int) {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add digit.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_updateCommandCount_void_TextDocumentEditor_int_wasm( - argsJsonString.cstring) - - -proc editor_text_runAction_Option_JsonNode_TextDocumentEditor_string_JsonNode_wasm( - arg: cstring): cstring {.importc.} -proc runAction*(self: TextDocumentEditor; action: string; args: JsonNode): Option[ - JsonNode] {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add action.toJson() - argsJson.add args.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_runAction_Option_JsonNode_TextDocumentEditor_string_JsonNode_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_findWordBoundary_Selection_TextDocumentEditor_Cursor_wasm( - arg: cstring): cstring {.importc.} -proc findWordBoundary*(self: TextDocumentEditor; cursor: Cursor): Selection {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add cursor.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_findWordBoundary_Selection_TextDocumentEditor_Cursor_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_getSelectionInPair_Selection_TextDocumentEditor_Cursor_char_wasm( - arg: cstring): cstring {.importc.} -proc getSelectionInPair*(self: TextDocumentEditor; cursor: Cursor; - delimiter: char): Selection {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add cursor.toJson() - argsJson.add delimiter.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_getSelectionInPair_Selection_TextDocumentEditor_Cursor_char_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_getSelectionInPairNested_Selection_TextDocumentEditor_Cursor_char_char_wasm( - arg: cstring): cstring {.importc.} -proc getSelectionInPairNested*(self: TextDocumentEditor; cursor: Cursor; - open: char; close: char): Selection {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add cursor.toJson() - argsJson.add open.toJson() - argsJson.add close.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_getSelectionInPairNested_Selection_TextDocumentEditor_Cursor_char_char_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_extendSelectionWithMove_Selection_TextDocumentEditor_Selection_string_int_wasm( - arg: cstring): cstring {.importc.} -proc extendSelectionWithMove*(self: TextDocumentEditor; selection: Selection; - move: string; count: int = 0): Selection {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add selection.toJson() - argsJson.add move.toJson() - argsJson.add count.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_extendSelectionWithMove_Selection_TextDocumentEditor_Selection_string_int_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_vimMotionWord_Selection_TextDocumentEditor_Cursor_int_wasm( - arg: cstring): cstring {.importc.} -proc vimMotionWord*(self: TextDocumentEditor; cursor: Cursor; count: int = 0): Selection {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add cursor.toJson() - argsJson.add count.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_vimMotionWord_Selection_TextDocumentEditor_Cursor_int_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_vimMotionWordBig_Selection_TextDocumentEditor_Cursor_int_wasm( - arg: cstring): cstring {.importc.} -proc vimMotionWordBig*(self: TextDocumentEditor; cursor: Cursor; count: int = 0): Selection {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add cursor.toJson() - argsJson.add count.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_vimMotionWordBig_Selection_TextDocumentEditor_Cursor_int_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_getSelectionForMove_Selection_TextDocumentEditor_Cursor_string_int_wasm( - arg: cstring): cstring {.importc.} -proc getSelectionForMove*(self: TextDocumentEditor; cursor: Cursor; - move: string; count: int = 0): Selection {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add cursor.toJson() - argsJson.add move.toJson() - argsJson.add count.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_getSelectionForMove_Selection_TextDocumentEditor_Cursor_string_int_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_applyMove_void_TextDocumentEditor_JsonNode_wasm(arg: cstring): cstring {. - importc.} -proc applyMove*(self: TextDocumentEditor; args: JsonNode) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add args.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_applyMove_void_TextDocumentEditor_JsonNode_wasm( - argsJsonString.cstring) - - -proc editor_text_deleteMove_void_TextDocumentEditor_string_bool_SelectionCursor_bool_wasm( - arg: cstring): cstring {.importc.} -proc deleteMove*(self: TextDocumentEditor; move: string; inside: bool = false; - which: SelectionCursor = SelectionCursor.Config; - all: bool = true) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add move.toJson() - argsJson.add inside.toJson() - argsJson.add which.toJson() - argsJson.add all.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_deleteMove_void_TextDocumentEditor_string_bool_SelectionCursor_bool_wasm( - argsJsonString.cstring) - - -proc editor_text_selectMove_void_TextDocumentEditor_string_bool_SelectionCursor_bool_wasm( - arg: cstring): cstring {.importc.} -proc selectMove*(self: TextDocumentEditor; move: string; inside: bool = false; - which: SelectionCursor = SelectionCursor.Config; - all: bool = true) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add move.toJson() - argsJson.add inside.toJson() - argsJson.add which.toJson() - argsJson.add all.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_selectMove_void_TextDocumentEditor_string_bool_SelectionCursor_bool_wasm( - argsJsonString.cstring) - - -proc editor_text_extendSelectMove_void_TextDocumentEditor_string_bool_SelectionCursor_bool_wasm( - arg: cstring): cstring {.importc.} -proc extendSelectMove*(self: TextDocumentEditor; move: string; - inside: bool = false; - which: SelectionCursor = SelectionCursor.Config; - all: bool = true) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add move.toJson() - argsJson.add inside.toJson() - argsJson.add which.toJson() - argsJson.add all.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_extendSelectMove_void_TextDocumentEditor_string_bool_SelectionCursor_bool_wasm( - argsJsonString.cstring) - - -proc editor_text_copyMove_void_TextDocumentEditor_string_bool_SelectionCursor_bool_wasm( - arg: cstring): cstring {.importc.} -proc copyMove*(self: TextDocumentEditor; move: string; inside: bool = false; - which: SelectionCursor = SelectionCursor.Config; all: bool = true) {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add move.toJson() - argsJson.add inside.toJson() - argsJson.add which.toJson() - argsJson.add all.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_copyMove_void_TextDocumentEditor_string_bool_SelectionCursor_bool_wasm( - argsJsonString.cstring) - - -proc editor_text_changeMove_void_TextDocumentEditor_string_bool_SelectionCursor_bool_wasm( - arg: cstring): cstring {.importc.} -proc changeMove*(self: TextDocumentEditor; move: string; inside: bool = false; - which: SelectionCursor = SelectionCursor.Config; - all: bool = true) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add move.toJson() - argsJson.add inside.toJson() - argsJson.add which.toJson() - argsJson.add all.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_changeMove_void_TextDocumentEditor_string_bool_SelectionCursor_bool_wasm( - argsJsonString.cstring) - - -proc editor_text_moveLast_void_TextDocumentEditor_string_SelectionCursor_bool_int_wasm( - arg: cstring): cstring {.importc.} -proc moveLast*(self: TextDocumentEditor; move: string; - which: SelectionCursor = SelectionCursor.Config; - all: bool = true; count: int = 0) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add move.toJson() - argsJson.add which.toJson() - argsJson.add all.toJson() - argsJson.add count.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_moveLast_void_TextDocumentEditor_string_SelectionCursor_bool_int_wasm( - argsJsonString.cstring) - - -proc editor_text_moveFirst_void_TextDocumentEditor_string_SelectionCursor_bool_int_wasm( - arg: cstring): cstring {.importc.} -proc moveFirst*(self: TextDocumentEditor; move: string; - which: SelectionCursor = SelectionCursor.Config; - all: bool = true; count: int = 0) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add move.toJson() - argsJson.add which.toJson() - argsJson.add all.toJson() - argsJson.add count.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_moveFirst_void_TextDocumentEditor_string_SelectionCursor_bool_int_wasm( - argsJsonString.cstring) - - -proc editor_text_getSearchQuery_string_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc getSearchQuery*(self: TextDocumentEditor): string {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_getSearchQuery_string_TextDocumentEditor_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_setSearchQuery_bool_TextDocumentEditor_string_bool_string_string_wasm( - arg: cstring): cstring {.importc.} -proc setSearchQuery*(self: TextDocumentEditor; query: string; - escapeRegex: bool = false; prefix: string = ""; - suffix: string = ""): bool {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add query.toJson() - argsJson.add escapeRegex.toJson() - argsJson.add prefix.toJson() - argsJson.add suffix.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_setSearchQuery_bool_TextDocumentEditor_string_bool_string_string_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_openSearchBar_void_TextDocumentEditor_string_bool_bool_wasm( - arg: cstring): cstring {.importc.} -proc openSearchBar*(self: TextDocumentEditor; query: string = ""; - scrollToPreview: bool = true; select: bool = true) {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add query.toJson() - argsJson.add scrollToPreview.toJson() - argsJson.add select.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_openSearchBar_void_TextDocumentEditor_string_bool_bool_wasm( - argsJsonString.cstring) - - -proc editor_text_setSearchQueryFromMove_Selection_TextDocumentEditor_string_int_string_string_wasm( - arg: cstring): cstring {.importc.} -proc setSearchQueryFromMove*(self: TextDocumentEditor; move: string; - count: int = 0; prefix: string = ""; - suffix: string = ""): Selection {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add move.toJson() - argsJson.add count.toJson() - argsJson.add prefix.toJson() - argsJson.add suffix.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_setSearchQueryFromMove_Selection_TextDocumentEditor_string_int_string_string_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_toggleLineComment_void_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc toggleLineComment*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_toggleLineComment_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_gotoDefinition_void_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc gotoDefinition*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_gotoDefinition_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_gotoDeclaration_void_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc gotoDeclaration*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_gotoDeclaration_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_gotoTypeDefinition_void_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc gotoTypeDefinition*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_gotoTypeDefinition_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_gotoImplementation_void_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc gotoImplementation*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_gotoImplementation_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_gotoReferences_void_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc gotoReferences*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_gotoReferences_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_switchSourceHeader_void_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc switchSourceHeader*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_switchSourceHeader_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_getCompletions_void_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc getCompletions*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_getCompletions_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_gotoSymbol_void_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc gotoSymbol*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_gotoSymbol_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_fuzzySearchLines_void_TextDocumentEditor_float_bool_wasm( - arg: cstring): cstring {.importc.} -proc fuzzySearchLines*(self: TextDocumentEditor; minScore: float = 0.2; - sort: bool = true) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add minScore.toJson() - argsJson.add sort.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_fuzzySearchLines_void_TextDocumentEditor_float_bool_wasm( - argsJsonString.cstring) - - -proc editor_text_gotoWorkspaceSymbol_void_TextDocumentEditor_string_wasm( - arg: cstring): cstring {.importc.} -proc gotoWorkspaceSymbol*(self: TextDocumentEditor; query: string = "") {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add query.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_gotoWorkspaceSymbol_void_TextDocumentEditor_string_wasm( - argsJsonString.cstring) - - -proc editor_text_rename_void_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc rename*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_rename_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_hideCompletions_void_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc hideCompletions*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_hideCompletions_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_selectPrevCompletion_void_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc selectPrevCompletion*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_selectPrevCompletion_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_selectNextCompletion_void_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc selectNextCompletion*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_selectNextCompletion_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_selectPrevCompletionVisual_void_TextDocumentEditor_wasm( - arg: cstring): cstring {.importc.} -proc selectPrevCompletionVisual*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_selectPrevCompletionVisual_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_selectNextCompletionVisual_void_TextDocumentEditor_wasm( - arg: cstring): cstring {.importc.} -proc selectNextCompletionVisual*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_selectNextCompletionVisual_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_hasTabStops_bool_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc hasTabStops*(self: TextDocumentEditor): bool {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_hasTabStops_bool_TextDocumentEditor_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_clearTabStops_void_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc clearTabStops*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_clearTabStops_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_selectNextTabStop_void_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc selectNextTabStop*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_selectNextTabStop_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_selectPrevTabStop_void_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc selectPrevTabStop*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_selectPrevTabStop_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_applyCompletion_void_TextDocumentEditor_JsonNode_wasm( - arg: cstring): cstring {.importc.} -proc applyCompletion*(self: TextDocumentEditor; completion: JsonNode) {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add completion.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_applyCompletion_void_TextDocumentEditor_JsonNode_wasm( - argsJsonString.cstring) - - -proc editor_text_isShowingCompletions_bool_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc isShowingCompletions*(self: TextDocumentEditor): bool {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_isShowingCompletions_bool_TextDocumentEditor_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_applySelectedCompletion_void_TextDocumentEditor_wasm( - arg: cstring): cstring {.importc.} -proc applySelectedCompletion*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_applySelectedCompletion_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_showHoverFor_void_TextDocumentEditor_Cursor_wasm(arg: cstring): cstring {. - importc.} -proc showHoverFor*(self: TextDocumentEditor; cursor: Cursor) {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add cursor.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_showHoverFor_void_TextDocumentEditor_Cursor_wasm( - argsJsonString.cstring) - - -proc editor_text_showHoverForCurrent_void_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc showHoverForCurrent*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_showHoverForCurrent_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_hideHover_void_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc hideHover*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_hideHover_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_cancelDelayedHideHover_void_TextDocumentEditor_wasm( - arg: cstring): cstring {.importc.} -proc cancelDelayedHideHover*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_cancelDelayedHideHover_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_hideHoverDelayed_void_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc hideHoverDelayed*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_hideHoverDelayed_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_selectCodeAction_void_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc selectCodeAction*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_selectCodeAction_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_clearDiagnostics_void_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc clearDiagnostics*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_clearDiagnostics_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_updateInlayHints_void_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc updateInlayHints*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_updateInlayHints_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_lspInfo_void_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc lspInfo*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_lspInfo_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_setReadOnly_void_TextDocumentEditor_bool_wasm(arg: cstring): cstring {. - importc.} -proc setReadOnly*(self: TextDocumentEditor; readOnly: bool) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add readOnly.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_setReadOnly_void_TextDocumentEditor_bool_wasm( - argsJsonString.cstring) - - -proc editor_text_setFileReadOnly_void_TextDocumentEditor_bool_wasm(arg: cstring): cstring {. - importc.} -proc setFileReadOnly*(self: TextDocumentEditor; readOnly: bool) {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add readOnly.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_setFileReadOnly_void_TextDocumentEditor_bool_wasm( - argsJsonString.cstring) - - -proc editor_text_isRunningSavedCommands_bool_TextDocumentEditor_wasm( - arg: cstring): cstring {.importc.} -proc isRunningSavedCommands*(self: TextDocumentEditor): bool {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_isRunningSavedCommands_bool_TextDocumentEditor_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_runSavedCommands_void_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc runSavedCommands*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_runSavedCommands_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_clearCurrentCommandHistory_void_TextDocumentEditor_bool_wasm( - arg: cstring): cstring {.importc.} -proc clearCurrentCommandHistory*(self: TextDocumentEditor; - retainLast: bool = false) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add retainLast.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_clearCurrentCommandHistory_void_TextDocumentEditor_bool_wasm( - argsJsonString.cstring) - - -proc editor_text_saveCurrentCommandHistory_void_TextDocumentEditor_wasm( - arg: cstring): cstring {.importc.} -proc saveCurrentCommandHistory*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_saveCurrentCommandHistory_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_getSelection_Selection_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc getSelection*(self: TextDocumentEditor): Selection {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_getSelection_Selection_TextDocumentEditor_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_getSelections_Selections_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc getSelections*(self: TextDocumentEditor): Selections {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_getSelections_Selections_TextDocumentEditor_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_setSelection_void_TextDocumentEditor_Selection_wasm( - arg: cstring): cstring {.importc.} -proc setSelection*(self: TextDocumentEditor; selection: Selection) {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add selection.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_setSelection_void_TextDocumentEditor_Selection_wasm( - argsJsonString.cstring) - - -proc editor_text_setSelections_void_TextDocumentEditor_Selections_wasm( - arg: cstring): cstring {.importc.} -proc setSelections*(self: TextDocumentEditor; selections: Selections) {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add selections.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_setSelections_void_TextDocumentEditor_Selections_wasm( - argsJsonString.cstring) - - -proc editor_text_setTargetSelection_void_TextDocumentEditor_Selection_wasm( - arg: cstring): cstring {.importc.} -proc setTargetSelection*(self: TextDocumentEditor; selection: Selection) {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add selection.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_setTargetSelection_void_TextDocumentEditor_Selection_wasm( - argsJsonString.cstring) - - -proc editor_text_enterChooseCursorMode_void_TextDocumentEditor_string_wasm( - arg: cstring): cstring {.importc.} -proc enterChooseCursorMode*(self: TextDocumentEditor; action: string) {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add action.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_enterChooseCursorMode_void_TextDocumentEditor_string_wasm( - argsJsonString.cstring) - - -proc editor_text_recordCurrentCommand_void_TextDocumentEditor_seq_string_wasm( - arg: cstring): cstring {.importc.} -proc recordCurrentCommand*(self: TextDocumentEditor; - registers: seq[string] = @[]) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add registers.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_recordCurrentCommand_void_TextDocumentEditor_seq_string_wasm( - argsJsonString.cstring) - - -proc editor_text_runControlClickCommand_void_TextDocumentEditor_wasm( - arg: cstring): cstring {.importc.} -proc runControlClickCommand*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_runControlClickCommand_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_runSingleClickCommand_void_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc runSingleClickCommand*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_runSingleClickCommand_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_runDoubleClickCommand_void_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc runDoubleClickCommand*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_runDoubleClickCommand_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_runTripleClickCommand_void_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc runTripleClickCommand*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_runTripleClickCommand_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_runDragCommand_void_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc runDragCommand*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_runDragCommand_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - - -proc editor_text_getCurrentEventHandlers_seq_string_TextDocumentEditor_wasm( - arg: cstring): cstring {.importc.} -proc getCurrentEventHandlers*(self: TextDocumentEditor): seq[string] {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_getCurrentEventHandlers_seq_string_TextDocumentEditor_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_setCustomHeader_void_TextDocumentEditor_string_wasm( - arg: cstring): cstring {.importc.} -proc setCustomHeader*(self: TextDocumentEditor; text: string) {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add text.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_setCustomHeader_void_TextDocumentEditor_string_wasm( - argsJsonString.cstring) - - -proc editor_text_cycleCase_string_TextDocumentEditor_Selection_bool_wasm( - arg: cstring): cstring {.importc.} -proc cycleCase*(self: TextDocumentEditor; selection: Selection; - inclusiveEnd: bool = false): string {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add selection.toJson() - argsJson.add inclusiveEnd.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_cycleCase_string_TextDocumentEditor_Selection_bool_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editor_text_cycleSelectedCase_void_TextDocumentEditor_wasm(arg: cstring): cstring {. - importc.} -proc cycleSelectedCase*(self: TextDocumentEditor) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = editor_text_cycleSelectedCase_void_TextDocumentEditor_wasm( - argsJsonString.cstring) - diff --git a/scripting/editors_api_wasm.nim b/scripting/editors_api_wasm.nim deleted file mode 100644 index 91066362b..000000000 --- a/scripting/editors_api_wasm.nim +++ /dev/null @@ -1,32 +0,0 @@ -import std/[json, options] -import scripting_api, misc/myjsonutils - -## This file is auto generated, don't modify. - - -proc editors_getAllEditors_seq_EditorId_DocumentEditorService_wasm(arg: cstring): cstring {. - importc.} -proc getAllEditors*(): seq[EditorId] {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = editors_getAllEditors_seq_EditorId_DocumentEditorService_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc editors_getExistingEditor_Option_EditorId_DocumentEditorService_string_wasm( - arg: cstring): cstring {.importc.} -proc getExistingEditor*(path: string): Option[EditorId] {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add path.toJson() - let argsJsonString = $argsJson - let res {.used.} = editors_getExistingEditor_Option_EditorId_DocumentEditorService_string_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - diff --git a/scripting/events_api_wasm.nim b/scripting/events_api_wasm.nim deleted file mode 100644 index 28274464f..000000000 --- a/scripting/events_api_wasm.nim +++ /dev/null @@ -1,101 +0,0 @@ -import std/[json, options] -import scripting_api, misc/myjsonutils - -## This file is auto generated, don't modify. - - -proc events_addKeyDefinitions_void_EventHandlerService_string_seq_string_wasm( - arg: cstring): cstring {.importc.} -proc addKeyDefinitions*(name: string; keys: seq[string]) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add name.toJson() - argsJson.add keys.toJson() - let argsJsonString = $argsJson - let res {.used.} = events_addKeyDefinitions_void_EventHandlerService_string_seq_string_wasm( - argsJsonString.cstring) - - -proc events_setKeyDefinitions_void_EventHandlerService_string_seq_string_wasm( - arg: cstring): cstring {.importc.} -proc setKeyDefinitions*(name: string; keys: seq[string]) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add name.toJson() - argsJson.add keys.toJson() - let argsJsonString = $argsJson - let res {.used.} = events_setKeyDefinitions_void_EventHandlerService_string_seq_string_wasm( - argsJsonString.cstring) - - -proc events_setLeader_void_EventHandlerService_string_wasm(arg: cstring): cstring {. - importc.} -proc setLeader*(leader: string) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add leader.toJson() - let argsJsonString = $argsJson - let res {.used.} = events_setLeader_void_EventHandlerService_string_wasm( - argsJsonString.cstring) - - -proc events_setLeaders_void_EventHandlerService_seq_string_wasm(arg: cstring): cstring {. - importc.} -proc setLeaders*(leaders: seq[string]) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add leaders.toJson() - let argsJsonString = $argsJson - let res {.used.} = events_setLeaders_void_EventHandlerService_seq_string_wasm( - argsJsonString.cstring) - - -proc events_addLeader_void_EventHandlerService_string_wasm(arg: cstring): cstring {. - importc.} -proc addLeader*(leader: string) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add leader.toJson() - let argsJsonString = $argsJson - let res {.used.} = events_addLeader_void_EventHandlerService_string_wasm( - argsJsonString.cstring) - - -proc events_addLeaders_void_EventHandlerService_seq_string_wasm(arg: cstring): cstring {. - importc.} -proc addLeaders*(leaders: seq[string]) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add leaders.toJson() - let argsJsonString = $argsJson - let res {.used.} = events_addLeaders_void_EventHandlerService_seq_string_wasm( - argsJsonString.cstring) - - -proc events_clearCommands_void_EventHandlerService_string_wasm(arg: cstring): cstring {. - importc.} -proc clearCommands*(context: string) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add context.toJson() - let argsJsonString = $argsJson - let res {.used.} = events_clearCommands_void_EventHandlerService_string_wasm( - argsJsonString.cstring) - - -proc events_removeCommand_void_EventHandlerService_string_string_wasm( - arg: cstring): cstring {.importc.} -proc removeCommand*(context: string; keys: string) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add context.toJson() - argsJson.add keys.toJson() - let argsJsonString = $argsJson - let res {.used.} = events_removeCommand_void_EventHandlerService_string_string_wasm( - argsJsonString.cstring) - - -proc events_addCommandDescription_void_EventHandlerService_string_string_string_wasm( - arg: cstring): cstring {.importc.} -proc addCommandDescription*(context: string; keys: string; - description: string = "") {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add context.toJson() - argsJson.add keys.toJson() - argsJson.add description.toJson() - let argsJsonString = $argsJson - let res {.used.} = events_addCommandDescription_void_EventHandlerService_string_string_string_wasm( - argsJsonString.cstring) - diff --git a/scripting/layout_api_wasm.nim b/scripting/layout_api_wasm.nim deleted file mode 100644 index 8951867f9..000000000 --- a/scripting/layout_api_wasm.nim +++ /dev/null @@ -1,347 +0,0 @@ -import std/[json, options] -import scripting_api, misc/myjsonutils - -## This file is auto generated, don't modify. - - -proc layout_changeSplitSize_void_LayoutService_float_bool_wasm(arg: cstring): cstring {. - importc.} -proc changeSplitSize*(change: float; vertical: bool) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add change.toJson() - argsJson.add vertical.toJson() - let argsJsonString = $argsJson - let res {.used.} = layout_changeSplitSize_void_LayoutService_float_bool_wasm( - argsJsonString.cstring) - - -proc layout_toggleMaximizeViewLocal_void_LayoutService_string_wasm(arg: cstring): cstring {. - importc.} -proc toggleMaximizeViewLocal*(slot: string = "**") {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add slot.toJson() - let argsJsonString = $argsJson - let res {.used.} = layout_toggleMaximizeViewLocal_void_LayoutService_string_wasm( - argsJsonString.cstring) - - -proc layout_toggleMaximizeView_void_LayoutService_wasm(arg: cstring): cstring {. - importc.} -proc toggleMaximizeView*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = layout_toggleMaximizeView_void_LayoutService_wasm( - argsJsonString.cstring) - - -proc layout_setMaxViews_void_LayoutService_string_int_wasm(arg: cstring): cstring {. - importc.} -proc setMaxViews*(slot: string; maxViews: int = int.high) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add slot.toJson() - argsJson.add maxViews.toJson() - let argsJsonString = $argsJson - let res {.used.} = layout_setMaxViews_void_LayoutService_string_int_wasm( - argsJsonString.cstring) - - -proc layout_getNumVisibleViews_int_LayoutService_wasm(arg: cstring): cstring {. - importc.} -proc getNumVisibleViews*(): int {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = layout_getNumVisibleViews_int_LayoutService_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc layout_getNumHiddenViews_int_LayoutService_wasm(arg: cstring): cstring {. - importc.} -proc getNumHiddenViews*(): int {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = layout_getNumHiddenViews_int_LayoutService_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc layout_showEditor_void_LayoutService_EditorId_string_bool_wasm(arg: cstring): cstring {. - importc.} -proc showEditor*(editorId: EditorId; slot: string = ""; focus: bool = true) {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add editorId.toJson() - argsJson.add slot.toJson() - argsJson.add focus.toJson() - let argsJsonString = $argsJson - let res {.used.} = layout_showEditor_void_LayoutService_EditorId_string_bool_wasm( - argsJsonString.cstring) - - -proc layout_getOrOpenEditor_Option_EditorId_LayoutService_string_wasm( - arg: cstring): cstring {.importc.} -proc getOrOpenEditor*(path: string): Option[EditorId] {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add path.toJson() - let argsJsonString = $argsJson - let res {.used.} = layout_getOrOpenEditor_Option_EditorId_LayoutService_string_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc layout_hideActiveView_void_LayoutService_bool_wasm(arg: cstring): cstring {. - importc.} -proc hideActiveView*(closeOpenPopup: bool = true) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add closeOpenPopup.toJson() - let argsJsonString = $argsJson - let res {.used.} = layout_hideActiveView_void_LayoutService_bool_wasm( - argsJsonString.cstring) - - -proc layout_closeActiveView_void_LayoutService_bool_bool_wasm(arg: cstring): cstring {. - importc.} -proc closeActiveView*(closeOpenPopup: bool = true; restoreHidden: bool = true) {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add closeOpenPopup.toJson() - argsJson.add restoreHidden.toJson() - let argsJsonString = $argsJson - let res {.used.} = layout_closeActiveView_void_LayoutService_bool_bool_wasm( - argsJsonString.cstring) - - -proc layout_hideOtherViews_void_LayoutService_wasm(arg: cstring): cstring {. - importc.} -proc hideOtherViews*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = layout_hideOtherViews_void_LayoutService_wasm( - argsJsonString.cstring) - - -proc layout_closeOtherViews_void_LayoutService_wasm(arg: cstring): cstring {. - importc.} -proc closeOtherViews*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = layout_closeOtherViews_void_LayoutService_wasm( - argsJsonString.cstring) - - -proc layout_focusViewLeft_void_LayoutService_wasm(arg: cstring): cstring {. - importc.} -proc focusViewLeft*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = layout_focusViewLeft_void_LayoutService_wasm( - argsJsonString.cstring) - - -proc layout_focusViewRight_void_LayoutService_wasm(arg: cstring): cstring {. - importc.} -proc focusViewRight*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = layout_focusViewRight_void_LayoutService_wasm( - argsJsonString.cstring) - - -proc layout_focusViewUp_void_LayoutService_wasm(arg: cstring): cstring {.importc.} -proc focusViewUp*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = layout_focusViewUp_void_LayoutService_wasm( - argsJsonString.cstring) - - -proc layout_focusViewDown_void_LayoutService_wasm(arg: cstring): cstring {. - importc.} -proc focusViewDown*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = layout_focusViewDown_void_LayoutService_wasm( - argsJsonString.cstring) - - -proc layout_focusView_void_LayoutService_string_wasm(arg: cstring): cstring {. - importc.} -proc focusView*(slot: string) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add slot.toJson() - let argsJsonString = $argsJson - let res {.used.} = layout_focusView_void_LayoutService_string_wasm( - argsJsonString.cstring) - - -proc layout_focusNextView_void_LayoutService_string_wasm(arg: cstring): cstring {. - importc.} -proc focusNextView*(slot: string = "") {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add slot.toJson() - let argsJsonString = $argsJson - let res {.used.} = layout_focusNextView_void_LayoutService_string_wasm( - argsJsonString.cstring) - - -proc layout_focusPrevView_void_LayoutService_string_wasm(arg: cstring): cstring {. - importc.} -proc focusPrevView*(slot: string = "") {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add slot.toJson() - let argsJsonString = $argsJson - let res {.used.} = layout_focusPrevView_void_LayoutService_string_wasm( - argsJsonString.cstring) - - -proc layout_openPrevView_void_LayoutService_wasm(arg: cstring): cstring {. - importc.} -proc openPrevView*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = layout_openPrevView_void_LayoutService_wasm( - argsJsonString.cstring) - - -proc layout_openNextView_void_LayoutService_wasm(arg: cstring): cstring {. - importc.} -proc openNextView*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = layout_openNextView_void_LayoutService_wasm( - argsJsonString.cstring) - - -proc layout_openLastView_void_LayoutService_wasm(arg: cstring): cstring {. - importc.} -proc openLastView*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = layout_openLastView_void_LayoutService_wasm( - argsJsonString.cstring) - - -proc layout_setLayout_void_LayoutService_string_wasm(arg: cstring): cstring {. - importc.} -proc setLayout*(layout: string) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add layout.toJson() - let argsJsonString = $argsJson - let res {.used.} = layout_setLayout_void_LayoutService_string_wasm( - argsJsonString.cstring) - - -proc layout_setActiveViewIndex_void_LayoutService_string_int_wasm(arg: cstring): cstring {. - importc.} -proc setActiveViewIndex*(slot: string; index: int) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add slot.toJson() - argsJson.add index.toJson() - let argsJsonString = $argsJson - let res {.used.} = layout_setActiveViewIndex_void_LayoutService_string_int_wasm( - argsJsonString.cstring) - - -proc layout_moveActiveViewFirst_void_LayoutService_wasm(arg: cstring): cstring {. - importc.} -proc moveActiveViewFirst*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = layout_moveActiveViewFirst_void_LayoutService_wasm( - argsJsonString.cstring) - - -proc layout_moveActiveViewPrev_void_LayoutService_wasm(arg: cstring): cstring {. - importc.} -proc moveActiveViewPrev*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = layout_moveActiveViewPrev_void_LayoutService_wasm( - argsJsonString.cstring) - - -proc layout_moveActiveViewNext_void_LayoutService_wasm(arg: cstring): cstring {. - importc.} -proc moveActiveViewNext*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = layout_moveActiveViewNext_void_LayoutService_wasm( - argsJsonString.cstring) - - -proc layout_moveActiveViewNextAndGoBack_void_LayoutService_wasm(arg: cstring): cstring {. - importc.} -proc moveActiveViewNextAndGoBack*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = layout_moveActiveViewNextAndGoBack_void_LayoutService_wasm( - argsJsonString.cstring) - - -proc layout_splitView_void_LayoutService_string_wasm(arg: cstring): cstring {. - importc.} -proc splitView*(slot: string = "") {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add slot.toJson() - let argsJsonString = $argsJson - let res {.used.} = layout_splitView_void_LayoutService_string_wasm( - argsJsonString.cstring) - - -proc layout_moveView_void_LayoutService_string_wasm(arg: cstring): cstring {. - importc.} -proc moveView*(slot: string) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add slot.toJson() - let argsJsonString = $argsJson - let res {.used.} = layout_moveView_void_LayoutService_string_wasm( - argsJsonString.cstring) - - -proc layout_wrapLayout_void_LayoutService_JsonNode_string_wasm(arg: cstring): cstring {. - importc.} -proc wrapLayout*(layout: JsonNode; slot: string = "**") {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add layout.toJson() - argsJson.add slot.toJson() - let argsJsonString = $argsJson - let res {.used.} = layout_wrapLayout_void_LayoutService_JsonNode_string_wasm( - argsJsonString.cstring) - - -proc layout_chooseLayout_void_LayoutService_wasm(arg: cstring): cstring {. - importc.} -proc chooseLayout*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = layout_chooseLayout_void_LayoutService_wasm( - argsJsonString.cstring) - - -proc layout_logLayout_void_LayoutService_wasm(arg: cstring): cstring {.importc.} -proc logLayout*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = layout_logLayout_void_LayoutService_wasm( - argsJsonString.cstring) - - -proc layout_open_void_LayoutService_string_string_wasm(arg: cstring): cstring {. - importc.} -proc open*(path: string; slot: string = "") {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add path.toJson() - argsJson.add slot.toJson() - let argsJsonString = $argsJson - let res {.used.} = layout_open_void_LayoutService_string_string_wasm( - argsJsonString.cstring) - diff --git a/scripting/lsp_api_wasm.nim b/scripting/lsp_api_wasm.nim deleted file mode 100644 index de0bda16c..000000000 --- a/scripting/lsp_api_wasm.nim +++ /dev/null @@ -1,29 +0,0 @@ -import std/[json, options] -import scripting_api, misc/myjsonutils - -## This file is auto generated, don't modify. - - -proc lsp_lspLogVerbose_void_bool_wasm(arg: cstring): cstring {.importc.} -proc lspLogVerbose*(val: bool) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add val.toJson() - let argsJsonString = $argsJson - let res {.used.} = lsp_lspLogVerbose_void_bool_wasm(argsJsonString.cstring) - - -proc lsp_lspToggleLogServerDebug_void_wasm(arg: cstring): cstring {.importc.} -proc lspToggleLogServerDebug*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = lsp_lspToggleLogServerDebug_void_wasm( - argsJsonString.cstring) - - -proc lsp_lspLogServerDebug_void_bool_wasm(arg: cstring): cstring {.importc.} -proc lspLogServerDebug*(val: bool) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add val.toJson() - let argsJsonString = $argsJson - let res {.used.} = lsp_lspLogServerDebug_void_bool_wasm(argsJsonString.cstring) - diff --git a/scripting/plugin_api.nim b/scripting/plugin_api.nim deleted file mode 100644 index f10469e5e..000000000 --- a/scripting/plugin_api.nim +++ /dev/null @@ -1,45 +0,0 @@ -import "../src/scripting_api" -export scripting_api - -## This file is auto generated, don't modify. - -import collab_api_wasm -export collab_api_wasm -import commands_api_wasm -export commands_api_wasm -import config_api_wasm -export config_api_wasm -import debugger_api_wasm -export debugger_api_wasm -import editor_api_wasm -export editor_api_wasm -import editor_text_api_wasm -export editor_text_api_wasm -import editors_api_wasm -export editors_api_wasm -import events_api_wasm -export events_api_wasm -import layout_api_wasm -export layout_api_wasm -import lsp_api_wasm -export lsp_api_wasm -import plugins_api_wasm -export plugins_api_wasm -import popup_selector_api_wasm -export popup_selector_api_wasm -import process_api_wasm -export process_api_wasm -import registers_api_wasm -export registers_api_wasm -import session_api_wasm -export session_api_wasm -import terminal_api_wasm -export terminal_api_wasm -import toast_api_wasm -export toast_api_wasm -import vcs_api_wasm -export vcs_api_wasm -import vfs_api_wasm -export vfs_api_wasm - -const enableAst* = false diff --git a/scripting/plugin_api_internal.nim b/scripting/plugin_api_internal.nim deleted file mode 100644 index 115acf373..000000000 --- a/scripting/plugin_api_internal.nim +++ /dev/null @@ -1,1005 +0,0 @@ -## This file is auto generated, don't modify. - -import std/[json, options] -import scripting_api - -template varargs*() {.pragma.} - -proc editor_text_enableAutoReload_void_TextDocumentEditor_bool_impl*( - self: TextDocumentEditor; enabled: bool) = - discard -proc editor_text_getFileName_string_TextDocumentEditor_impl*( - self: TextDocumentEditor): string = - discard -proc editor_text_lineCount_int_TextDocumentEditor_impl*(self: TextDocumentEditor): int = - discard -proc editor_text_lineLength_int_TextDocumentEditor_int_impl*( - self: TextDocumentEditor; line: int): int = - discard -proc editor_text_screenLineCount_int_TextDocumentEditor_impl*( - self: TextDocumentEditor): int = - discard -proc editor_text_doMoveCursorLine_Cursor_TextDocumentEditor_Cursor_int_bool_bool_impl*( - self: TextDocumentEditor; cursor: Cursor; offset: int; wrap: bool = false; - includeAfter: bool = false): Cursor = - discard -proc editor_text_doMoveCursorVisualLine_Cursor_TextDocumentEditor_Cursor_int_bool_bool_impl*( - self: TextDocumentEditor; cursor: Cursor; offset: int; wrap: bool = false; - includeAfter: bool = false): Cursor = - discard -proc editor_text_doMoveCursorHome_Cursor_TextDocumentEditor_Cursor_int_bool_bool_impl*( - self: TextDocumentEditor; cursor: Cursor; offset: int; wrap: bool; - includeAfter: bool): Cursor = - discard -proc editor_text_doMoveCursorEnd_Cursor_TextDocumentEditor_Cursor_int_bool_bool_impl*( - self: TextDocumentEditor; cursor: Cursor; offset: int; wrap: bool; - includeAfter: bool): Cursor = - discard -proc editor_text_doMoveCursorVisualHome_Cursor_TextDocumentEditor_Cursor_int_bool_bool_impl*( - self: TextDocumentEditor; cursor: Cursor; offset: int; wrap: bool; - includeAfter: bool): Cursor = - discard -proc editor_text_doMoveCursorVisualEnd_Cursor_TextDocumentEditor_Cursor_int_bool_bool_impl*( - self: TextDocumentEditor; cursor: Cursor; offset: int; wrap: bool; - includeAfter: bool): Cursor = - discard -proc editor_text_doMoveCursorPrevFindResult_Cursor_TextDocumentEditor_Cursor_int_bool_bool_impl*( - self: TextDocumentEditor; cursor: Cursor; offset: int; wrap: bool; - includeAfter: bool): Cursor = - discard -proc editor_text_doMoveCursorNextFindResult_Cursor_TextDocumentEditor_Cursor_int_bool_bool_impl*( - self: TextDocumentEditor; cursor: Cursor; offset: int; wrap: bool; - includeAfter: bool): Cursor = - discard -proc editor_text_doMoveCursorLineCenter_Cursor_TextDocumentEditor_Cursor_int_bool_bool_impl*( - self: TextDocumentEditor; cursor: Cursor; offset: int; wrap: bool; - includeAfter: bool): Cursor = - discard -proc editor_text_doMoveCursorCenter_Cursor_TextDocumentEditor_Cursor_int_bool_bool_impl*( - self: TextDocumentEditor; cursor: Cursor; offset: int; wrap: bool; - includeAfter: bool): Cursor = - discard -proc editor_text_doMoveCursorColumn_Cursor_TextDocumentEditor_Cursor_int_bool_bool_impl*( - self: TextDocumentEditor; cursor: Cursor; offset: int; wrap: bool = true; - includeAfter: bool = true): Cursor = - discard -proc editor_text_includeSelectionEnd_Selection_TextDocumentEditor_Selection_bool_impl*( - self: TextDocumentEditor; res: Selection; includeAfter: bool = true): Selection = - discard -proc editor_text_findSurroundStart_Option_Cursor_TextDocumentEditor_Cursor_int_char_char_int_impl*( - editor: TextDocumentEditor; cursor: Cursor; count: int; c0: char; c1: char; - depth: int = 1): Option[Cursor] = - discard -proc editor_text_findSurroundEnd_Option_Cursor_TextDocumentEditor_Cursor_int_char_char_int_impl*( - editor: TextDocumentEditor; cursor: Cursor; count: int; c0: char; c1: char; - depth: int = 1): Option[Cursor] = - discard -proc editor_text_setMode_void_TextDocumentEditor_string_impl*( - self: TextDocumentEditor; mode: string) = - discard -proc editor_text_mode_string_TextDocumentEditor_impl*(self: TextDocumentEditor): string = - discard -proc editor_text_getContextWithMode_string_TextDocumentEditor_string_impl*( - self: TextDocumentEditor; context: string): string = - discard -proc editor_text_updateTargetColumn_void_TextDocumentEditor_SelectionCursor_impl*( - self: TextDocumentEditor; cursor: SelectionCursor = Last) = - discard -proc editor_text_invertSelection_void_TextDocumentEditor_impl*( - self: TextDocumentEditor) = - discard -proc editor_text_getRevision_int_TextDocumentEditor_impl*( - self: TextDocumentEditor): int = - discard -proc editor_text_getUsage_string_TextDocumentEditor_impl*( - self: TextDocumentEditor): string = - discard -proc editor_text_getText_string_TextDocumentEditor_Selection_bool_impl*( - self: TextDocumentEditor; selection: Selection; inclusiveEnd: bool = false): string = - discard -proc editor_text_insert_seq_Selection_TextDocumentEditor_seq_Selection_string_bool_bool_impl*( - self: TextDocumentEditor; selections: seq[Selection]; text: string; - notify: bool = true; record: bool = true): seq[Selection] = - discard -proc editor_text_insertMulti_seq_Selection_TextDocumentEditor_seq_Selection_seq_string_bool_bool_impl*( - self: TextDocumentEditor; selections: seq[Selection]; texts: seq[string]; - notify: bool = true; record: bool = true): seq[Selection] = - discard -proc editor_text_delete_seq_Selection_TextDocumentEditor_seq_Selection_bool_bool_bool_impl*( - self: TextDocumentEditor; selections: seq[Selection]; notify: bool = true; - record: bool = true; inclusiveEnd: bool = false): seq[Selection] = - discard -proc editor_text_edit_seq_Selection_TextDocumentEditor_seq_Selection_seq_string_bool_bool_bool_impl*( - self: TextDocumentEditor; selections: seq[Selection]; texts: seq[string]; - notify: bool = true; record: bool = true; inclusiveEnd: bool = false): seq[ - Selection] = - discard -proc editor_text_deleteLines_void_TextDocumentEditor_Slice_int_Selections_impl*( - self: TextDocumentEditor; slice: Slice[int]; oldSelections: Selections) = - discard -proc editor_text_selectPrev_void_TextDocumentEditor_impl*( - self: TextDocumentEditor) = - discard -proc editor_text_selectNext_void_TextDocumentEditor_impl*( - self: TextDocumentEditor) = - discard -proc editor_text_selectInside_void_TextDocumentEditor_Cursor_impl*( - self: TextDocumentEditor; cursor: Cursor) = - discard -proc editor_text_selectInsideCurrent_void_TextDocumentEditor_impl*( - self: TextDocumentEditor) = - discard -proc editor_text_selectLine_void_TextDocumentEditor_int_impl*( - self: TextDocumentEditor; line: int) = - discard -proc editor_text_selectLineCurrent_void_TextDocumentEditor_impl*( - self: TextDocumentEditor) = - discard -proc editor_text_getParentNodeSelection_Selection_TextDocumentEditor_Selection_bool_impl*( - self: TextDocumentEditor; selection: Selection; includeAfter: bool = true): Selection = - discard -proc editor_text_getNextNamedSiblingNodeSelection_Option_Selection_TextDocumentEditor_Selection_bool_impl*( - self: TextDocumentEditor; selection: Selection; includeAfter: bool = true): Option[ - Selection] = - discard -proc editor_text_getNextSiblingNodeSelection_Option_Selection_TextDocumentEditor_Selection_bool_impl*( - self: TextDocumentEditor; selection: Selection; includeAfter: bool = true): Option[ - Selection] = - discard -proc editor_text_getParentNodeSelections_Selections_TextDocumentEditor_Selections_bool_impl*( - self: TextDocumentEditor; selections: Selections; includeAfter: bool = true): Selections = - discard -proc editor_text_selectParentTs_void_TextDocumentEditor_Selection_bool_impl*( - self: TextDocumentEditor; selection: Selection; includeAfter: bool = true) = - discard -proc editor_text_printTreesitterTree_void_TextDocumentEditor_impl*( - self: TextDocumentEditor) = - discard -proc editor_text_printTreesitterTreeUnderCursor_void_TextDocumentEditor_impl*( - self: TextDocumentEditor) = - discard -proc editor_text_selectParentCurrentTs_void_TextDocumentEditor_bool_impl*( - self: TextDocumentEditor; includeAfter: bool = true) = - discard -proc editor_text_getNextNodeWithSameType_Option_Selection_TextDocumentEditor_Selection_int_bool_bool_bool_bool_impl*( - self: TextDocumentEditor; selection: Selection; offset: int = 0; - includeAfter: bool = true; wrap: bool = true; stepIn: bool = true; - stepOut: bool = true): Option[Selection] = - discard -proc editor_text_shouldShowCompletionsAt_bool_TextDocumentEditor_Cursor_impl*( - self: TextDocumentEditor; cursor: Cursor): bool = - discard -proc editor_text_autoShowCompletions_void_TextDocumentEditor_impl*( - self: TextDocumentEditor) = - discard -proc editor_text_insertText_void_TextDocumentEditor_string_bool_impl*( - self: TextDocumentEditor; text: string; autoIndent: bool = true) = - discard -proc editor_text_indent_void_TextDocumentEditor_impl*(self: TextDocumentEditor) = - discard -proc editor_text_unindent_void_TextDocumentEditor_impl*(self: TextDocumentEditor) = - discard -proc editor_text_insertIndent_void_TextDocumentEditor_impl*( - self: TextDocumentEditor) = - discard -proc editor_text_undo_void_TextDocumentEditor_string_impl*( - self: TextDocumentEditor; checkpoint: string = "word") = - discard -proc editor_text_redo_void_TextDocumentEditor_string_impl*( - self: TextDocumentEditor; checkpoint: string = "word") = - discard -proc editor_text_addNextCheckpoint_void_TextDocumentEditor_string_impl*( - self: TextDocumentEditor; checkpoint: string) = - discard -proc editor_text_printUndoHistory_void_TextDocumentEditor_int_impl*( - self: TextDocumentEditor; max: int = 50) = - discard -proc editor_text_copy_void_TextDocumentEditor_string_bool_impl*( - self: TextDocumentEditor; register: string = ""; inclusiveEnd: bool = false) = - discard -proc editor_text_paste_void_TextDocumentEditor_string_bool_impl*( - self: TextDocumentEditor; register: string = ""; inclusiveEnd: bool = false) = - discard -proc editor_text_scrollText_void_TextDocumentEditor_float32_impl*( - self: TextDocumentEditor; amount: float32) = - discard -proc editor_text_scrollLines_void_TextDocumentEditor_int_impl*( - self: TextDocumentEditor; amount: int) = - discard -proc editor_text_duplicateLastSelection_void_TextDocumentEditor_impl*( - self: TextDocumentEditor) = - discard -proc editor_text_addCursorBelow_void_TextDocumentEditor_impl*( - self: TextDocumentEditor) = - discard -proc editor_text_addCursorAbove_void_TextDocumentEditor_impl*( - self: TextDocumentEditor) = - discard -proc editor_text_getPrevFindResult_Selection_TextDocumentEditor_Cursor_int_bool_bool_impl*( - self: TextDocumentEditor; cursor: Cursor; offset: int = 0; - includeAfter: bool = true; wrap: bool = true): Selection = - discard -proc editor_text_getNextFindResult_Selection_TextDocumentEditor_Cursor_int_bool_bool_impl*( - self: TextDocumentEditor; cursor: Cursor; offset: int = 0; - includeAfter: bool = true; wrap: bool = true): Selection = - discard -proc editor_text_getPrevDiagnostic_Selection_TextDocumentEditor_Cursor_int_int_bool_bool_impl*( - self: TextDocumentEditor; cursor: Cursor; severity: int = 0; - offset: int = 0; includeAfter: bool = true; wrap: bool = true): Selection = - discard -proc editor_text_getNextDiagnostic_Selection_TextDocumentEditor_Cursor_int_int_bool_bool_impl*( - self: TextDocumentEditor; cursor: Cursor; severity: int = 0; - offset: int = 0; includeAfter: bool = true; wrap: bool = true): Selection = - discard -proc editor_text_closeDiff_void_TextDocumentEditor_impl*(self: TextDocumentEditor) = - discard -proc editor_text_getPrevChange_Selection_TextDocumentEditor_Cursor_impl*( - self: TextDocumentEditor; cursor: Cursor): Selection = - discard -proc editor_text_getNextChange_Selection_TextDocumentEditor_Cursor_impl*( - self: TextDocumentEditor; cursor: Cursor): Selection = - discard -proc editor_text_updateDiff_void_TextDocumentEditor_bool_impl*( - self: TextDocumentEditor; gotoFirstDiff: bool = false) = - discard -proc editor_text_checkoutFile_void_TextDocumentEditor_impl*( - self: TextDocumentEditor) = - discard -proc editor_text_addNextFindResultToSelection_void_TextDocumentEditor_bool_bool_impl*( - self: TextDocumentEditor; includeAfter: bool = true; wrap: bool = true) = - discard -proc editor_text_addPrevFindResultToSelection_void_TextDocumentEditor_bool_bool_impl*( - self: TextDocumentEditor; includeAfter: bool = true; wrap: bool = true) = - discard -proc editor_text_setAllFindResultToSelection_void_TextDocumentEditor_impl*( - self: TextDocumentEditor) = - discard -proc editor_text_clearSelections_void_TextDocumentEditor_impl*( - self: TextDocumentEditor) = - discard -proc editor_text_moveCursorColumn_void_TextDocumentEditor_int_SelectionCursor_bool_bool_bool_impl*( - self: TextDocumentEditor; distance: int; - cursor: SelectionCursor = SelectionCursor.Config; all: bool = true; - wrap: bool = true; includeAfter: bool = true) = - discard -proc editor_text_moveCursorLine_void_TextDocumentEditor_int_SelectionCursor_bool_bool_bool_impl*( - self: TextDocumentEditor; distance: int; - cursor: SelectionCursor = SelectionCursor.Config; all: bool = true; - wrap: bool = true; includeAfter: bool = true) = - discard -proc editor_text_moveCursorVisualLine_void_TextDocumentEditor_int_SelectionCursor_bool_bool_bool_impl*( - self: TextDocumentEditor; distance: int; - cursor: SelectionCursor = SelectionCursor.Config; all: bool = true; - wrap: bool = true; includeAfter: bool = true) = - discard -proc editor_text_moveCursorHome_void_TextDocumentEditor_SelectionCursor_bool_impl*( - self: TextDocumentEditor; cursor: SelectionCursor = SelectionCursor.Config; - all: bool = true) = - discard -proc editor_text_moveCursorEnd_void_TextDocumentEditor_SelectionCursor_bool_bool_impl*( - self: TextDocumentEditor; cursor: SelectionCursor = SelectionCursor.Config; - all: bool = true; includeAfter: bool = true) = - discard -proc editor_text_moveCursorVisualHome_void_TextDocumentEditor_SelectionCursor_bool_impl*( - self: TextDocumentEditor; cursor: SelectionCursor = SelectionCursor.Config; - all: bool = true) = - discard -proc editor_text_moveCursorVisualEnd_void_TextDocumentEditor_SelectionCursor_bool_bool_impl*( - self: TextDocumentEditor; cursor: SelectionCursor = SelectionCursor.Config; - all: bool = true; includeAfter: bool = true) = - discard -proc editor_text_moveCursorTo_void_TextDocumentEditor_string_SelectionCursor_bool_impl*( - self: TextDocumentEditor; str: string; - cursor: SelectionCursor = SelectionCursor.Config; all: bool = true) = - discard -proc editor_text_moveCursorBefore_void_TextDocumentEditor_string_SelectionCursor_bool_impl*( - self: TextDocumentEditor; str: string; - cursor: SelectionCursor = SelectionCursor.Config; all: bool = true) = - discard -proc editor_text_moveCursorNextFindResult_void_TextDocumentEditor_SelectionCursor_bool_bool_impl*( - self: TextDocumentEditor; cursor: SelectionCursor = SelectionCursor.Config; - all: bool = true; wrap: bool = true) = - discard -proc editor_text_moveCursorPrevFindResult_void_TextDocumentEditor_SelectionCursor_bool_bool_impl*( - self: TextDocumentEditor; cursor: SelectionCursor = SelectionCursor.Config; - all: bool = true; wrap: bool = true) = - discard -proc editor_text_moveCursorLineCenter_void_TextDocumentEditor_SelectionCursor_bool_impl*( - self: TextDocumentEditor; cursor: SelectionCursor = SelectionCursor.Config; - all: bool = true) = - discard -proc editor_text_moveCursorCenter_void_TextDocumentEditor_SelectionCursor_bool_impl*( - self: TextDocumentEditor; cursor: SelectionCursor = SelectionCursor.Config; - all: bool = true) = - discard -proc editor_text_scrollToCursor_void_TextDocumentEditor_SelectionCursor_impl*( - self: TextDocumentEditor; cursor: SelectionCursor = SelectionCursor.Config) = - discard -proc editor_text_setNextScrollBehaviour_void_TextDocumentEditor_ScrollBehaviour_impl*( - self: TextDocumentEditor; scrollBehaviour: ScrollBehaviour) = - discard -proc editor_text_setCursorScrollOffset_void_TextDocumentEditor_float_SelectionCursor_impl*( - self: TextDocumentEditor; offset: float; - cursor: SelectionCursor = SelectionCursor.Config) = - discard -proc editor_text_getContentBounds_Vec2_TextDocumentEditor_impl*( - self: TextDocumentEditor): Vec2 = - discard -proc editor_text_centerCursor_void_TextDocumentEditor_SelectionCursor_impl*( - self: TextDocumentEditor; cursor: SelectionCursor = SelectionCursor.Config) = - discard -proc editor_text_reloadTreesitter_void_TextDocumentEditor_impl*( - self: TextDocumentEditor) = - discard -proc editor_text_deleteLeft_void_TextDocumentEditor_impl*( - self: TextDocumentEditor) = - discard -proc editor_text_deleteRight_void_TextDocumentEditor_bool_impl*( - self: TextDocumentEditor; includeAfter: bool = true) = - discard -proc editor_text_getCommandCount_int_TextDocumentEditor_impl*( - self: TextDocumentEditor): int = - discard -proc editor_text_setCommandCount_void_TextDocumentEditor_int_impl*( - self: TextDocumentEditor; count: int) = - discard -proc editor_text_setCommandCountRestore_void_TextDocumentEditor_int_impl*( - self: TextDocumentEditor; count: int) = - discard -proc editor_text_updateCommandCount_void_TextDocumentEditor_int_impl*( - self: TextDocumentEditor; digit: int) = - discard -proc editor_text_setFlag_void_TextDocumentEditor_string_bool_impl*( - self: TextDocumentEditor; name: string; value: bool) = - discard -proc editor_text_getFlag_bool_TextDocumentEditor_string_impl*( - self: TextDocumentEditor; name: string): bool = - discard -proc editor_text_runAction_Option_JsonNode_TextDocumentEditor_string_JsonNode_impl*( - self: TextDocumentEditor; action: string; args: JsonNode): Option[JsonNode] = - discard -proc editor_text_findWordBoundary_Selection_TextDocumentEditor_Cursor_impl*( - self: TextDocumentEditor; cursor: Cursor): Selection = - discard -proc editor_text_getSelectionInPair_Selection_TextDocumentEditor_Cursor_char_impl*( - self: TextDocumentEditor; cursor: Cursor; delimiter: char): Selection = - discard -proc editor_text_getSelectionInPairNested_Selection_TextDocumentEditor_Cursor_char_char_impl*( - self: TextDocumentEditor; cursor: Cursor; open: char; close: char): Selection = - discard -proc editor_text_extendSelectionWithMove_Selection_TextDocumentEditor_Selection_string_int_impl*( - self: TextDocumentEditor; selection: Selection; move: string; count: int = 0): Selection = - discard -proc editor_text_getSelectionForMove_Selection_TextDocumentEditor_Cursor_string_int_impl*( - self: TextDocumentEditor; cursor: Cursor; move: string; count: int = 0): Selection = - discard -proc editor_text_applyMove_void_TextDocumentEditor_JsonNode_impl*( - self: TextDocumentEditor; args: JsonNode) = - discard -proc editor_text_deleteMove_void_TextDocumentEditor_string_bool_SelectionCursor_bool_impl*( - self: TextDocumentEditor; move: string; inside: bool = false; - which: SelectionCursor = SelectionCursor.Config; all: bool = true) = - discard -proc editor_text_selectMove_void_TextDocumentEditor_string_bool_SelectionCursor_bool_impl*( - self: TextDocumentEditor; move: string; inside: bool = false; - which: SelectionCursor = SelectionCursor.Config; all: bool = true) = - discard -proc editor_text_extendSelectMove_void_TextDocumentEditor_string_bool_SelectionCursor_bool_impl*( - self: TextDocumentEditor; move: string; inside: bool = false; - which: SelectionCursor = SelectionCursor.Config; all: bool = true) = - discard -proc editor_text_copyMove_void_TextDocumentEditor_string_bool_SelectionCursor_bool_impl*( - self: TextDocumentEditor; move: string; inside: bool = false; - which: SelectionCursor = SelectionCursor.Config; all: bool = true) = - discard -proc editor_text_changeMove_void_TextDocumentEditor_string_bool_SelectionCursor_bool_impl*( - self: TextDocumentEditor; move: string; inside: bool = false; - which: SelectionCursor = SelectionCursor.Config; all: bool = true) = - discard -proc editor_text_moveLast_void_TextDocumentEditor_string_SelectionCursor_bool_int_impl*( - self: TextDocumentEditor; move: string; - which: SelectionCursor = SelectionCursor.Config; all: bool = true; - count: int = 0) = - discard -proc editor_text_moveFirst_void_TextDocumentEditor_string_SelectionCursor_bool_int_impl*( - self: TextDocumentEditor; move: string; - which: SelectionCursor = SelectionCursor.Config; all: bool = true; - count: int = 0) = - discard -proc editor_text_setSearchQuery_void_TextDocumentEditor_string_bool_string_string_impl*( - self: TextDocumentEditor; query: string; escapeRegex: bool = false; - prefix: string = ""; suffix: string = "") = - discard -proc editor_text_setSearchQueryFromMove_Selection_TextDocumentEditor_string_int_string_string_impl*( - self: TextDocumentEditor; move: string; count: int = 0; prefix: string = ""; - suffix: string = ""): Selection = - discard -proc editor_text_toggleLineComment_void_TextDocumentEditor_impl*( - self: TextDocumentEditor) = - discard -proc editor_text_gotoDefinition_void_TextDocumentEditor_impl*( - self: TextDocumentEditor) = - discard -proc editor_text_gotoDeclaration_void_TextDocumentEditor_impl*( - self: TextDocumentEditor) = - discard -proc editor_text_gotoTypeDefinition_void_TextDocumentEditor_impl*( - self: TextDocumentEditor) = - discard -proc editor_text_gotoImplementation_void_TextDocumentEditor_impl*( - self: TextDocumentEditor) = - discard -proc editor_text_gotoReferences_void_TextDocumentEditor_impl*( - self: TextDocumentEditor) = - discard -proc editor_text_switchSourceHeader_void_TextDocumentEditor_impl*( - self: TextDocumentEditor) = - discard -proc editor_text_getCompletions_void_TextDocumentEditor_impl*( - self: TextDocumentEditor) = - discard -proc editor_text_gotoSymbol_void_TextDocumentEditor_impl*( - self: TextDocumentEditor) = - discard -proc editor_text_fuzzySearchLines_void_TextDocumentEditor_float_bool_impl*( - self: TextDocumentEditor; minScore: float = 0.2; sort: bool = true) = - discard -proc editor_text_gotoWorkspaceSymbol_void_TextDocumentEditor_string_impl*( - self: TextDocumentEditor; query: string = "") = - discard -proc editor_text_hideCompletions_void_TextDocumentEditor_impl*( - self: TextDocumentEditor) = - discard -proc editor_text_selectPrevCompletion_void_TextDocumentEditor_impl*( - self: TextDocumentEditor) = - discard -proc editor_text_selectNextCompletion_void_TextDocumentEditor_impl*( - self: TextDocumentEditor) = - discard -proc editor_text_hasTabStops_bool_TextDocumentEditor_impl*( - self: TextDocumentEditor): bool = - discard -proc editor_text_clearTabStops_void_TextDocumentEditor_impl*( - self: TextDocumentEditor) = - discard -proc editor_text_selectNextTabStop_void_TextDocumentEditor_impl*( - self: TextDocumentEditor) = - discard -proc editor_text_selectPrevTabStop_void_TextDocumentEditor_impl*( - self: TextDocumentEditor) = - discard -proc editor_text_applyCompletion_void_TextDocumentEditor_JsonNode_impl*( - self: TextDocumentEditor; completion: JsonNode) = - discard -proc editor_text_applySelectedCompletion_void_TextDocumentEditor_impl*( - self: TextDocumentEditor) = - discard -proc editor_text_showHoverFor_void_TextDocumentEditor_Cursor_impl*( - self: TextDocumentEditor; cursor: Cursor) = - discard -proc editor_text_showHoverForCurrent_void_TextDocumentEditor_impl*( - self: TextDocumentEditor) = - discard -proc editor_text_hideHover_void_TextDocumentEditor_impl*(self: TextDocumentEditor) = - discard -proc editor_text_cancelDelayedHideHover_void_TextDocumentEditor_impl*( - self: TextDocumentEditor) = - discard -proc editor_text_hideHoverDelayed_void_TextDocumentEditor_impl*( - self: TextDocumentEditor) = - discard -proc editor_text_clearDiagnostics_void_TextDocumentEditor_impl*( - self: TextDocumentEditor) = - discard -proc editor_text_updateDiagnosticsForCurrent_void_TextDocumentEditor_impl*( - self: TextDocumentEditor) = - discard -proc editor_text_showDiagnosticsForCurrent_void_TextDocumentEditor_impl*( - self: TextDocumentEditor) = - discard -proc editor_text_setReadOnly_void_TextDocumentEditor_bool_impl*( - self: TextDocumentEditor; readOnly: bool) = - discard -proc editor_text_setFileReadOnly_void_TextDocumentEditor_bool_impl*( - self: TextDocumentEditor; readOnly: bool) = - discard -proc editor_text_isRunningSavedCommands_bool_TextDocumentEditor_impl*( - self: TextDocumentEditor): bool = - discard -proc editor_text_runSavedCommands_void_TextDocumentEditor_impl*( - self: TextDocumentEditor) = - discard -proc editor_text_clearCurrentCommandHistory_void_TextDocumentEditor_bool_impl*( - self: TextDocumentEditor; retainLast: bool = false) = - discard -proc editor_text_saveCurrentCommandHistory_void_TextDocumentEditor_impl*( - self: TextDocumentEditor) = - discard -proc editor_text_getSelection_Selection_TextDocumentEditor_impl*( - self: TextDocumentEditor): Selection = - discard -proc editor_text_setSelection_void_TextDocumentEditor_Selection_impl*( - self: TextDocumentEditor; selection: Selection) = - discard -proc editor_text_setTargetSelection_void_TextDocumentEditor_Selection_impl*( - self: TextDocumentEditor; selection: Selection) = - discard -proc editor_text_enterChooseCursorMode_void_TextDocumentEditor_string_impl*( - self: TextDocumentEditor; action: string) = - discard -proc editor_text_recordCurrentCommand_void_TextDocumentEditor_impl*( - self: TextDocumentEditor) = - discard -proc editor_text_runSingleClickCommand_void_TextDocumentEditor_impl*( - self: TextDocumentEditor) = - discard -proc editor_text_runDoubleClickCommand_void_TextDocumentEditor_impl*( - self: TextDocumentEditor) = - discard -proc editor_text_runTripleClickCommand_void_TextDocumentEditor_impl*( - self: TextDocumentEditor) = - discard -proc editor_text_runDragCommand_void_TextDocumentEditor_impl*( - self: TextDocumentEditor) = - discard -proc debugger_prevDebuggerView_void_Debugger_impl*() = - discard -proc debugger_nextDebuggerView_void_Debugger_impl*() = - discard -proc debugger_setDebuggerView_void_Debugger_string_impl*(view: string) = - discard -proc debugger_selectFirstVariable_void_Debugger_impl*() = - discard -proc debugger_selectLastVariable_void_Debugger_impl*() = - discard -proc debugger_prevThread_void_Debugger_impl*() = - discard -proc debugger_nextThread_void_Debugger_impl*() = - discard -proc debugger_prevStackFrame_void_Debugger_impl*() = - discard -proc debugger_nextStackFrame_void_Debugger_impl*() = - discard -proc debugger_openFileForCurrentFrame_void_Debugger_impl*() = - discard -proc debugger_prevVariable_void_Debugger_impl*() = - discard -proc debugger_nextVariable_void_Debugger_impl*() = - discard -proc debugger_expandVariable_void_Debugger_impl*() = - discard -proc debugger_collapseVariable_void_Debugger_impl*() = - discard -proc debugger_stopDebugSession_void_Debugger_impl*() = - discard -proc debugger_stopDebugSessionDelayed_void_Debugger_impl*() = - discard -proc debugger_runConfiguration_void_Debugger_string_impl*(name: string) = - discard -proc debugger_chooseRunConfiguration_void_Debugger_impl*() = - discard -proc debugger_runLastConfiguration_void_Debugger_impl*() = - discard -proc debugger_addBreakpoint_void_Debugger_EditorId_int_impl*(editorId: EditorId; - line: int) = - discard -proc debugger_removeBreakpoint_void_Debugger_string_int_impl*(path: string; - line: int) = - discard -proc debugger_toggleBreakpointEnabled_void_Debugger_string_int_impl*( - path: string; line: int) = - discard -proc debugger_toggleAllBreakpointsEnabled_void_Debugger_impl*() = - discard -proc debugger_toggleBreakpointsEnabled_void_Debugger_impl*() = - discard -proc debugger_editBreakpoints_void_Debugger_impl*() = - discard -proc debugger_continueExecution_void_Debugger_impl*() = - discard -proc debugger_stepOver_void_Debugger_impl*() = - discard -proc debugger_stepIn_void_Debugger_impl*() = - discard -proc debugger_stepOut_void_Debugger_impl*() = - discard -proc lsp_lspLogVerbose_void_bool_impl*(val: bool) = - discard -proc lsp_lspToggleLogServerDebug_void_impl*() = - discard -proc lsp_lspLogServerDebug_void_bool_impl*(val: bool) = - discard -proc popup_selector_setPreviewVisible_void_SelectorPopup_bool_impl*( - self: SelectorPopup; visible: bool) = - discard -proc popup_selector_togglePreview_void_SelectorPopup_impl*(self: SelectorPopup) = - discard -proc popup_selector_getSelectedItemJson_JsonNode_SelectorPopup_impl*( - self: SelectorPopup): JsonNode = - discard -proc popup_selector_accept_void_SelectorPopup_impl*(self: SelectorPopup) = - discard -proc popup_selector_cancel_void_SelectorPopup_impl*(self: SelectorPopup) = - discard -proc popup_selector_sort_void_SelectorPopup_ToggleBool_impl*(self: SelectorPopup; - sort: ToggleBool) = - discard -proc popup_selector_setMinScore_void_SelectorPopup_float_bool_impl*( - self: SelectorPopup; value: float; add: bool = false) = - discard -proc popup_selector_prev_void_SelectorPopup_int_impl*(self: SelectorPopup; - count: int = 1) = - discard -proc popup_selector_next_void_SelectorPopup_int_impl*(self: SelectorPopup; - count: int = 1) = - discard -proc popup_selector_toggleFocusPreview_void_SelectorPopup_impl*( - self: SelectorPopup) = - discard -proc popup_selector_setFocusPreview_void_SelectorPopup_bool_impl*( - self: SelectorPopup; focus: bool) = - discard -proc editor_reapplyConfigKeybindings_void_App_bool_bool_bool_impl*( - app: bool = false; home: bool = false; workspace: bool = false) = - discard -proc editor_splitView_void_App_impl*() = - discard -proc editor_runExternalCommand_void_App_string_seq_string_string_impl*( - command: string; args: seq[string] = @[]; workingDir: string = "") = - discard -proc editor_disableLogFrameTime_void_App_bool_impl*(disable: bool) = - discard -proc editor_enableDebugPrintAsyncAwaitStackTrace_void_App_bool_impl*(enable: bool) = - discard -proc editor_showDebuggerView_void_App_impl*() = - discard -proc editor_setLocationListFromCurrentPopup_void_App_impl*() = - discard -proc editor_getBackend_Backend_App_impl*(): Backend = - discard -proc editor_getHostOs_string_App_impl*(): string = - discard -proc editor_loadApplicationFile_Option_string_App_string_impl*(path: string): Option[ - string] = - discard -proc editor_toggleShowDrawnNodes_void_App_impl*() = - discard -proc editor_setMaxViews_void_App_int_bool_impl*(maxViews: int; - openExisting: bool = false) = - discard -proc editor_saveAppState_void_App_impl*() = - discard -proc editor_requestRender_void_App_bool_impl*(redrawEverything: bool = false) = - discard -proc editor_setHandleInputs_void_App_string_bool_impl*(context: string; - value: bool) = - discard -proc editor_setHandleActions_void_App_string_bool_impl*(context: string; - value: bool) = - discard -proc editor_setConsumeAllActions_void_App_string_bool_impl*(context: string; - value: bool) = - discard -proc editor_setConsumeAllInput_void_App_string_bool_impl*(context: string; - value: bool) = - discard -proc editor_clearWorkspaceCaches_void_App_impl*() = - discard -proc editor_openGithubWorkspace_void_App_string_string_string_impl*(user: string; - repository: string; branchOrHash: string) = - discard -proc editor_openRemoteServerWorkspace_void_App_string_impl*(url: string) = - discard -proc editor_callScriptAction_JsonNode_App_string_JsonNode_impl*(context: string; - args: JsonNode): JsonNode = - discard -proc editor_addScriptAction_void_App_string_string_seq_tuple_name_string_typ_string_string_bool_string_impl*( - name: string; docs: string = ""; - params: seq[tuple[name: string, typ: string]] = @[]; - returnType: string = ""; active: bool = false; context: string = "script") = - discard -proc editor_openLocalWorkspace_void_App_string_impl*(path: string) = - discard -proc editor_getFlag_bool_App_string_bool_impl*(flag: string; - default: bool = false): bool = - discard -proc editor_setFlag_void_App_string_bool_impl*(flag: string; value: bool) = - discard -proc editor_toggleFlag_void_App_string_impl*(flag: string) = - discard -proc editor_setOption_void_App_string_JsonNode_bool_impl*(option: string; - value: JsonNode; override: bool = true) = - discard -proc editor_quit_void_App_impl*() = - discard -proc editor_quitImmediately_void_App_int_impl*(exitCode: int = 0) = - discard -proc editor_help_void_App_string_impl*(about: string = "") = - discard -proc editor_loadWorkspaceFile_void_App_string_string_impl*(path: string; - callback: string) = - discard -proc editor_writeWorkspaceFile_void_App_string_string_impl*(path: string; - content: string) = - discard -proc editor_changeFontSize_void_App_float32_impl*(amount: float32) = - discard -proc editor_changeLineDistance_void_App_float32_impl*(amount: float32) = - discard -proc editor_platformTotalLineHeight_float32_App_impl*(): float32 = - discard -proc editor_platformLineHeight_float32_App_impl*(): float32 = - discard -proc editor_platformLineDistance_float32_App_impl*(): float32 = - discard -proc editor_changeLayoutProp_void_App_string_float32_impl*(prop: string; - change: float32) = - discard -proc editor_toggleStatusBarLocation_void_App_impl*() = - discard -proc editor_logs_void_App_bool_impl*(scrollToBottom: bool = false) = - discard -proc editor_toggleConsoleLogger_void_App_impl*() = - discard -proc editor_showEditor_void_App_EditorId_Option_int_impl*(editorId: EditorId; - viewIndex: Option[int] = int.none) = - discard -proc editor_getVisibleEditors_seq_EditorId_App_impl*(): seq[EditorId] = - discard -proc editor_getHiddenEditors_seq_EditorId_App_impl*(): seq[EditorId] = - discard -proc editor_getExistingEditor_Option_EditorId_App_string_impl*(path: string): Option[ - EditorId] = - discard -proc editor_getOrOpenEditor_Option_EditorId_App_string_impl*(path: string): Option[ - EditorId] = - discard -proc editor_closeView_void_App_int_bool_bool_impl*(index: int; - keepHidden: bool = true; restoreHidden: bool = true) = - discard -proc editor_closeCurrentView_void_App_bool_bool_impl*(keepHidden: bool = true; - restoreHidden: bool = true) = - discard -proc editor_closeOtherViews_void_App_bool_impl*(keepHidden: bool = true) = - discard -proc editor_moveCurrentViewToTop_void_App_impl*() = - discard -proc editor_nextView_void_App_impl*() = - discard -proc editor_prevView_void_App_impl*() = - discard -proc editor_toggleMaximizeView_void_App_impl*() = - discard -proc editor_moveCurrentViewPrev_void_App_impl*() = - discard -proc editor_moveCurrentViewNext_void_App_impl*() = - discard -proc editor_setLayout_void_App_string_impl*(layout: string) = - discard -proc editor_commandLine_void_App_string_impl*(initialValue: string = "") = - discard -proc editor_exitCommandLine_void_App_impl*() = - discard -proc editor_selectPreviousCommandInHistory_void_App_impl*() = - discard -proc editor_selectNextCommandInHistory_void_App_impl*() = - discard -proc editor_executeCommandLine_bool_App_impl*(): bool = - discard -proc editor_writeFile_void_App_string_bool_impl*(path: string = ""; - appFile: bool = false) = - discard -proc editor_loadFile_void_App_string_impl*(path: string = "") = - discard -proc editor_removeFromLocalStorage_void_App_impl*() = - discard -proc editor_loadTheme_void_App_string_impl*(name: string) = - discard -proc editor_chooseTheme_void_App_impl*() = - discard -proc editor_createFile_void_App_string_impl*(path: string) = - discard -proc editor_mountVfs_void_App_string_string_JsonNode_impl*(parentPath: string; - prefix: string; config: JsonNode) = - discard -proc editor_browseKeybinds_void_App_bool_float_float_float_impl*( - preview: bool = true; scaleX: float = 0.9; scaleY: float = 0.8; - previewScale: float = 0.4) = - discard -proc editor_connectCollaborator_void_App_int_impl*(port: int = 6969) = - discard -proc editor_hostCollaborator_void_App_int_impl*(port: int = 6969) = - discard -proc editor_chooseFile_void_App_bool_float_float_float_impl*( - preview: bool = true; scaleX: float = 0.8; scaleY: float = 0.8; - previewScale: float = 0.5) = - discard -proc editor_openLastEditor_void_App_impl*() = - discard -proc editor_chooseOpen_void_App_bool_float_float_float_impl*( - preview: bool = true; scaleX: float = 0.8; scaleY: float = 0.8; - previewScale: float = 0.6) = - discard -proc editor_chooseOpenDocument_void_App_impl*() = - discard -proc editor_gotoNextLocation_void_App_impl*() = - discard -proc editor_gotoPrevLocation_void_App_impl*() = - discard -proc editor_chooseLocation_void_App_impl*() = - discard -proc editor_searchGlobalInteractive_void_App_impl*() = - discard -proc editor_searchGlobal_void_App_string_impl*(query: string) = - discard -proc editor_installTreesitterParser_void_App_string_string_impl*( - language: string; host: string = "github.com") = - discard -proc editor_chooseGitActiveFiles_void_App_bool_impl*(all: bool = false) = - discard -proc editor_exploreFiles_void_App_string_impl*(root: string = "") = - discard -proc editor_exploreUserConfigDir_void_App_impl*() = - discard -proc editor_exploreAppConfigDir_void_App_impl*() = - discard -proc editor_exploreHelp_void_App_impl*() = - discard -proc editor_exploreWorkspacePrimary_void_App_impl*() = - discard -proc editor_exploreCurrentFileDirectory_void_App_impl*() = - discard -proc editor_openPreviousEditor_void_App_impl*() = - discard -proc editor_openNextEditor_void_App_impl*() = - discard -proc editor_setGithubAccessToken_void_App_string_impl*(token: string) = - discard -proc editor_reloadConfig_void_App_bool_impl*(clearOptions: bool = false) = - discard -proc editor_reloadPlugin_void_App_impl*() = - discard -proc editor_reloadState_void_App_impl*() = - discard -proc editor_saveSession_void_App_string_impl*(sessionFile: string = "") = - discard -proc editor_logOptions_void_App_impl*() = - discard -proc editor_dumpKeymapGraphViz_void_App_string_impl*(context: string = "") = - discard -proc editor_clearCommands_void_App_string_impl*(context: string) = - discard -proc editor_getAllEditors_seq_EditorId_App_impl*(): seq[EditorId] = - discard -proc editor_setMode_void_App_string_impl*(mode: string) = - discard -proc editor_mode_string_App_impl*(): string = - discard -proc editor_getContextWithMode_string_App_string_impl*(context: string): string = - discard -proc editor_scriptRunAction_void_string_string_impl*(action: string; arg: string) = - discard -proc editor_scriptLog_void_string_impl*(message: string) = - discard -proc editor_changeAnimationSpeed_void_App_float_impl*(factor: float) = - discard -proc editor_setLeader_void_App_string_impl*(leader: string) = - discard -proc editor_setLeaders_void_App_seq_string_impl*(leaders: seq[string]) = - discard -proc editor_addLeader_void_App_string_impl*(leader: string) = - discard -proc editor_registerPluginSourceCode_void_App_string_string_impl*(path: string; - content: string) = - discard -proc editor_addCommandScript_void_App_string_string_string_string_string_string_tuple_filename_string_line_int_column_int_impl*( - context: string; subContext: string; keys: string; action: string; - arg: string = ""; description: string = ""; - source: tuple[filename: string, line: int, column: int] = ("", 0, 0)) = - discard -proc editor_removeCommand_void_App_string_string_impl*(context: string; - keys: string) = - discard -proc editor_getActivePopup_EditorId_impl*(): EditorId = - discard -proc editor_getActiveEditor_EditorId_impl*(): EditorId = - discard -proc editor_getActiveEditor2_EditorId_App_impl*(): EditorId = - discard -proc editor_logRootNode_void_App_impl*() = - discard -proc editor_sourceCurrentDocument_void_App_impl*() = - discard -proc editor_getEditorInView_EditorId_int_impl*(index: int): EditorId = - discard -proc editor_scriptIsSelectorPopup_bool_EditorId_impl*(editorId: EditorId): bool = - discard -proc editor_scriptIsTextEditor_bool_EditorId_impl*(editorId: EditorId): bool = - discard -proc editor_scriptIsAstEditor_bool_EditorId_impl*(editorId: EditorId): bool = - discard -proc editor_scriptIsModelEditor_bool_EditorId_impl*(editorId: EditorId): bool = - discard -proc editor_scriptRunActionFor_void_EditorId_string_string_impl*( - editorId: EditorId; action: string; arg: string) = - discard -proc editor_scriptInsertTextInto_void_EditorId_string_impl*(editorId: EditorId; - text: string) = - discard -proc editor_scriptTextEditorSelection_Selection_EditorId_impl*(editorId: EditorId): Selection = - discard -proc editor_scriptSetTextEditorSelection_void_EditorId_Selection_impl*( - editorId: EditorId; selection: Selection) = - discard -proc editor_scriptTextEditorSelections_seq_Selection_EditorId_impl*( - editorId: EditorId): seq[Selection] = - discard -proc editor_scriptSetTextEditorSelections_void_EditorId_seq_Selection_impl*( - editorId: EditorId; selections: seq[Selection]) = - discard -proc editor_scriptGetTextEditorLine_string_EditorId_int_impl*(editorId: EditorId; - line: int): string = - discard -proc editor_scriptGetTextEditorLineCount_int_EditorId_impl*(editorId: EditorId): int = - discard -proc editor_setSessionDataJson_void_App_string_JsonNode_bool_impl*(path: string; - value: JsonNode; override: bool = true) = - discard -proc editor_getSessionDataJson_JsonNode_App_string_JsonNode_impl*(path: string; - default: JsonNode): JsonNode = - discard -proc editor_scriptGetOptionJson_JsonNode_string_JsonNode_impl*(path: string; - default: JsonNode): JsonNode = - discard -proc editor_scriptGetOptionInt_int_string_int_impl*(path: string; default: int): int = - discard -proc editor_scriptGetOptionFloat_float_string_float_impl*(path: string; - default: float): float = - discard -proc editor_scriptGetOptionBool_bool_string_bool_impl*(path: string; - default: bool): bool = - discard -proc editor_scriptGetOptionString_string_string_string_impl*(path: string; - default: string): string = - discard -proc editor_scriptSetOptionInt_void_string_int_impl*(path: string; value: int) = - discard -proc editor_scriptSetOptionFloat_void_string_float_impl*(path: string; - value: float) = - discard -proc editor_scriptSetOptionBool_void_string_bool_impl*(path: string; value: bool) = - discard -proc editor_scriptSetOptionString_void_string_string_impl*(path: string; - value: string) = - discard -proc editor_scriptSetCallback_void_string_int_impl*(path: string; id: int) = - discard -proc editor_setRegisterText_void_App_string_string_impl*(text: string; - register: string = "") = - discard -proc editor_getRegisterText_string_App_string_impl*(register: string): string = - discard -proc editor_startRecordingKeys_void_App_string_impl*(register: string) = - discard -proc editor_stopRecordingKeys_void_App_string_impl*(register: string) = - discard -proc editor_startRecordingCommands_void_App_string_impl*(register: string) = - discard -proc editor_stopRecordingCommands_void_App_string_impl*(register: string) = - discard -proc editor_isReplayingCommands_bool_App_impl*(): bool = - discard -proc editor_isReplayingKeys_bool_App_impl*(): bool = - discard -proc editor_isRecordingCommands_bool_App_string_impl*(registry: string): bool = - discard -proc editor_replayCommands_void_App_string_impl*(register: string) = - discard -proc editor_replayKeys_void_App_string_impl*(register: string) = - discard -proc editor_inputKeys_void_App_string_impl*(input: string) = - discard -proc editor_collectGarbage_void_App_impl*() = - discard -proc editor_printStatistics_void_App_impl*() = - discard diff --git a/scripting/plugin_runtime.nim b/scripting/plugin_runtime.nim deleted file mode 100644 index f9167c3b4..000000000 --- a/scripting/plugin_runtime.nim +++ /dev/null @@ -1,438 +0,0 @@ -import std/[strformat, tables, macros, json, strutils, sugar, sequtils, genasts, options, compilesettings] -import misc/[event, util, myjsonutils, macro_utils, embed_source] -import plugin_api, script_expose - -export plugin_api, util, strformat, tables, json, strutils, sugar, sequtils, scripting_api, script_expose -export embed_source.embedSource, embed_source.currentSourceLocation - -embedSource() - -type AnyDocumentEditor = TextDocumentEditor | ModelDocumentEditor - -var voidCallbacks = initTable[int, proc(args: JsonNode): void]() -var boolCallbacks = initTable[int, proc(args: JsonNode): bool]() -var anyCallbacks = initTable[int, proc(args: JsonNode): JsonNode]() -var onEditorModeChanged* = initEvent[tuple[editor: EditorId, oldMode: string, newMode: string]]() -var callbackId = 0 - -proc emscripten_notify_memory_growth*(a: int32) {.exportc.} = discard -const env* = "wasm" - -proc info*(args: varargs[string, `$`]) = - var msgLen = 0 - for arg in args: - msgLen += arg.len - var result = newStringOfCap(msgLen + 12) - result.add "[" - result.add env - result.add "] " - - for arg in args: - result.add(arg) - scriptLog(result) - -template infof*(x: static string) = - scriptLog("[" & env & "] " & fmt(x)) - -proc addCallback*(action: proc(args: JsonNode): void): int = - result = callbackId - voidCallbacks[result] = action - callbackId += 1 - -proc addCallback*(action: proc(args: JsonNode): bool): int = - result = callbackId - boolCallbacks[result] = action - callbackId += 1 - -proc addCallback*(action: proc(args: JsonNode): JsonNode): int = - result = callbackId - anyCallbacks[result] = action - callbackId += 1 - -func toJsonString[T: string](value: T): string = escapeJson(value) -func toJsonString[T: char](value: T): string = escapeJson($value) -func toJsonString[T](value: T): string = $value - -proc removeCommand*(context: string, keys: string) = - removeCommand(context, keys) - -macro runAction*(action: string, args: varargs[untyped]): untyped = - var stmts = nnkStmtList.newTree() - let str = nskVar.genSym "str" - stmts.add quote do: - var `str` = "" - for arg in args: - stmts.add quote do: - `str`.add " " - `str`.add `arg`.toJsonString - - return quote do: - `stmts` - discard scriptRunAction(`action`, `str`) - -template isTextEditor*(editorId: EditorId, injected: untyped): bool = - (scriptIsTextEditor(editorId) and ((let injected {.inject.} = TextDocumentEditor(id: editorId); true))) - -template isModelEditor*(editorId: EditorId, injected: untyped): bool = - (scriptIsModelEditor(editorId) and ((let injected {.inject.} = ModelDocumentEditor(id: editorId); true))) - -template isSelectorPopup*(editorId: EditorId, injected: untyped): bool = - (scriptIsSelectorPopup(editorId) and ((let injected {.inject.} = SelectorPopup(id: editorId); true))) - -proc handleCallbackImpl*(id: int, args: JsonNode): bool = - # infof"handleCallbackImpl {id}, {args}" - if voidCallbacks.contains(id): - voidCallbacks[id](args) - return true - elif boolCallbacks.contains(id): - return boolCallbacks[id](args) - elif anyCallbacks.contains(id): - return anyCallbacks[id](args).isNotNil - return false - -proc handleAnyCallbackImpl*(id: int, args: JsonNode): JsonNode = - # infof"handleAnyCallbackImpl {id}, {args}" - if voidCallbacks.contains(id): - voidCallbacks[id](args) - return newJNull() - elif boolCallbacks.contains(id): - return newJBool(boolCallbacks[id](args)) - elif anyCallbacks.contains(id): - return anyCallbacks[id](args) - return nil - -proc handleScriptActionImpl*(name: string, args: JsonNode): JsonNode = - # infof"handleScriptActionImpl {name}, {args}" - if scriptActions.contains(name): - return scriptActions[name](args) - return nil - -proc runAction*(id: EditorId, action: string, arg: string = "") = - scriptRunActionFor(id, action, arg) - -proc runAction*(editor: TextDocumentEditor, action: string, arg: string = "") = - scriptRunActionFor(editor.id, action, arg) - -proc selection*(editor: TextDocumentEditor): Selection = - return editor.getSelection() - -proc selections*(editor: TextDocumentEditor): seq[Selection] = - return editor.getSelections() - -proc `selection=`*(editor: TextDocumentEditor, selection: Selection) = - editor.setSelection(selection) - -proc `selections=`*(editor: TextDocumentEditor, selections: seq[Selection]) = - editor.setSelections(selections) - -proc `targetSelection=`*(editor: TextDocumentEditor, selection: Selection) = - editor.setTargetSelection(selection) - -proc getOption*[T](path: string, default: T = T.default): T = - try: - let json: JsonNode = plugin_api.getOptionJson(path, newJNull()) - return json.jsonTo T - except: - return default - -proc setOption*[T](path: string, value: T) = - plugin_api.setOption(path, value.toJson) - -proc setConfig*[T](editor: TextDocumentEditor, path: string, value: T) = - plugin_api.setConfig(editor, path, value.toJson) - -proc getSessionData*[T](path: string, default: T = T.default): T = - return getSessionDataJson(path, default.toJson).jsonTo(T) - -proc setSessionData*[T](path: string, value: T) = - setSessionDataJson(path, value.toJson) - -proc bindArgs*(args: NimNode): tuple[stmts: NimNode, arg: NimNode] = - var stmts = nnkStmtList.newTree() - let str = nskVar.genSym "str" - stmts.addAst(str): - var str = "" - for arg in args: - if arg.kind == nnkExprEqExpr: - # todo: check name - stmts.addAst(str, arg = arg[1]): - str.add " " - str.add arg.toJsonString - else: - stmts.addAst(str, arg): - str.add " " - str.add arg.toJsonString - - return (stmts, str) - -var keysPrefix*: string = "" - -template withKeys*(keys: varargs[string], body: untyped): untyped = - for key in keys: - let oldValue = keysPrefix - keysPrefix = keysPrefix & key - defer: - keysPrefix = oldValue - body - -proc loadWorkspaceFile*(path: string, action: proc(content: Option[string]): void {.closure, gcsafe.}) = - let key = "$loadWorkspaceFile" & $callbackId - callbackId += 1 - scriptActions[key] = proc(args: JsonNode): JsonNode = - action(args.jsonTo(Option[string])) - scriptActions.del(key) - return newJNull() - addScriptAction(key, "", @[("path", "string"), ("callback", "proc(content: Option[string])")], "", false) - loadWorkspaceFile(path, key) - -proc runProcess*(process: string, args: seq[string], workingDir: Option[string] = string.none, eval: bool = false, callback: proc(output: string, err: string): void {.closure, gcsafe.} = nil) = - let key = "$runProcess" & $callbackId - callbackId += 1 - scriptActions[key] = proc(args: JsonNode): JsonNode = - let args = args.jsonTo(Option[tuple[output: string, err: string]]) - if callback != nil and args.isSome: - callback(args.get.output, args.get.err) - scriptActions.del(key) - return newJNull() - addScriptAction(key, "", @[("process", "string"), ("args", "seq[string]"), ("workingDir", "Option[string]"), ("callback", "proc(content: Option[string])")], "", false) - runProcess(process, args, key.some, workingDir, eval) - -macro addCommand*(context: string, keys: string, action: string, args: varargs[untyped]): untyped = - let (stmts, str) = bindArgs(args) - return genAst(stmts, context, keys, action, str): - stmts - addCommandScript(context, "", keysPrefix & keys, action, str, source = currentSourceLocation(-2)) - -proc addCommand*(context: string, keys: string, action: proc(): void, source = currentSourceLocation()) = - let key = "$" & context & keys - scriptActions[key] = proc(args: JsonNode): JsonNode = - action() - return newJNull() - - # addCommandScript(context, "", keysPrefix & keys, "lambda-action", key.toJsonString) - addCommandScript(context, "", keysPrefix & keys, key, "", source = source) - -proc addCommandDesc(context: string, keys: string, desc: string, action: proc(): void, source = currentSourceLocation()) = - let key = "$" & context & keys - scriptActions[key] = proc(args: JsonNode): JsonNode = - action() - return newJNull() - - addCommandScript(context, "", keysPrefix & keys, key, "", desc, source) - -proc addCommand*[T: proc](context: string, keys: string, args: string, action: T, source = currentSourceLocation()) = - let key = "$" & context & keys - scriptActions[key] = proc(args: JsonNode): JsonNode = - return callJson(action, args) - - addCommandScript(context, "", keysPrefix & keys, key, args, source = source) - -proc addCommandDesc[T: proc](context: string, keys: string, args: string, desc: string, action: T, source = currentSourceLocation()) = - let key = "$" & context & keys - scriptActions[key] = proc(args: JsonNode): JsonNode = - return callJson(action, args) - - addCommandScript(context, "", keysPrefix & keys, key, args, desc, source) - -template addCommandBlock*(context: string, keys: string, body: untyped): untyped = - block: - let p = proc() = - body - addCommand context, keys, p, currentSourceLocation(-2) - -template addCommandBlockDesc*(context: string, keys: string, desc: string, body: untyped): untyped = - block: - let p = proc() = - body - addCommandDesc context, keys, desc, p, currentSourceLocation(-2) - -func getContextWithMode*(context: string, mode: string): string = - if mode.contains("."): - return mode - if mode.len == 0 or mode[0] == '#': - return context & mode - else: - return context & "." & mode - -# App commands -template addEditorCommandBlock*(mode: string, keys: string, body: untyped): untyped = - addCommand getContextWithMode("editor", mode), keys, proc() = - body - -proc addEditorCommand*(mode: string, keys: string, action: proc(): void, source = currentSourceLocation()) = - block: - let p = proc() = - action() - addCommand getContextWithMode("editor", mode), keys, p, source = source - -macro addEditorCommand*(mode: string, keys: string, action: string, args: varargs[untyped]): untyped = - var stmts = nnkStmtList.newTree() - let str = nskVar.genSym "str" - stmts.add quote do: - var `str` = "" - for arg in args: - stmts.add quote do: - `str`.add " " - `str`.add `arg`.toJsonString - - return genAst(stmts, mode, keys, action, str): - stmts - addCommandScript(getContextWithMode("editor", mode), "", keysPrefix & keys, action, str, source = currentSourceLocation(-2)) - -# Text commands -template addTextCommandBlock*(mode: string, keys: string, body: untyped): untyped = - block: - let p = proc() = - try: - let editor {.inject, used.} = TextDocumentEditor(id: getActiveEditor()) - body - except: - let m {.inject.} = mode - let k {.inject.} = keys - infof"TextCommandBlock {m} {k}: {getCurrentExceptionMsg()}" - addCommand getContextWithMode("editor.text", mode), keys, p, currentSourceLocation(-2) - -template addTextCommandBlockDesc*(mode: string, keys: string, desc: string, body: untyped): untyped = - block: - let p = proc() = - try: - let editor {.inject, used.} = TextDocumentEditor(id: getActiveEditor()) - body - except: - let m {.inject.} = mode - let k {.inject.} = keys - infof"TextCommandBlock {m} {k}: {getCurrentExceptionMsg()}" - addCommandDesc getContextWithMode("editor.text", mode), keys, desc, p, currentSourceLocation(-2) - - -proc addTextCommand*(mode: string, keys: string, action: proc(editor: TextDocumentEditor): void, source = currentSourceLocation()) = - block: - let context = getContextWithMode("editor.text", mode) - let p = proc() = - try: - action(TextDocumentEditor(id: getActiveEditor())) - except: - let m {.inject.} = mode - let k {.inject.} = keys - infof"TextCommand {m} {k}: {getCurrentExceptionMsg()}" - addCommand context, keys, p, source = source - -macro addTextCommand*(mode: string, keys: string, action: string, args: varargs[untyped]): untyped = - let (stmts, str) = bindArgs(args) - return genAst(stmts, mode, keys, action, str): - stmts - addCommandScript(getContextWithMode("editor.text", mode), "", keysPrefix & keys, action, str, source = currentSourceLocation(-2)) - -var customMoves = initTable[string, proc(editor: TextDocumentEditor, cursor: Cursor, count: int): Selection]() -proc handleCustomTextMove*(editor: TextDocumentEditor, move: string, cursor: Cursor, count: int): Option[Selection] = - if customMoves.contains(move): - return customMoves[move](editor, cursor, count).some - return Selection.none - -block: # Custom moves - let id = addCallback proc(args: JsonNode): JsonNode = - type Payload = object - editor: EditorId - move: string - cursor: Cursor - count: int - - let input = args.jsonTo(Payload) - if input.editor.isTextEditor editor: - let selection = handleCustomTextMove(editor, input.move, input.cursor, input.count) - if selection.isSome: - return selection.toJson - return nil - else: - infof"Custom move: editor {input.editor} is not a text editor" - return nil - - scriptSetCallback("editor.text.custom-move", id) - -proc addCustomTextMove*(name: string, action: proc(editor: TextDocumentEditor, cursor: Cursor, count: int): Selection) = - customMoves[name] = action - -# Model commands -template addModelCommandBlock*(mode: static[string], keys: string, body: untyped): untyped = - let context = getContextWithMode("editor.model", mode) - addCommand context, keys, proc() = - try: - let editor {.inject, used.} = ModelDocumentEditor(id: getActiveEditor()) - body - except: - let m {.inject.} = mode - let k {.inject.} = keys - infof"ModelCommandBlock {m} {k}: {getCurrentExceptionMsg()}" - -proc addModelCommand*(mode: string, keys: string, action: proc(editor: ModelDocumentEditor): void) = - let context = getContextWithMode("editor.model", mode) - addCommand context, keys, proc() = - action(ModelDocumentEditor(id: getActiveEditor())) - -macro addModelCommand*(mode: static[string], keys: string, action: string, args: varargs[untyped]): untyped = - let context = getContextWithMode("editor.model", mode) - var stmts = nnkStmtList.newTree() - let str = nskVar.genSym "str" - stmts.add quote do: - var `str` = "" - for arg in args: - stmts.add quote do: - `str`.add " " - `str`.add `arg`.toJsonString - - return genAst(stmts, context, keys, action, str): - stmts - addCommandScript(context, "", keysPrefix & keys, action, str, source = currentSourceLocation(-2)) - -proc setModelInputHandler*(context: string, action: proc(editor: ModelDocumentEditor, input: string): bool) = - let id = addCallback proc(args: JsonNode): bool = - let input = args.str - action(ModelDocumentEditor(id: getActiveEditor()), input) - scriptSetCallback("editor.model.input-handler." & context, id) - # setHandleInputs("editor.model." & context, true) - -when defined(wasm): - macro wasmexport*(t: typed): untyped = - if t.kind notin {nnkProcDef, nnkFuncDef}: - error("Can only export procedures", t) - let - newProc = copyNimTree(t) - codeGen = nnkExprColonExpr.newTree(ident"codegendecl", newLit"EMSCRIPTEN_KEEPALIVE $# $#$#") - if newProc[4].kind == nnkEmpty: - newProc[4] = nnkPragma.newTree(codeGen) - else: - newProc[4].add codeGen - newProc[4].add ident"exportC" - result = newStmtList() - result.add: - quote do: - {.emit: "/*INCLUDESECTION*/\n#include ".} - result.add: - newProc - - proc NimMain() {.importc.} - proc emscripten_stack_init() {.importc.} - # proc init_pthread_self() {.importc.} # todo - - proc stackSave*(): uint32 {.wasmexport.} = - assert false, "stackSave not supported" - - proc stackRestore*(n: uint32) {.wasmexport.} = - assert false, "stackRestore not supported" - - proc stackAlloc*(n: uint32): pointer {.wasmexport.} = - assert false, "stackAlloc not supported" - - proc plugin_main*() {.wasmexport.} = - emscripten_stack_init() - # init_pthread_self() - NimMain() - - proc my_alloc*(len: uint32): pointer {.wasmexport.} = - return alloc0(len) - - proc my_dealloc*(p: pointer) {.wasmexport.} = - dealloc(p) - -else: - template wasmexport*(t: typed): untyped = t diff --git a/scripting/plugin_runtime_impl.nim b/scripting/plugin_runtime_impl.nim deleted file mode 100644 index 3abd67256..000000000 --- a/scripting/plugin_runtime_impl.nim +++ /dev/null @@ -1,62 +0,0 @@ -import std/[compilesettings] -import plugin_runtime -import misc/[event, embed_source] - -generateEmbeddedSourceMap() - -const projPath = querySetting(SingleValueSetting.projectPath).normalizeSourcePath & "/" - -for path, content in embeddedSourceFiles(): - let relPath = if path.startsWith(projPath): - path[projPath.len..^1] - else: - path - registerPluginSourceCode(relPath, content) - -proc handleCallback*(id: int, args: JsonNode): bool = handleCallbackImpl(id, args) -proc handleAnyCallback*(id: int, args: JsonNode): JsonNode = handleAnyCallbackImpl(id, args) -proc handleScriptAction*(name: string, args: JsonNode): JsonNode = handleScriptActionImpl(name, args) - -proc postInitializeWasm(): bool {.wasmexport.} = - when compiles(postInitialize()): - try: - return postInitialize() - except: - info &"postInitializeWasm failed: {getCurrentExceptionMsg()}\n{getCurrentException().getStackTrace()}" - return false - else: - true - -proc handleCallbackWasm(id: int32, args: cstring): bool {.wasmexport.} = - try: - return handleCallback(id.int, ($args).parseJson) - except: - info &"handleCallbackWasm failed: {id} {args}: {getCurrentExceptionMsg()}\n{getCurrentException().getStackTrace()}" - return false - -var handleAnyCallbackWasmResult = "" -proc handleAnyCallbackWasm(id: int32, args: cstring): cstring {.wasmexport.} = - # infof"handleAnyCallbackWasm {id.int} {args}" - try: - let res = handleAnyCallback(id.int, ($args).parseJson) - if res.isNil: - return "" - handleAnyCallbackWasmResult = $res - return handleAnyCallbackWasmResult.cstring - except: - info &"handleAnyCallbackWasm failed: {id.int} {args}: {getCurrentExceptionMsg()}\n{getCurrentException().getStackTrace()}" - return cstring ("error: " & getCurrentExceptionMsg()) - -var handleScriptActionWasmResult = "" -proc handleScriptActionWasm(name: cstring, args: cstring): cstring {.wasmexport.} = - # infof"handleScriptActionWasm {name} {args}" - try: - let res = handleScriptAction($name, ($args).parseJson) - if res.isNil: - return "" - handleScriptActionWasmResult = $res - return handleScriptActionWasmResult.cstring - except: - info &"handleScriptActionWasm failed: {name} '{args}': {getCurrentExceptionMsg()}\n{getCurrentException().getStackTrace()}" - handleScriptActionWasmResult = "error: " & getCurrentExceptionMsg() - return handleScriptActionWasmResult.cstring diff --git a/scripting/plugins_api_wasm.nim b/scripting/plugins_api_wasm.nim deleted file mode 100644 index e7da5b98c..000000000 --- a/scripting/plugins_api_wasm.nim +++ /dev/null @@ -1,60 +0,0 @@ -import std/[json, options] -import scripting_api, misc/myjsonutils - -## This file is auto generated, don't modify. - - -proc plugins_bindKeys_void_PluginService_string_string_string_string_string_string_tuple_filename_string_line_int_column_int_wasm( - arg: cstring): cstring {.importc.} -proc bindKeys*(context: string; subContext: string; keys: string; - action: string; arg: string = ""; description: string = ""; - source: tuple[filename: string, line: int, column: int] = ("", 0, 0)) {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add context.toJson() - argsJson.add subContext.toJson() - argsJson.add keys.toJson() - argsJson.add action.toJson() - argsJson.add arg.toJson() - argsJson.add description.toJson() - argsJson.add source.toJson() - let argsJsonString = $argsJson - let res {.used.} = plugins_bindKeys_void_PluginService_string_string_string_string_string_string_tuple_filename_string_line_int_column_int_wasm( - argsJsonString.cstring) - - -proc plugins_callScriptAction_JsonNode_PluginService_string_JsonNode_wasm( - arg: cstring): cstring {.importc.} -proc callScriptAction*(context: string; args: JsonNode): JsonNode {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add context.toJson() - argsJson.add args.toJson() - let argsJsonString = $argsJson - let res {.used.} = plugins_callScriptAction_JsonNode_PluginService_string_JsonNode_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc plugins_addScriptAction_void_PluginService_string_string_seq_tuple_name_string_typ_string_string_bool_string_bool_wasm( - arg: cstring): cstring {.importc.} -proc addScriptAction*(name: string; docs: string = ""; - params: seq[tuple[name: string, typ: string]] = @[]; - returnType: string = ""; active: bool = false; - context: string = "script"; override: bool = false) {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add name.toJson() - argsJson.add docs.toJson() - argsJson.add params.toJson() - argsJson.add returnType.toJson() - argsJson.add active.toJson() - argsJson.add context.toJson() - argsJson.add override.toJson() - let argsJsonString = $argsJson - let res {.used.} = plugins_addScriptAction_void_PluginService_string_string_seq_tuple_name_string_typ_string_string_bool_string_bool_wasm( - argsJsonString.cstring) - diff --git a/scripting/popup_selector_api_wasm.nim b/scripting/popup_selector_api_wasm.nim deleted file mode 100644 index 1b863631f..000000000 --- a/scripting/popup_selector_api_wasm.nim +++ /dev/null @@ -1,136 +0,0 @@ -import std/[json, options] -import scripting_api, misc/myjsonutils - -## This file is auto generated, don't modify. - - -proc popup_selector_setPreviewVisible_void_SelectorPopup_bool_wasm(arg: cstring): cstring {. - importc.} -proc setPreviewVisible*(self: SelectorPopup; visible: bool) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add visible.toJson() - let argsJsonString = $argsJson - let res {.used.} = popup_selector_setPreviewVisible_void_SelectorPopup_bool_wasm( - argsJsonString.cstring) - - -proc popup_selector_togglePreview_void_SelectorPopup_wasm(arg: cstring): cstring {. - importc.} -proc togglePreview*(self: SelectorPopup) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = popup_selector_togglePreview_void_SelectorPopup_wasm( - argsJsonString.cstring) - - -proc popup_selector_getSelectedItemJson_JsonNode_SelectorPopup_wasm(arg: cstring): cstring {. - importc.} -proc getSelectedItemJson*(self: SelectorPopup): JsonNode {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = popup_selector_getSelectedItemJson_JsonNode_SelectorPopup_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc popup_selector_pop_void_SelectorPopup_wasm(arg: cstring): cstring {.importc.} -proc pop*(self: SelectorPopup) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = popup_selector_pop_void_SelectorPopup_wasm( - argsJsonString.cstring) - - -proc popup_selector_accept_void_SelectorPopup_wasm(arg: cstring): cstring {. - importc.} -proc accept*(self: SelectorPopup) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = popup_selector_accept_void_SelectorPopup_wasm( - argsJsonString.cstring) - - -proc popup_selector_cancel_void_SelectorPopup_wasm(arg: cstring): cstring {. - importc.} -proc cancel*(self: SelectorPopup) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = popup_selector_cancel_void_SelectorPopup_wasm( - argsJsonString.cstring) - - -proc popup_selector_sort_void_SelectorPopup_ToggleBool_wasm(arg: cstring): cstring {. - importc.} -proc sort*(self: SelectorPopup; sort: ToggleBool) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add sort.toJson() - let argsJsonString = $argsJson - let res {.used.} = popup_selector_sort_void_SelectorPopup_ToggleBool_wasm( - argsJsonString.cstring) - - -proc popup_selector_setMinScore_void_SelectorPopup_float_bool_wasm(arg: cstring): cstring {. - importc.} -proc setMinScore*(self: SelectorPopup; value: float; add: bool = false) {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add value.toJson() - argsJson.add add.toJson() - let argsJsonString = $argsJson - let res {.used.} = popup_selector_setMinScore_void_SelectorPopup_float_bool_wasm( - argsJsonString.cstring) - - -proc popup_selector_prev_void_SelectorPopup_int_wasm(arg: cstring): cstring {. - importc.} -proc prev*(self: SelectorPopup; count: int = 1) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add count.toJson() - let argsJsonString = $argsJson - let res {.used.} = popup_selector_prev_void_SelectorPopup_int_wasm( - argsJsonString.cstring) - - -proc popup_selector_next_void_SelectorPopup_int_wasm(arg: cstring): cstring {. - importc.} -proc next*(self: SelectorPopup; count: int = 1) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add count.toJson() - let argsJsonString = $argsJson - let res {.used.} = popup_selector_next_void_SelectorPopup_int_wasm( - argsJsonString.cstring) - - -proc popup_selector_setFocusPreview_void_SelectorPopup_bool_wasm(arg: cstring): cstring {. - importc.} -proc setFocusPreview*(self: SelectorPopup; focus: bool) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - argsJson.add focus.toJson() - let argsJsonString = $argsJson - let res {.used.} = popup_selector_setFocusPreview_void_SelectorPopup_bool_wasm( - argsJsonString.cstring) - - -proc popup_selector_toggleFocusPreview_void_SelectorPopup_wasm(arg: cstring): cstring {. - importc.} -proc toggleFocusPreview*(self: SelectorPopup) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add self.toJson() - let argsJsonString = $argsJson - let res {.used.} = popup_selector_toggleFocusPreview_void_SelectorPopup_wasm( - argsJsonString.cstring) - diff --git a/scripting/process_api_wasm.nim b/scripting/process_api_wasm.nim deleted file mode 100644 index 73fe1be9e..000000000 --- a/scripting/process_api_wasm.nim +++ /dev/null @@ -1,22 +0,0 @@ -import std/[json, options] -import scripting_api, misc/myjsonutils - -## This file is auto generated, don't modify. - - -proc process_runProcess_void_PluginService_string_seq_string_Option_string_Option_string_bool_wasm( - arg: cstring): cstring {.importc.} -proc runProcess*(process: string; args: seq[string]; - callback: Option[string] = string.none; - workingDir: Option[string] = string.none; eval: bool = false) {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add process.toJson() - argsJson.add args.toJson() - argsJson.add callback.toJson() - argsJson.add workingDir.toJson() - argsJson.add eval.toJson() - let argsJsonString = $argsJson - let res {.used.} = process_runProcess_void_PluginService_string_seq_string_Option_string_Option_string_bool_wasm( - argsJsonString.cstring) - diff --git a/scripting/registers_api_wasm.nim b/scripting/registers_api_wasm.nim deleted file mode 100644 index 9b1363b23..000000000 --- a/scripting/registers_api_wasm.nim +++ /dev/null @@ -1,110 +0,0 @@ -import std/[json, options] -import scripting_api, misc/myjsonutils - -## This file is auto generated, don't modify. - - -proc registers_setRegisterText_void_Registers_string_string_wasm(arg: cstring): cstring {. - importc.} -proc setRegisterText*(text: string; register: string = "") {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add text.toJson() - argsJson.add register.toJson() - let argsJsonString = $argsJson - let res {.used.} = registers_setRegisterText_void_Registers_string_string_wasm( - argsJsonString.cstring) - - -proc registers_getRegisterText_string_Registers_string_wasm(arg: cstring): cstring {. - importc.} -proc getRegisterText*(register: string): string {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add register.toJson() - let argsJsonString = $argsJson - let res {.used.} = registers_getRegisterText_string_Registers_string_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc registers_startRecordingKeys_void_Registers_string_wasm(arg: cstring): cstring {. - importc.} -proc startRecordingKeys*(register: string) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add register.toJson() - let argsJsonString = $argsJson - let res {.used.} = registers_startRecordingKeys_void_Registers_string_wasm( - argsJsonString.cstring) - - -proc registers_stopRecordingKeys_void_Registers_string_wasm(arg: cstring): cstring {. - importc.} -proc stopRecordingKeys*(register: string) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add register.toJson() - let argsJsonString = $argsJson - let res {.used.} = registers_stopRecordingKeys_void_Registers_string_wasm( - argsJsonString.cstring) - - -proc registers_startRecordingCommands_void_Registers_string_wasm(arg: cstring): cstring {. - importc.} -proc startRecordingCommands*(register: string) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add register.toJson() - let argsJsonString = $argsJson - let res {.used.} = registers_startRecordingCommands_void_Registers_string_wasm( - argsJsonString.cstring) - - -proc registers_stopRecordingCommands_void_Registers_string_wasm(arg: cstring): cstring {. - importc.} -proc stopRecordingCommands*(register: string) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add register.toJson() - let argsJsonString = $argsJson - let res {.used.} = registers_stopRecordingCommands_void_Registers_string_wasm( - argsJsonString.cstring) - - -proc registers_isReplayingCommands_bool_Registers_wasm(arg: cstring): cstring {. - importc.} -proc isReplayingCommands*(): bool {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = registers_isReplayingCommands_bool_Registers_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc registers_isReplayingKeys_bool_Registers_wasm(arg: cstring): cstring {. - importc.} -proc isReplayingKeys*(): bool {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = registers_isReplayingKeys_bool_Registers_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc registers_isRecordingCommands_bool_Registers_string_wasm(arg: cstring): cstring {. - importc.} -proc isRecordingCommands*(registry: string): bool {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add registry.toJson() - let argsJsonString = $argsJson - let res {.used.} = registers_isRecordingCommands_bool_Registers_string_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - diff --git a/scripting/script_expose.nim b/scripting/script_expose.nim deleted file mode 100644 index 94f38cd8f..000000000 --- a/scripting/script_expose.nim +++ /dev/null @@ -1,62 +0,0 @@ -import std/[strformat, tables, macros, json, strutils, sugar, sequtils, genasts] -import misc/[util, wrap, myjsonutils] -import plugin_api - -export plugin_api, util, strformat, tables, json, strutils, sugar, sequtils, scripting_api - -var scriptActions* = initTable[string, proc(args: JsonNode): JsonNode]() - -proc exposeImpl*(context: NimNode, name: NimNode, fun: NimNode, active: bool): NimNode = - # defer: - # echo result.repr - - let def = if fun.kind == nnkProcDef: fun else: fun.getImpl - if def.kind != nnkProcDef: - error("expose can only be used on proc definitions", fun) - - let signature = def.copy - signature[6] = newEmptyNode() - - let signatureUntyped = parseExpr(signature.repr) - let jsonWrapperName = (def.name.repr & "Json").ident - let jsonWrapper = createJsonWrapper(signatureUntyped, jsonWrapperName) - - let documentation = def.getDocumentation() - let documentationStr = documentation.map((it) => it.strVal).get("").newLit - - let returnType = if def[3][0].kind == nnkEmpty: "" else: def[3][0].repr - var params: seq[(string, string)] = @[] - for param in def[3][1..^1]: - params.add (param[0].repr, param[1].repr) - - if def == fun: - return genAst(name, def, jsonWrapper, jsonWrapperName, documentationStr, params, returnType, active, context): - def - jsonWrapper - scriptActions[name] = jsonWrapperName - addScriptAction(name, documentationStr, params, returnType, active, context) - - else: - return genAst(name, jsonWrapper, jsonWrapperName, documentationStr, params, returnType, active, context): - jsonWrapper - scriptActions[name] = jsonWrapperName - addScriptAction(name, documentationStr, params, returnType, active, context) - -macro expose*(name: string, fun: typed): untyped = - return exposeImpl(newLit"script", name, fun, active=false) - -macro expose*(context, string, name: string, fun: typed): untyped = - return exposeImpl(context, name, fun, active=false) - -macro exposeActive*(context: string, name: string, fun: typed): untyped = - return exposeImpl(context, name, fun, active=true) - -macro callJson*(fun: typed, args: JsonNode): JsonNode = - ## Calls a function with a json object as argument, converting the json object to nim types - let jsonWrapperName = genSym(nskProc, "jsonWrapper") - let jsonWrapper = createJsonWrapper(fun, fun.getType, jsonWrapperName) - jsonWrapper.addPragma("closure".ident) - return genAst(jsonWrapper, jsonWrapperName, args): - block: - jsonWrapper - jsonWrapperName(args) diff --git a/scripting/session_api_wasm.nim b/scripting/session_api_wasm.nim deleted file mode 100644 index 5272ecb6c..000000000 --- a/scripting/session_api_wasm.nim +++ /dev/null @@ -1,34 +0,0 @@ -import std/[json, options] -import scripting_api, misc/myjsonutils - -## This file is auto generated, don't modify. - - -proc session_setSessionDataJson_void_SessionService_string_JsonNode_bool_wasm( - arg: cstring): cstring {.importc.} -proc setSessionDataJson*(path: string; value: JsonNode; override: bool = true) {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add path.toJson() - argsJson.add value.toJson() - argsJson.add override.toJson() - let argsJsonString = $argsJson - let res {.used.} = session_setSessionDataJson_void_SessionService_string_JsonNode_bool_wasm( - argsJsonString.cstring) - - -proc session_getSessionDataJson_JsonNode_SessionService_string_JsonNode_wasm( - arg: cstring): cstring {.importc.} -proc getSessionDataJson*(path: string; default: JsonNode): JsonNode {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add path.toJson() - argsJson.add default.toJson() - let argsJsonString = $argsJson - let res {.used.} = session_getSessionDataJson_JsonNode_SessionService_string_JsonNode_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - diff --git a/scripting/terminal_api_wasm.nim b/scripting/terminal_api_wasm.nim deleted file mode 100644 index 1e0759fb4..000000000 --- a/scripting/terminal_api_wasm.nim +++ /dev/null @@ -1,128 +0,0 @@ -import std/[json, options] -import scripting_api, misc/myjsonutils - -## This file is auto generated, don't modify. - - -proc terminal_setTerminalMode_void_TerminalService_string_wasm(arg: cstring): cstring {. - importc.} -proc setTerminalMode*(mode: string) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add mode.toJson() - let argsJsonString = $argsJson - let res {.used.} = terminal_setTerminalMode_void_TerminalService_string_wasm( - argsJsonString.cstring) - - -proc terminal_escape_void_TerminalService_wasm(arg: cstring): cstring {.importc.} -proc escape*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = terminal_escape_void_TerminalService_wasm( - argsJsonString.cstring) - - -proc terminal_createTerminal_void_TerminalService_string_CreateTerminalOptions_wasm( - arg: cstring): cstring {.importc.} -proc createTerminal*(command: string = ""; - options: CreateTerminalOptions = CreateTerminalOptions()) {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add command.toJson() - argsJson.add options.toJson() - let argsJsonString = $argsJson - let res {.used.} = terminal_createTerminal_void_TerminalService_string_CreateTerminalOptions_wasm( - argsJsonString.cstring) - - -proc terminal_runInTerminal_void_TerminalService_string_string_RunInTerminalOptions_wasm( - arg: cstring): cstring {.importc.} -proc runInTerminal*(shell: string; command: string; - options: RunInTerminalOptions = RunInTerminalOptions()) {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add shell.toJson() - argsJson.add command.toJson() - argsJson.add options.toJson() - let argsJsonString = $argsJson - let res {.used.} = terminal_runInTerminal_void_TerminalService_string_string_RunInTerminalOptions_wasm( - argsJsonString.cstring) - - -proc terminal_scrollTerminal_void_TerminalService_int_wasm(arg: cstring): cstring {. - importc.} -proc scrollTerminal*(amount: int) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add amount.toJson() - let argsJsonString = $argsJson - let res {.used.} = terminal_scrollTerminal_void_TerminalService_int_wasm( - argsJsonString.cstring) - - -proc terminal_pasteTerminal_void_TerminalService_string_wasm(arg: cstring): cstring {. - importc.} -proc pasteTerminal*(register: string = "") {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add register.toJson() - let argsJsonString = $argsJson - let res {.used.} = terminal_pasteTerminal_void_TerminalService_string_wasm( - argsJsonString.cstring) - - -proc terminal_enableTerminalDebugLog_void_TerminalService_bool_wasm(arg: cstring): cstring {. - importc.} -proc enableTerminalDebugLog*(enable: bool) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add enable.toJson() - let argsJsonString = $argsJson - let res {.used.} = terminal_enableTerminalDebugLog_void_TerminalService_bool_wasm( - argsJsonString.cstring) - - -proc terminal_sendTerminalInput_void_TerminalService_string_bool_wasm( - arg: cstring): cstring {.importc.} -proc sendTerminalInput*(input: string; noKitty: bool = false) {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add input.toJson() - argsJson.add noKitty.toJson() - let argsJsonString = $argsJson - let res {.used.} = terminal_sendTerminalInput_void_TerminalService_string_bool_wasm( - argsJsonString.cstring) - - -proc terminal_sendTerminalInputAndSetMode_void_TerminalService_string_string_wasm( - arg: cstring): cstring {.importc.} -proc sendTerminalInputAndSetMode*(input: string; mode: string) {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add input.toJson() - argsJson.add mode.toJson() - let argsJsonString = $argsJson - let res {.used.} = terminal_sendTerminalInputAndSetMode_void_TerminalService_string_string_wasm( - argsJsonString.cstring) - - -proc terminal_editTerminalBuffer_void_TerminalService_wasm(arg: cstring): cstring {. - importc.} -proc editTerminalBuffer*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = terminal_editTerminalBuffer_void_TerminalService_wasm( - argsJsonString.cstring) - - -proc terminal_selectTerminal_void_TerminalService_bool_float_float_float_wasm( - arg: cstring): cstring {.importc.} -proc selectTerminal*(preview: bool = true; scaleX: float = 0.9; - scaleY: float = 0.9; previewScale: float = 0.6) {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add preview.toJson() - argsJson.add scaleX.toJson() - argsJson.add scaleY.toJson() - argsJson.add previewScale.toJson() - let argsJsonString = $argsJson - let res {.used.} = terminal_selectTerminal_void_TerminalService_bool_float_float_float_wasm( - argsJsonString.cstring) - diff --git a/scripting/toast_api_wasm.nim b/scripting/toast_api_wasm.nim deleted file mode 100644 index a520fb556..000000000 --- a/scripting/toast_api_wasm.nim +++ /dev/null @@ -1,18 +0,0 @@ -import std/[json, options] -import scripting_api, misc/myjsonutils - -## This file is auto generated, don't modify. - - -proc toast_showToast_void_ToastService_string_string_string_wasm(arg: cstring): cstring {. - importc.} -proc showToast*(title: string; message: string; color: string) {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add title.toJson() - argsJson.add message.toJson() - argsJson.add color.toJson() - let argsJsonString = $argsJson - let res {.used.} = toast_showToast_void_ToastService_string_string_string_wasm( - argsJsonString.cstring) - diff --git a/scripting/vcs_api_wasm.nim b/scripting/vcs_api_wasm.nim deleted file mode 100644 index f90882fe1..000000000 --- a/scripting/vcs_api_wasm.nim +++ /dev/null @@ -1,15 +0,0 @@ -import std/[json, options] -import scripting_api, misc/myjsonutils - -## This file is auto generated, don't modify. - - -proc vcs_chooseGitActiveFiles_void_VCSService_bool_wasm(arg: cstring): cstring {. - importc.} -proc chooseGitActiveFiles*(all: bool = false) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add all.toJson() - let argsJsonString = $argsJson - let res {.used.} = vcs_chooseGitActiveFiles_void_VCSService_bool_wasm( - argsJsonString.cstring) - diff --git a/scripting/vfs_api_wasm.nim b/scripting/vfs_api_wasm.nim deleted file mode 100644 index 254882ffc..000000000 --- a/scripting/vfs_api_wasm.nim +++ /dev/null @@ -1,109 +0,0 @@ -import std/[json, options] -import scripting_api, misc/myjsonutils - -## This file is auto generated, don't modify. - - -proc vfs_mountVfs_void_VFSService_Option_string_string_JsonNode_wasm( - arg: cstring): cstring {.importc.} -proc mountVfs*(parentPath: Option[string]; prefix: string; config: JsonNode) {. - gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add parentPath.toJson() - argsJson.add prefix.toJson() - argsJson.add config.toJson() - let argsJsonString = $argsJson - let res {.used.} = vfs_mountVfs_void_VFSService_Option_string_string_JsonNode_wasm( - argsJsonString.cstring) - - -proc vfs_normalizePath_string_VFSService_string_wasm(arg: cstring): cstring {. - importc.} -proc normalizePath*(path: string): string {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add path.toJson() - let argsJsonString = $argsJson - let res {.used.} = vfs_normalizePath_string_VFSService_string_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc vfs_localizePath_string_VFSService_string_wasm(arg: cstring): cstring {. - importc.} -proc localizePath*(path: string): string {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add path.toJson() - let argsJsonString = $argsJson - let res {.used.} = vfs_localizePath_string_VFSService_string_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc vfs_writeFileSync_void_VFSService_string_string_wasm(arg: cstring): cstring {. - importc.} -proc writeFileSync*(path: string; content: string) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add path.toJson() - argsJson.add content.toJson() - let argsJsonString = $argsJson - let res {.used.} = vfs_writeFileSync_void_VFSService_string_string_wasm( - argsJsonString.cstring) - - -proc vfs_readFileSync_string_VFSService_string_wasm(arg: cstring): cstring {. - importc.} -proc readFileSync*(path: string): string {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add path.toJson() - let argsJsonString = $argsJson - let res {.used.} = vfs_readFileSync_string_VFSService_string_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc vfs_deleteFileSync_void_VFSService_string_wasm(arg: cstring): cstring {. - importc.} -proc deleteFileSync*(path: string) {.gcsafe, raises: [].} = - var argsJson = newJArray() - argsJson.add path.toJson() - let argsJsonString = $argsJson - let res {.used.} = vfs_deleteFileSync_void_VFSService_string_wasm( - argsJsonString.cstring) - - -proc vfs_genTempPath_string_VFSService_string_string_string_int_bool_wasm( - arg: cstring): cstring {.importc.} -proc genTempPath*(prefix: string; suffix: string; dir: string = "temp://"; - randLen: int = 8; checkExists: bool = true): string {.gcsafe, - raises: [].} = - var argsJson = newJArray() - argsJson.add prefix.toJson() - argsJson.add suffix.toJson() - argsJson.add dir.toJson() - argsJson.add randLen.toJson() - argsJson.add checkExists.toJson() - let argsJsonString = $argsJson - let res {.used.} = vfs_genTempPath_string_VFSService_string_string_string_int_bool_wasm( - argsJsonString.cstring) - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - - -proc vfs_dumpVfsHierarchy_void_VFSService_wasm(arg: cstring): cstring {.importc.} -proc dumpVfsHierarchy*() {.gcsafe, raises: [].} = - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = vfs_dumpVfsHierarchy_void_VFSService_wasm( - argsJsonString.cstring) - diff --git a/src/app.nim b/src/app.nim index 66b2e364d..bccaade95 100644 --- a/src/app.nim +++ b/src/app.nim @@ -20,7 +20,6 @@ import misc/async_process when enableAst: import ast/[model, project] -import scripting/[scripting_wasm] import plugin_system_wasm import scripting_api as api except DocumentEditor, TextDocumentEditor, AstDocumentEditor, ModelDocumentEditor, Popup, SelectorPopup @@ -108,7 +107,6 @@ type disableLogFrameTime*: bool = true logBuffer = "" - wasmScriptContext*: ScriptContextWasm pluginSystemWasm*: PluginSystemWasm initializeCalled: bool @@ -228,26 +226,6 @@ proc runConfigCommands(self: App, key: string) = discard self.handleAction(action, arg, record=false) proc initScripting(self: App, options: AppOptions) {.async.} = - if not options.disableOldWasmPlugins: - try: - log(lvlInfo, fmt"load wasm configs") - self.wasmScriptContext = new ScriptContextWasm - self.plugins.pluginSystems.add self.wasmScriptContext - self.wasmScriptContext.moduleVfs = VFS() - self.wasmScriptContext.vfs = self.vfs - self.vfs.mount("plugs://", self.wasmScriptContext.moduleVfs) - - withPluginSystem self.plugins, self.wasmScriptContext: - let t1 = startTimer() - await self.wasmScriptContext.init("app://config", self.vfs) - log(lvlInfo, fmt"init wasm configs ({t1.elapsed.ms}ms)") - - let t2 = startTimer() - discard self.wasmScriptContext.postInitialize() - log(lvlInfo, fmt"post init wasm configs ({t2.elapsed.ms}ms)") - except CatchableError: - log lvlError, &"Failed to load wasm configs: {getCurrentExceptionMsg()}\n{getCurrentException().getStackTrace()}" - self.runConfigCommands("wasm-plugin-post-load-commands") self.runConfigCommands("plugin-post-load-commands") @@ -1087,9 +1065,6 @@ proc shutdown*(self: App) = for document in self.editors.documents: document.deinit() - if self.wasmScriptContext.isNotNil: - self.wasmScriptContext.deinit() - {.gcsafe.}: gAppInterface = nil self[] = AppObject() @@ -1350,14 +1325,14 @@ proc toggleStatusBarLocation*(self: App) {.expose("editor").} = proc logs*(self: App, slot: string = "", focus: bool = true, scrollToBottom: bool = false) {.expose("editor").} = let editors = self.editors.getEditorsForDocument(self.logDocument) let editor = if editors.len > 0: - self.layout.showEditor(editors[0].id, slot = slot, focus = focus) + self.layout.showEditor(editors[0].id.EditorId, slot = slot, focus = focus) editors[0] else: self.layout.createAndAddView(self.logDocument).get if scrollToBottom and editor of TextDocumentEditor: let editor = editor.TextDocumentEditor - editor.moveLast("file") + editor.move("(file) (end)") editor.selection = editor.selection.last.toSelection proc toggleConsoleLogger*(self: App) {.expose("editor").} = @@ -2089,7 +2064,7 @@ proc chooseOpen*(self: App, preview: bool = true, scaleX: float = 0.8, scaleY: f let item = popup.getSelectedItem().getOr: return true - let editorId = item.data.parseInt.EditorId.catch: + let editorId = item.data.parseInt.EditorIdNew.catch: log lvlError, fmt"Failed to parse editor id from data '{item}'" return true @@ -2765,30 +2740,6 @@ proc exploreCurrentFileDirectory*(self: App) {.expose("editor").} = if self.layout.tryGetCurrentEditorView().getSome(view) and view.document.isNotNil: self.exploreFiles(view.document.filename.splitPath.head) -# todo: move to scripting_base -proc reloadPluginAsync*(self: App) {.async.} = - if self.wasmScriptContext.isNotNil: - log lvlInfo, "Reload wasm plugins" - try: - self.plugins.clearScriptActionsFor(self.wasmScriptContext) - - let t1 = startTimer() - withPluginSystem self.plugins, self.wasmScriptContext: - await self.wasmScriptContext.reload() - log(lvlInfo, fmt"Reload wasm plugins ({t1.elapsed.ms}ms)") - - withPluginSystem self.plugins, self.wasmScriptContext: - let t2 = startTimer() - discard self.wasmScriptContext.postInitialize() - log(lvlInfo, fmt"Post init wasm plugins ({t2.elapsed.ms}ms)") - - log lvlInfo, &"Successfully reloaded wasm plugins" - except CatchableError: - log lvlError, &"Failed to reload wasm plugins: {getCurrentExceptionMsg()}\n{getCurrentException().getStackTrace()}" - - self.runConfigCommands("wasm-plugin-post-reload-commands") - self.runConfigCommands("plugin-post-reload-commands") - proc reloadConfigAsync*(self: App) {.async.} = await self.loadConfigFrom(appConfigDir, "app") if not self.appOptions.skipUserSettings: @@ -2804,7 +2755,7 @@ proc reloadConfig*(self: App, clearOptions: bool = false) {.expose("editor").} = proc reloadPlugin*(self: App) {.expose("editor").} = log lvlInfo, &"Reload current plugin" - asyncSpawn self.reloadPluginAsync() + # todo: delete proc reloadTheme*(self: App) {.expose("editor").} = log lvlInfo, &"Reload theme" @@ -3155,13 +3106,13 @@ proc getActiveEditor*(): EditorId {.expose("editor").} = if gEditor.isNil: return EditorId(-1) if gEditor.commands.commandLineMode: - return gEditor.commands.commandLineEditor.id + return gEditor.commands.commandLineEditor.id.EditorId if gEditor.layout.popups.len > 0 and gEditor.layout.popups[gEditor.layout.popups.high].getActiveEditor().getSome(editor): - return editor.id + return editor.id.EditorId if gEditor.layout.tryGetCurrentView().getSome(view) and view.getActiveEditor().getSome(editor): - return editor.id + return editor.id.EditorId return EditorId(-1) @@ -3194,7 +3145,7 @@ proc scriptIsTextEditor*(editorId: EditorId): bool {.expose("editor").} = {.gcsafe.}: if gEditor.isNil: return false - if gEditor.editors.getEditorForId(editorId).getSome(editor): + if gEditor.editors.getEditorForId(editorId.EditorIdNew).getSome(editor): return editor of TextDocumentEditor return false @@ -3203,7 +3154,7 @@ proc scriptIsModelEditor*(editorId: EditorId): bool {.expose("editor").} = if gEditor.isNil: return false when enableAst: - if gEditor.editors.getEditorForId(editorId).getSome(editor): + if gEditor.editors.getEditorForId(editorId.EditorIdNew).getSome(editor): return editor of ModelDocumentEditor return false @@ -3213,9 +3164,9 @@ proc scriptRunActionFor*(editorId: EditorId, action: string, arg: string) {.expo return defer: gEditor.platform.requestRender() - if gEditor.editors.getEditorForId(editorId).getSome(editor): + if gEditor.editors.getEditorForId(editorId.EditorIdNew).getSome(editor): discard editor.handleAction(action, arg, record=false) - elif gEditor.layout.getPopupForId(editorId).getSome(popup): + elif gEditor.layout.getPopupForId(editorId.EditorId).getSome(popup): discard popup.handleAction(action, arg) proc scriptSetCallback*(path: string, id: int) {.expose("editor").} = @@ -3224,24 +3175,6 @@ proc scriptSetCallback*(path: string, id: int) {.expose("editor").} = return gEditor.plugins.callbacks[path] = id -proc replayCommands*(self: App, register: string) {.expose("editor").} = - if not self.registers.registers.contains(register) or self.registers.registers[register].kind != RegisterKind.Text: - log lvlError, fmt"No commands recorded in register '{register}'" - return - - if self.registers.bIsReplayingCommands: - log lvlError, fmt"replayCommands '{register}': Already replaying commands" - return - - log lvlInfo, &"replayCommands '{register}':\n{self.registers.registers[register].text}" - self.registers.bIsReplayingCommands = true - defer: - self.registers.bIsReplayingCommands = false - - for command in self.registers.registers[register].text.splitLines: - let (action, arg) = parseAction(command) - discard self.handleAction(action, arg, record=false) - proc replayKeys*(self: App, register: string) {.expose("editor").} = if not self.registers.registers.contains(register) or self.registers.registers[register].kind != RegisterKind.Text: log lvlError, fmt"No commands recorded in register '{register}'" @@ -3504,6 +3437,3 @@ proc handleAction(self: App, action: string, arg: string, record: bool): Option[ log lvlError, fmt"Unknown command '{action}'" return JsonNode.none - -template generatePluginBindings*(): untyped = - createEditorWasmImportConstructor() diff --git a/src/channel.nim b/src/channel.nim index c1088b2df..ec2daed1e 100644 --- a/src/channel.nim +++ b/src/channel.nim @@ -1,4 +1,4 @@ -import std/[strformat, hashes, macros, genasts, atomics, locks, tables, options] +import std/[hashes, macros, atomics, locks, tables, options] import misc/[event, custom_async, id, generational_seq, util] import nimsumtree/arc @@ -17,17 +17,22 @@ type isOpenImpl*: proc(self: ptr BaseChannel): bool {.gcsafe, raises: [].} peekImpl*: proc(self: ptr BaseChannel, to: Option[uint8]): int {.gcsafe, raises: [].} writeImpl*: proc(self: ptr BaseChannel, data: openArray[uint8]) {.gcsafe, raises: [IOError].} + writeSinkImpl*: proc(self: ptr BaseChannel, data: sink seq[uint8]) {.gcsafe, raises: [IOError].} flushReadImpl*: proc(self: ptr BaseChannel): int {.gcsafe, raises: [IOError].} readImpl*: proc(self: ptr BaseChannel, res: var openArray[uint8]): int {.gcsafe, raises: [IOError].} listenImpl*: proc(self: Arc[BaseChannel], cb: ChannelListener): ListenId {.gcsafe, raises: [].} # todo: make this thread save + InMemoryBuffer = object + data: ptr UncheckedArray[uint8] + len: int InMemoryChannel* = object of BaseChannel isOpen: bool isWaiting: bool data: seq[uint8] # todo: use something more efficient which doesn't require moving memory + dataStart: int writeChannelPeekable: Atomic[int] - channel: ptr Channel[seq[uint8]] + channel: ptr Channel[InMemoryBuffer] ChannelRegistry* = object lock*: Lock @@ -47,6 +52,7 @@ proc close*(self: var BaseChannel) {.gcsafe, raises: [].} = self.closeImpl(self. proc isOpen*(self: var BaseChannel): bool {.raises: [].} = self.isOpenImpl(self.addr) proc peek*(self: var BaseChannel, to: Option[uint8] = uint8.none): int {.raises: [].} = self.peekImpl(self.addr, to) proc write*(self: var BaseChannel, data: openArray[uint8]) {.raises: [IOError].} = self.writeImpl(self.addr, data) +proc write*(self: var BaseChannel, data: sink seq[uint8]) {.raises: [IOError].} = self.writeSinkImpl(self.addr, data.ensureMove) proc read*(self: var BaseChannel, res: var openArray[uint8]): int {.raises: [IOError].} = self.readImpl(self.addr, res) proc flushRead*(self: var BaseChannel): int {.raises: [IOError].} = self.flushReadImpl(self.addr) @@ -55,6 +61,7 @@ proc isOpen*(self: Arc[BaseChannel]): bool {.raises: [].} = self.getMutUnsafe.is proc peek*(self: Arc[BaseChannel], to: Option[uint8] = uint8.none): int {.raises: [].} = self.getMutUnsafe.peek(to) proc write*(self: Arc[BaseChannel], data: openArray[uint8]) {.raises: [IOError].} = self.getMutUnsafe.write(data) proc write*(self: Arc[BaseChannel], data: openArray[char]) {.raises: [IOError].} = self.getMutUnsafe.write(cast[ptr UncheckedArray[uint8]](data[0].addr).toOpenArray(0, data.high)) +proc write*(self: Arc[BaseChannel], data: sink seq[uint8]) {.raises: [IOError].} = self.getMutUnsafe.write(data.ensureMove) proc read*(self: Arc[BaseChannel], res: var openArray[uint8]): int {.raises: [IOError].} = self.getMutUnsafe.read(res) proc flushRead*(self: Arc[BaseChannel]): int {.raises: [IOError].} = self.getMutUnsafe.flushRead() proc listen*(self: Arc[BaseChannel], cb: ChannelListener): ListenId {.gcsafe, raises: [].} = self.get.listenImpl(self, cb) @@ -137,13 +144,22 @@ proc close(self: ptr InMemoryChannel) {.gcsafe, raises: [].} = proc isOpen(self: ptr InMemoryChannel): bool = self.isOpen proc peek(self: ptr InMemoryChannel, to: Option[uint8] = uint8.none): int = if to.getSome(to): - self.data.find(to) + self.data.find(to, self.dataStart) - self.dataStart else: - self.data.len + self.data.len - self.dataStart proc write(self: ptr InMemoryChannel, data: openArray[uint8]) = if data.len > 0: - self.channel[].send(@data) + var buff = InMemoryBuffer(data: cast[ptr UncheckedArray[uint8]](alloc(data.len)), len: data.len) + copyMem(buff.data[0].addr, data[0].addr, data.len) + self.channel[].send(buff) + discard self.signal.fireSync() + +proc write(self: ptr InMemoryChannel, data: sink seq[uint8]) = + if data.len > 0: + var buff = InMemoryBuffer(data: cast[ptr UncheckedArray[uint8]](alloc(data.len)), len: data.len) + copyMem(buff.data[0].addr, data[0].addr, data.len) + self.channel[].send(buff) discard self.signal.fireSync() proc flushRead(self: ptr InMemoryChannel): int = @@ -152,17 +168,27 @@ proc flushRead(self: ptr InMemoryChannel): int = var (ok, data) = self.channel[].tryRecv() if not ok: break - self.data.add data.ensureMove + let oldLen = self.data.len + self.data.setLen(oldLen + data.len) + copyMem(self.data[oldLen].addr, data.data, data.len) + dealloc(data.data) except ValueError as e: echo "Failed to read memory channel: ", e.msg - return self.data.len + return self.data.len - self.dataStart proc read(self: ptr InMemoryChannel, res: var openArray[uint8]): int = discard self.flushRead() - if self.data.len > 0 and res.len > 0: - let toRead = min(self.data.len, res.len) - copyMem(res[0].addr, self.data[0].addr, toRead) - self.data = self.data[toRead..^1] + if self.data.len > self.dataStart and res.len > 0: + let toRead = min(self.data.len - self.dataStart, res.len) + copyMem(res[0].addr, self.data[self.dataStart].addr, toRead) + self.dataStart += toRead + if self.dataStart == self.data.len: + self.data.setLen(0) + self.dataStart = 0 + elif self.dataStart > (self.data.len - self.dataStart) * 5: + moveMem(self.data[0].addr, self.data[self.dataStart].addr, self.data.len - self.dataStart) + self.data.setLen(self.data.len - self.dataStart) + self.dataStart = 0 return toRead return 0 @@ -203,7 +229,7 @@ proc cloneAs*[B](self: Arc[B], T: typedesc[B]): Arc[T] = proc newInMemoryChannel*(): Arc[BaseChannel] = let signal = ThreadSignalPtr.new() - var channel = create(Channel[seq[uint8]]) + var channel = create(Channel[InMemoryBuffer]) channel[].open() var res = Arc[InMemoryChannel].new() @@ -216,6 +242,7 @@ proc newInMemoryChannel*(): Arc[BaseChannel] = isOpenImpl: proc(self: ptr BaseChannel): bool {.gcsafe, raises: [].} = isOpen(cast[ptr InMemoryChannel](self)), peekImpl: proc(self: ptr BaseChannel, to: Option[uint8]): int {.gcsafe, raises: [].} = peek(cast[ptr InMemoryChannel](self), to), writeImpl: proc(self: ptr BaseChannel, data: openArray[uint8]) {.gcsafe, raises: [IOError].} = write(cast[ptr InMemoryChannel](self), data), + writeSinkImpl: proc(self: ptr BaseChannel, data: sink seq[uint8]) {.gcsafe, raises: [IOError].} = write(cast[ptr InMemoryChannel](self), data.ensureMove), readImpl: proc(self: ptr BaseChannel, res: var openArray[uint8]): int {.gcsafe, raises: [IOError].} = read(cast[ptr InMemoryChannel](self), res), flushReadImpl: proc(self: ptr BaseChannel): int {.gcsafe, raises: [IOError].} = flushRead(cast[ptr InMemoryChannel](self)), listenImpl: proc(self: Arc[BaseChannel], cb: ChannelListener): ListenId {.gcsafe, raises: [].} = listenInMemoryChannel(self.cloneAs(InMemoryChannel), cb), diff --git a/src/clipboard.nim b/src/clipboard.nim index c5d42dde2..a575fb2f2 100644 --- a/src/clipboard.nim +++ b/src/clipboard.nim @@ -1,13 +1,26 @@ -import std/[options] +import std/[options, macros] import misc/[util, custom_async, custom_logger] logCategory "clipboard" import compilation_config -when enableSystemClipboard: +when enableWindyClipboard: + import windy static: - echo "Building with system clipboard" + hint("Building with windy clipboard") + + proc setSystemClipboardText*(str: string) = + {.gcsafe.}: + setClipboardString(str) + + proc getSystemClipboardText*(): Future[Option[string]] {.async.} = + {.gcsafe.}: + return getClipboardString().some + +elif enableSystemClipboard: + static: + hint("Building with system clipboard") import nimclipboard/libclipboard import system/ansi_c diff --git a/src/command_service.nim b/src/command_service.nim index 6df3cc74d..14ac1138d 100644 --- a/src/command_service.nim +++ b/src/command_service.nim @@ -23,7 +23,7 @@ type parameters*: seq[tuple[name: string, `type`: string]] returnType*: string signature*: string - execute*: proc(args: string): string {.gcsafe.} + execute*: proc(args: string): string {.gcsafe, raises: [CatchableError].} CommandPermissions* = object allowAll*: Option[bool] @@ -51,6 +51,7 @@ type prefixCommandHandlers: seq[tuple[prefix: string, execute: proc(command: string): Option[string] {.gcsafe, raises: [].}]] commandIdCounter: int = 1 commands*: Table[string, Command] + activeCommands*: Table[string, Command] idToCommand*: Table[CommandId, string] proc all*(_: typedesc[CommandPermissions]) = CommandPermissions(allowAll: some(true), disallowAll: some(true)) @@ -115,6 +116,27 @@ proc unregisterCommand*(self: CommandService, id: CommandId) = self.commands.del(self.idToCommand[id]) self.idToCommand.del(id) +proc registerActiveCommand*(self: CommandService, command: sink Command, override: bool = false): CommandId = + if command.name == "": + log lvlError, &"Trying to register command with no name" + return + + if not override and self.activeCommands.contains(command.name): + log lvlError, &"Trying to register command '{command.name}' which already exists" + return + + let id = self.commandIdCounter.CommandId + inc self.commandIdCounter + + self.unregisterCommand(command.name) + + command.id = id + command.signature = "(" & command.parameters.mapIt(it.name & ": " & it.`type`).join(", ") & ") " & command.returnType + self.idToCommand[id] = command.name + self.activeCommands[command.name] = command.ensureMove + + return id + proc registerCommand*(self: CommandService, command: sink Command, override: bool = false): CommandId = if command.name == "": log lvlError, &"Trying to register command with no name" diff --git a/src/command_service_api.nim b/src/command_service_api.nim index bca03d965..1a2c69e5b 100644 --- a/src/command_service_api.nim +++ b/src/command_service_api.nim @@ -1,4 +1,4 @@ -import std/[strutils, options, json] +import std/[strutils, options, json, tables] import scripting_api except DocumentEditor, TextDocumentEditor, AstDocumentEditor from scripting_api as api import nil import misc/[util, custom_logger, custom_async, custom_unicode, myjsonutils, async_process, delayed_task, timer] @@ -73,6 +73,7 @@ proc exitCommandLine*(self: CommandService) {.expose("commands").} = discard self.defaultCommandHandler(string.none) except Exception as e: log lvlError, &"exitCommandLine: {e.msg}" + self.commandHandler = nil self.requestRender() proc commandLineResult*(self: CommandService, value: string, showInCommandLine: bool = false, @@ -117,6 +118,7 @@ commandLineImpl = commandLine proc executeCommandLine*(self: CommandService): bool {.expose("commands").} = defer: self.requestRender() + self.commandHandler = nil let editor = self.commandLineEditor.TextDocumentEditor self.commandLineInputMode = false @@ -170,7 +172,7 @@ proc selectPreviousCommandInHistory*(self: CommandService) {.expose("commands"). self.currentHistoryEntry = 0 editor.document.content = self.languageServerCommandLine.LanguageServerCommandLine.commandHistory[self.currentHistoryEntry] - editor.moveLast("file", Both) + editor.move("(file) (end)") if self.prefix != "": editor.clearOverlays(overlayIdPrefix) editor.displayMap.overlay.addOverlay(point(0, 0)...point(0, 0), self.prefix, overlayIdPrefix, scope = "comment", bias = Bias.Left) @@ -191,7 +193,7 @@ proc selectNextCommandInHistory*(self: CommandService) {.expose("commands").} = self.currentHistoryEntry = self.languageServerCommandLine.LanguageServerCommandLine.commandHistory.high editor.document.content = self.languageServerCommandLine.LanguageServerCommandLine.commandHistory[self.currentHistoryEntry] - editor.moveLast("file", Both) + editor.move("(file) (end)") if self.prefix != "": editor.clearOverlays(overlayIdPrefix) editor.displayMap.overlay.addOverlay(point(0, 0)...point(0, 0), self.prefix, overlayIdPrefix, scope = "comment", bias = Bias.Left) diff --git a/src/compilation_config.nim b/src/compilation_config.nim index fc26a8747..08fa525a3 100644 --- a/src/compilation_config.nim +++ b/src/compilation_config.nim @@ -4,7 +4,8 @@ const exposeScriptingApi* {.booldefine.}: bool = false const enableGui* {.booldefine.}: bool = false const enableTerminal* {.booldefine.}: bool = false const enableTableIdCacheChecking* {.booldefine.}: bool = false -const enableSystemClipboard* {.booldefine.}: bool = true +const enableWindyClipboard* {.booldefine.}: bool = true +const enableSystemClipboard* {.booldefine.}: bool = false const enableAst* {.booldefine.}: bool = false const enableOldPluginVersions* {.booldefine.}: bool = false const enableLibssh* {.booldefine.}: bool = false diff --git a/src/desktop_main.nim b/src/desktop_main.nim index d3188f105..5a3700460 100644 --- a/src/desktop_main.nim +++ b/src/desktop_main.nim @@ -265,7 +265,6 @@ when enableGui: # Do this after every import # Don't remove those imports, they are needed by generatePluginBindings -import std/[macrocache] when enableAst: import ast/model_document import text/text_editor @@ -273,16 +272,12 @@ import text/language/lsp_client import text/language/debugger import plugin_service import vcs/vcs_api -import wasm3, wasm3/[wasm3c, wasmconversions] -import selector_popup, collab, layout, config_provider, document_editor, session, events, register, selector_popup_builder_impl, vfs_service, command_service_api, toast, terminal_service +import selector_popup, collab, layout, document_editor, session, events, register, selector_popup_builder_impl, vfs_service, command_service_api, toast, terminal_service import language_server_paths import language_server_regex import plugin_api/[process] import scripting/expose - -generatePluginBindings() -static: - generateScriptingApiPerModule() +import config_provider defineSetAllDefaultSettings() @@ -505,3 +500,5 @@ when defined(windows) and copyWasmtimeDll: const dllOut = querySetting(SingleValueSetting.outDir) / "wasmtime.dll" echo "[desktop_main.nim] run tools/copy_wasmtime_dll.nims" echo staticExec &"nim \"-d:inDir={dllIn}\" \"-d:outDir={dllOut}\" --hints:off --skipUserCfg --skipProjCfg --skipParentCfg ../tools/copy_wasmtime_dll.nims" + +printDispatchStats() diff --git a/src/document_editor.nim b/src/document_editor.nim index 27b98b235..0553fec47 100644 --- a/src/document_editor.nim +++ b/src/document_editor.nim @@ -5,7 +5,7 @@ import platform/[platform] import scripting/expose import document, events, input, service, platform_service, dispatch_tables, config_provider -from scripting_api import EditorId, newEditorId +from scripting_api import EditorId {.push gcsafe.} {.push raises: [].} @@ -19,8 +19,7 @@ declareSettings EditorSettings, "editor": type EditorIdNew* = distinct uint64 DocumentEditor* = ref object of RootObj - id*: EditorId - idNew*: EditorIdNew + id*: EditorIdNew userId*: Id renderHeader*: bool fillAvailableSpace*: bool @@ -37,8 +36,8 @@ type DocumentEditorService* = ref object of Service platform: Platform - editors*: Table[EditorId, DocumentEditor] - pinnedEditors*: HashSet[EditorId] + editors*: Table[EditorIdNew, DocumentEditor] + pinnedEditors*: HashSet[EditorIdNew] pinnedDocuments*: seq[Document] onEditorRegistered*: Event[DocumentEditor] onEditorDeregistered*: Event[DocumentEditor] @@ -61,7 +60,7 @@ addBuiltinService(DocumentEditorService) method init*(self: DocumentEditorService): Future[Result[void, ref CatchableError]] {.async: (raises: []).} = log lvlInfo, &"DocumentEditorService.init" - self.pinnedEditors = initHashSet[EditorId]() + self.pinnedEditors = initHashSet[EditorIdNew]() return ok() method canOpenFile*(self: DocumentFactory, path: string): bool {.base, gcsafe, raises: [].} = discard @@ -70,10 +69,9 @@ method createDocument*(self: DocumentFactory, services: Services, path: string, method canEditDocument*(self: DocumentEditorFactory, document: Document): bool {.base, gcsafe, raises: [].} = discard method createEditor*(self: DocumentEditorFactory, services: Services, document: Document): DocumentEditor {.base, gcsafe, raises: [].} = discard -func id*(self: DocumentEditor): EditorId = self.id +func id*(self: DocumentEditor): EditorIdNew = self.id proc init*(self: DocumentEditor) = - self.id = newEditorId() self.userId = newId() self.renderHeader = true @@ -166,12 +164,12 @@ proc unregisterDocument*(self: DocumentEditorService, document: Document) = self.documents.del(document.id) proc registerEditor*(self: DocumentEditorService, editor: DocumentEditor): void = - editor.idNew = self.allEditors.add(editor) + editor.id = self.allEditors.add(editor) self.editors[editor.id] = editor self.onEditorRegistered.invoke editor proc unregisterEditor*(self: DocumentEditorService, editor: DocumentEditor): void = - self.allEditors.del(editor.idNew) + self.allEditors.del(editor.id) self.editors.del(editor.id) self.onEditorDeregistered.invoke editor @@ -198,7 +196,7 @@ proc getEditorsForDocument*(self: DocumentEditorService, document: Document): se if editor.getDocument() == document: result.add editor -proc getEditorForId*(self: DocumentEditorService, id: EditorId): Option[DocumentEditor] = +proc getEditorForId*(self: DocumentEditorService, id: EditorIdNew): Option[DocumentEditor] = self.editors.withValue(id, editor): return editor[].some @@ -292,7 +290,7 @@ static: proc getAllEditors*(self: DocumentEditorService): seq[EditorId] {.expose("editors").} = for id in self.editors.keys: - result.add id + result.add id.EditorId proc getExistingEditor*(self: DocumentEditorService, path: string): Option[EditorId] {.expose("editors").} = ## Returns an existing editor for the given file if one exists, @@ -308,7 +306,7 @@ proc getExistingEditor*(self: DocumentEditorService, path: string): Option[Edito continue if editor.getDocument().filename != path: continue - return id.some + return id.EditorId.some return EditorId.none diff --git a/src/finder/open_editor_previewer.nim b/src/finder/open_editor_previewer.nim index d761cc008..b158a0577 100644 --- a/src/finder/open_editor_previewer.nim +++ b/src/finder/open_editor_previewer.nim @@ -38,7 +38,7 @@ method previewItem*(self: OpenEditorPreviewer, item: FinderItem, editor: Documen let editor = editor.TextDocumentEditor - let editorToPreview = self.editors.getEditorForId(editorId).getOr: + let editorToPreview = self.editors.getEditorForId(editorId.EditorIdNew).getOr: return if not (editorToPreview of TextDocumentEditor): diff --git a/src/generated/plugin_api_host.nim b/src/generated/plugin_api_host.nim index 2102e9e42..cdf120e0f 100644 --- a/src/generated/plugin_api_host.nim +++ b/src/generated/plugin_api_host.nim @@ -25,6 +25,19 @@ type Rect* = object pos*: Vec2f size*: Vec2f + ActiveEditorFlag* = enum + IncludeCommandLine = "include-command-line", + IncludePopups = "include-popups" + ActiveEditorFlags* = set[ActiveEditorFlag] + Lamport* = object + replicaId*: uint16 + value*: uint32 + Bias* = enum + Left = "left", Right = "right" + Anchor* = object + timestamp*: Lamport + offset*: uint32 + bias*: Bias ## Shared reference to a rope. The rope data is stored in the editor, not in the plugin, so ropes ## can be used to efficiently access any document content or share a string with another plugin. ## Ropes are reference counted internally, and this resource also affects that reference count. @@ -62,6 +75,14 @@ type ReadFlag* = enum Binary = "binary" ReadFlags* = set[ReadFlag] + ScrollBehaviour* = enum + CenterAlways = "center-always", CenterOffscreen = "center-offscreen", + CenterMargin = "center-margin", ScrollToMargin = "scroll-to-margin", + TopOfScreen = "top-of-screen" + ScrollSnapBehaviour* = enum + Never = "never", Always = "always", + MinDistanceOffscreen = "min-distance-offscreen", + MinDistanceCenter = "min-distance-center" when not declared(RopeResource): {.error: "Missing resource type definition for " & "RopeResource" & ". Define the type before the importWit statement.".} @@ -92,6 +113,7 @@ type handleViewRenderCallback*: FuncT handleChannelUpdate*: FuncT notifyTaskComplete*: FuncT + handleMove*: FuncT proc mem(funcs: ExportedFuncs): WasmMemory = if funcs.mMemory.get.kind == WASMTIME_EXTERN_SHAREDMEMORY: return initWasmMemory(funcs.mMemory.get.of_field.sharedmemory) @@ -107,43 +129,49 @@ proc collectExports*(funcs: var ExportedFuncs; instance: InstanceT; funcs.mStackAlloc = instance.getExport(context, "mem_stack_alloc") funcs.mStackSave = instance.getExport(context, "mem_stack_save") funcs.mStackRestore = instance.getExport(context, "mem_stack_restore") - let f_9395242601 = instance.getExport(context, "init_plugin") - if f_9395242601.isSome: - assert f_9395242601.get.kind == WASMTIME_EXTERN_FUNC - funcs.initPlugin = f_9395242601.get.of_field.func_field + let f_9177138803 = instance.getExport(context, "init_plugin") + if f_9177138803.isSome: + assert f_9177138803.get.kind == WASMTIME_EXTERN_FUNC + funcs.initPlugin = f_9177138803.get.of_field.func_field else: echo "Failed to find exported function \'", "init_plugin", "\'" - let f_9395242617 = instance.getExport(context, "handle_command") - if f_9395242617.isSome: - assert f_9395242617.get.kind == WASMTIME_EXTERN_FUNC - funcs.handleCommand = f_9395242617.get.of_field.func_field + let f_9177138819 = instance.getExport(context, "handle_command") + if f_9177138819.isSome: + assert f_9177138819.get.kind == WASMTIME_EXTERN_FUNC + funcs.handleCommand = f_9177138819.get.of_field.func_field else: echo "Failed to find exported function \'", "handle_command", "\'" - let f_9395242667 = instance.getExport(context, "handle_mode_changed") - if f_9395242667.isSome: - assert f_9395242667.get.kind == WASMTIME_EXTERN_FUNC - funcs.handleModeChanged = f_9395242667.get.of_field.func_field + let f_9177138869 = instance.getExport(context, "handle_mode_changed") + if f_9177138869.isSome: + assert f_9177138869.get.kind == WASMTIME_EXTERN_FUNC + funcs.handleModeChanged = f_9177138869.get.of_field.func_field else: echo "Failed to find exported function \'", "handle_mode_changed", "\'" - let f_9395242668 = instance.getExport(context, "handle_view_render_callback") - if f_9395242668.isSome: - assert f_9395242668.get.kind == WASMTIME_EXTERN_FUNC - funcs.handleViewRenderCallback = f_9395242668.get.of_field.func_field + let f_9177138870 = instance.getExport(context, "handle_view_render_callback") + if f_9177138870.isSome: + assert f_9177138870.get.kind == WASMTIME_EXTERN_FUNC + funcs.handleViewRenderCallback = f_9177138870.get.of_field.func_field else: echo "Failed to find exported function \'", "handle_view_render_callback", "\'" - let f_9395242692 = instance.getExport(context, "handle_channel_update") - if f_9395242692.isSome: - assert f_9395242692.get.kind == WASMTIME_EXTERN_FUNC - funcs.handleChannelUpdate = f_9395242692.get.of_field.func_field + let f_9177138894 = instance.getExport(context, "handle_channel_update") + if f_9177138894.isSome: + assert f_9177138894.get.kind == WASMTIME_EXTERN_FUNC + funcs.handleChannelUpdate = f_9177138894.get.of_field.func_field else: echo "Failed to find exported function \'", "handle_channel_update", "\'" - let f_9395242693 = instance.getExport(context, "notify_task_complete") - if f_9395242693.isSome: - assert f_9395242693.get.kind == WASMTIME_EXTERN_FUNC - funcs.notifyTaskComplete = f_9395242693.get.of_field.func_field + let f_9177138895 = instance.getExport(context, "notify_task_complete") + if f_9177138895.isSome: + assert f_9177138895.get.kind == WASMTIME_EXTERN_FUNC + funcs.notifyTaskComplete = f_9177138895.get.of_field.func_field else: echo "Failed to find exported function \'", "notify_task_complete", "\'" + let f_9177138896 = instance.getExport(context, "handle_move") + if f_9177138896.isSome: + assert f_9177138896.get.kind == WASMTIME_EXTERN_FUNC + funcs.handleMove = f_9177138896.get.of_field.func_field + else: + echo "Failed to find exported function \'", "handle_move", "\'" proc initPlugin*(funcs: ExportedFuncs): WasmtimeResult[void] = var args: array[max(1, 0), ValT] @@ -328,6 +356,71 @@ proc notifyTaskComplete*(funcs: ExportedFuncs; task: uint64; canceled: bool): Wa if res.isErr: return res.toResult(void) +proc handleMove*(funcs: ExportedFuncs; fun: uint32; data: uint32; text: uint32; + selections: seq[Selection]; count: int32; eol: bool): WasmtimeResult[ + seq[Selection]] = + var args: array[max(1, 7), ValT] + var results: array[max(1, 1), ValT] + var trap: ptr WasmTrapT = nil + var memory = funcs.mem + let savePoint = stackSave(funcs.mStackSave.get.of_field.func_field, + funcs.mContext) + defer: + discard stackRestore(funcs.mStackRestore.get.of_field.func_field, + funcs.mContext, savePoint.val) + var dataPtrWasm0: WasmPtr + args[0] = toWasmVal(fun) + args[1] = toWasmVal(data) + args[2] = toWasmVal(text) + if selections.len > 0: + dataPtrWasm0 = block: + let temp = stackAlloc(funcs.mStackAlloc.get.of_field.func_field, + funcs.mContext, (selections.len * 16).int32, 4) + if temp.isErr: + return temp.toResult(seq[Selection]) + temp.val + args[3] = toWasmVal(cast[int32](dataPtrWasm0)) + block: + for i0 in 0 ..< selections.len: + cast[ptr int32](memory[dataPtrWasm0 + i0 * 16 + 0].addr)[] = selections[ + i0].first.line + cast[ptr int32](memory[dataPtrWasm0 + i0 * 16 + 4].addr)[] = selections[ + i0].first.column + cast[ptr int32](memory[dataPtrWasm0 + i0 * 16 + 8].addr)[] = selections[ + i0].last.line + cast[ptr int32](memory[dataPtrWasm0 + i0 * 16 + 12].addr)[] = selections[ + i0].last.column + else: + args[3] = toWasmVal(0.int32) + args[4] = toWasmVal(cast[int32](selections.len)) + args[5] = toWasmVal(count) + args[6] = toWasmVal(eol) + let res = funcs.handleMove.addr.call(funcs.mContext, + args.toOpenArray(0, 7 - 1), + results.toOpenArray(0, 1 - 1), trap.addr).toResult( + seq[Selection]) + if trap != nil: + return trap.toResult(seq[Selection]) + if res.isErr: + return res.toResult(seq[Selection]) + var retVal: seq[Selection] + let retArea: ptr UncheckedArray[uint8] = memory.getRawPtr( + results[0].to(WasmPtr)) + block: + let p0 = cast[ptr UncheckedArray[uint8]](memory.getRawPtr( + cast[ptr int32](retArea[0].addr)[].WasmPtr)) + retVal = newSeq[typeof(retVal[0])](cast[ptr int32](retArea[4].addr)[]) + for i0 in 0 ..< retVal.len: + retVal[i0].first.line = convert(cast[ptr int32](p0[i0 * 16 + 0].addr)[], + int32) + retVal[i0].first.column = convert(cast[ptr int32](p0[i0 * 16 + 4].addr)[], + int32) + retVal[i0].last.line = convert(cast[ptr int32](p0[i0 * 16 + 8].addr)[], + int32) + retVal[i0].last.column = convert(cast[ptr int32](p0[i0 * 16 + 12].addr)[], + int32) + return wasmtime.ok(retVal) + proc coreApiVersion(instance: ptr InstanceData): int32 proc coreGetTime(instance: ptr InstanceData): float64 proc coreGetPlatform(instance: ptr InstanceData): Platform @@ -343,6 +436,7 @@ proc commandsDefineCommand(instance: ptr InstanceData; name: sink string; fun: uint32; data: uint32): void proc commandsRunCommand(instance: ptr InstanceData; name: sink string; arguments: sink string): Result[string, CommandError] +proc commandsExitCommandLine(instance: ptr InstanceData): void proc settingsGetSettingRaw(instance: ptr InstanceData; name: sink string): string proc settingsSetSettingRaw(instance: ptr InstanceData; name: sink string; value: sink string): void @@ -353,13 +447,23 @@ proc typesRunes(instance: ptr InstanceData; self: var RopeResource): int64 proc typesLines(instance: ptr InstanceData; self: var RopeResource): int64 proc typesText(instance: ptr InstanceData; self: var RopeResource): string proc typesSlice(instance: ptr InstanceData; self: var RopeResource; a: int64; - b: int64): RopeResource + b: int64; inclusive: bool): RopeResource +proc typesSliceSelection(instance: ptr InstanceData; self: var RopeResource; + s: Selection; inclusive: bool): RopeResource +proc typesFind(instance: ptr InstanceData; self: var RopeResource; + sub: sink string; start: int64): Option[int64] proc typesSlicePoints(instance: ptr InstanceData; self: var RopeResource; a: Cursor; b: Cursor): RopeResource -proc editorActiveEditor(instance: ptr InstanceData): Option[Editor] +proc typesLineLength(instance: ptr InstanceData; self: var RopeResource; + line: int64): int64 +proc typesRuneAt(instance: ptr InstanceData; self: var RopeResource; a: Cursor): Rune +proc typesByteAt(instance: ptr InstanceData; self: var RopeResource; a: Cursor): uint8 +proc editorActiveEditor(instance: ptr InstanceData; options: ActiveEditorFlags): Option[ + Editor] proc editorGetDocument(instance: ptr InstanceData; editor: Editor): Option[ Document] -proc textEditorActiveTextEditor(instance: ptr InstanceData): Option[TextEditor] +proc textEditorActiveTextEditor(instance: ptr InstanceData; + options: ActiveEditorFlags): Option[TextEditor] proc textEditorGetDocument(instance: ptr InstanceData; editor: TextEditor): Option[ TextDocument] proc textEditorAsTextEditor(instance: ptr InstanceData; editor: Editor): Option[ @@ -369,13 +473,100 @@ proc textEditorAsTextDocument(instance: ptr InstanceData; document: Document): O proc textEditorCommand(instance: ptr InstanceData; editor: TextEditor; name: sink string; arguments: sink string): Result[ string, CommandError] +proc textEditorRecordCurrentCommand(instance: ptr InstanceData; + editor: TextEditor; + registers: sink seq[string]): void +proc textEditorClearCurrentCommandHistory(instance: ptr InstanceData; + editor: TextEditor; retainLast: bool): void +proc textEditorSaveCurrentCommandHistory(instance: ptr InstanceData; + editor: TextEditor): void +proc textEditorHideCompletions(instance: ptr InstanceData; editor: TextEditor): void +proc textEditorScrollToCursor(instance: ptr InstanceData; editor: TextEditor; + behaviour: Option[ScrollBehaviour]; + relativePosition: float32): void +proc textEditorSetNextSnapBehaviour(instance: ptr InstanceData; + editor: TextEditor; + behaviour: ScrollSnapBehaviour): void +proc textEditorUpdateTargetColumn(instance: ptr InstanceData; editor: TextEditor): void +proc textEditorGetUsage(instance: ptr InstanceData; editor: TextEditor): string +proc textEditorGetRevision(instance: ptr InstanceData; editor: TextEditor): int32 +proc textEditorSetMode(instance: ptr InstanceData; editor: TextEditor; + mode: sink string; exclusive: bool): void +proc textEditorMode(instance: ptr InstanceData; editor: TextEditor): string +proc textEditorModes(instance: ptr InstanceData; editor: TextEditor): seq[string] +proc textEditorClearTabStops(instance: ptr InstanceData; editor: TextEditor): void +proc textEditorUndo(instance: ptr InstanceData; editor: TextEditor; + checkpoint: sink string): void +proc textEditorRedo(instance: ptr InstanceData; editor: TextEditor; + checkpoint: sink string): void +proc textEditorAddNextCheckpoint(instance: ptr InstanceData; editor: TextEditor; + checkpoint: sink string): void +proc textEditorCopy(instance: ptr InstanceData; editor: TextEditor; + register: sink string; inclusiveEnd: bool): void +proc textEditorPaste(instance: ptr InstanceData; editor: TextEditor; + selections: sink seq[Selection]; register: sink string; + inclusiveEnd: bool): void +proc textEditorAutoShowCompletions(instance: ptr InstanceData; + editor: TextEditor): void +proc textEditorToggleLineComment(instance: ptr InstanceData; editor: TextEditor): void +proc textEditorInsertText(instance: ptr InstanceData; editor: TextEditor; + text: sink string; autoIndent: bool): void +proc textEditorOpenSearchBar(instance: ptr InstanceData; editor: TextEditor; + query: sink string; scrollToPreview: bool; + selectResult: bool): void +proc textEditorSetSearchQueryFromMove(instance: ptr InstanceData; + editor: TextEditor; move: sink string; + count: int32; prefix: sink string; + suffix: sink string): Selection +proc textEditorSetSearchQuery(instance: ptr InstanceData; editor: TextEditor; + query: sink string; escapeRegex: bool; + prefix: sink string; suffix: sink string): bool +proc textEditorGetSearchQuery(instance: ptr InstanceData; editor: TextEditor): string +proc textEditorApplyMove(instance: ptr InstanceData; editor: TextEditor; + selection: Selection; move: sink string; count: int32; + wrap: bool; includeEol: bool): seq[Selection] +proc textEditorMultiMove(instance: ptr InstanceData; editor: TextEditor; + selections: sink seq[Selection]; move: sink string; + count: int32; wrap: bool; includeEol: bool): seq[ + Selection] proc textEditorSetSelection(instance: ptr InstanceData; editor: TextEditor; s: Selection): void +proc textEditorSetSelections(instance: ptr InstanceData; editor: TextEditor; + s: sink seq[Selection]): void proc textEditorGetSelection(instance: ptr InstanceData; editor: TextEditor): Selection +proc textEditorGetSelections(instance: ptr InstanceData; editor: TextEditor): seq[ + Selection] +proc textEditorLineLength(instance: ptr InstanceData; editor: TextEditor; + line: int32): int32 proc textEditorAddModeChangedHandler(instance: ptr InstanceData; fun: uint32): int32 -proc textEditorEdit(instance: ptr InstanceData; editor: TextEditor; - selections: sink seq[Selection]; contents: sink seq[string]): seq[ +proc textEditorGetSettingRaw(instance: ptr InstanceData; editor: TextEditor; + name: sink string): string +proc textEditorSetSettingRaw(instance: ptr InstanceData; editor: TextEditor; + name: sink string; value: sink string): void +proc textEditorEvaluateExpressions(instance: ptr InstanceData; + editor: TextEditor; + selections: sink seq[Selection]; + inclusive: bool; prefix: sink string; + suffix: sink string; addSelectionIndex: bool): void +proc textEditorIndent(instance: ptr InstanceData; editor: TextEditor; + delta: int32): void +proc textEditorGetCommandCount(instance: ptr InstanceData; editor: TextEditor): int32 +proc textEditorSetCursorScrollOffset(instance: ptr InstanceData; + editor: TextEditor; cursor: Cursor; + scrollOffset: float32): void +proc textEditorGetVisibleLineCount(instance: ptr InstanceData; + editor: TextEditor): int32 +proc textEditorCreateAnchors(instance: ptr InstanceData; editor: TextEditor; + selections: sink seq[Selection]): seq[ + (Anchor, Anchor)] +proc textEditorResolveAnchors(instance: ptr InstanceData; editor: TextEditor; + anchors: sink seq[(Anchor, Anchor)]): seq[ Selection] +proc textEditorEdit(instance: ptr InstanceData; editor: TextEditor; + selections: sink seq[Selection]; contents: sink seq[string]; + inclusive: bool): seq[Selection] +proc textEditorDefineMove(instance: ptr InstanceData; move: sink string; + fun: uint32; data: uint32): void proc textEditorContent(instance: ptr InstanceData; editor: TextEditor): RopeResource proc textDocumentContent(instance: ptr InstanceData; document: TextDocument): RopeResource proc layoutShow(instance: ptr InstanceData; v: View; slot: sink string; @@ -383,6 +574,8 @@ proc layoutShow(instance: ptr InstanceData; v: View; slot: sink string; proc layoutClose(instance: ptr InstanceData; v: View; keepHidden: bool; restoreHidden: bool): void proc layoutFocus(instance: ptr InstanceData; slot: sink string): void +proc layoutCloseActiveView(instance: ptr InstanceData; closeOpenPopup: bool; + restoreHidden: bool): void proc renderNewRenderView(instance: ptr InstanceData): RenderViewResource proc renderRenderViewFromUserId(instance: ptr InstanceData; id: sink string): Option[ RenderViewResource] @@ -472,6 +665,17 @@ proc processProcessStart(instance: ptr InstanceData; name: sink string; proc processStderr(instance: ptr InstanceData; self: var ProcessResource): ReadChannelResource proc processStdout(instance: ptr InstanceData; self: var ProcessResource): ReadChannelResource proc processStdin(instance: ptr InstanceData; self: var ProcessResource): WriteChannelResource +proc registersIsReplayingCommands(instance: ptr InstanceData): bool +proc registersIsRecordingCommands(instance: ptr InstanceData; + register: sink string): bool +proc registersSetRegisterText(instance: ptr InstanceData; text: sink string; + register: sink string): void +proc registersGetRegisterText(instance: ptr InstanceData; register: sink string): string +proc registersStartRecordingCommands(instance: ptr InstanceData; + register: sink string): void +proc registersStopRecordingCommands(instance: ptr InstanceData; + register: sink string): void +proc registersReplayCommands(instance: ptr InstanceData; register: sink string): void proc defineComponent*(linker: ptr LinkerT): WasmtimeResult[void] = block: let e = block: @@ -742,6 +946,14 @@ proc defineComponent*(linker: ptr LinkerT): WasmtimeResult[void] = cast[ptr int8](memory[retArea + 4].addr)[] = cast[int8](res.error) if e.isErr: return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype([], []) + linker.defineFuncUnchecked("nev:plugins/commands", "exit-command-line", ty): + var instance = cast[ptr InstanceData](store.getData()) + commandsExitCommandLine(instance) + if e.isErr: + return e block: let e = block: var ty: ptr WasmFunctypeT = newFunctype( @@ -934,20 +1146,81 @@ proc defineComponent*(linker: ptr LinkerT): WasmtimeResult[void] = block: let e = block: var ty: ptr WasmFunctypeT = newFunctype( - [WasmValkind.I32, WasmValkind.I64, WasmValkind.I64], [WasmValkind.I32]) + [WasmValkind.I32, WasmValkind.I64, WasmValkind.I64, WasmValkind.I32], + [WasmValkind.I32]) linker.defineFuncUnchecked("nev:plugins/types", "[method]rope.slice", ty): var instance = cast[ptr InstanceData](store.getData()) var self: ptr RopeResource var a: int64 var b: int64 + var inclusive: bool self = ?instance.resources.resourceHostData(parameters[0].i32, RopeResource) a = convert(parameters[1].i64, int64) b = convert(parameters[2].i64, int64) - let res = typesSlice(instance, self[], a, b) + inclusive = parameters[3].i32.bool + let res = typesSlice(instance, self[], a, b, inclusive) + parameters[0].i32 = ?instance.resources.resourceNew(store, res) + if e.isErr: + return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype([WasmValkind.I32, WasmValkind.I32, + WasmValkind.I32, WasmValkind.I32, WasmValkind.I32, WasmValkind.I32], + [WasmValkind.I32]) + linker.defineFuncUnchecked("nev:plugins/types", + "[method]rope.slice-selection", ty): + var instance = cast[ptr InstanceData](store.getData()) + var self: ptr RopeResource + var s: Selection + var inclusive: bool + self = ?instance.resources.resourceHostData(parameters[0].i32, + RopeResource) + s.first.line = convert(parameters[1].i32, int32) + s.first.column = convert(parameters[2].i32, int32) + s.last.line = convert(parameters[3].i32, int32) + s.last.column = convert(parameters[4].i32, int32) + inclusive = parameters[5].i32.bool + let res = typesSliceSelection(instance, self[], s, inclusive) parameters[0].i32 = ?instance.resources.resourceNew(store, res) if e.isErr: return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype([WasmValkind.I32, WasmValkind.I32, + WasmValkind.I32, WasmValkind.I64, WasmValkind.I32], []) + linker.defineFuncUnchecked("nev:plugins/types", "[method]rope.find", ty): + var instance = cast[ptr InstanceData](store.getData()) + var mainMemory = caller.getExport("memory") + if mainMemory.isNone: + mainMemory = instance.getMemoryFor(caller) + var memory: ptr UncheckedArray[uint8] = nil + if mainMemory.get.kind == WASMTIME_EXTERN_SHAREDMEMORY: + memory = cast[ptr UncheckedArray[uint8]](data( + mainMemory.get.of_field.sharedmemory)) + elif mainMemory.get.kind == WASMTIME_EXTERN_MEMORY: + memory = cast[ptr UncheckedArray[uint8]](store.data( + mainMemory.get.of_field.memory.addr)) + else: + assert false + var self: ptr RopeResource + var sub: string + var start: int64 + self = ?instance.resources.resourceHostData(parameters[0].i32, + RopeResource) + block: + let p0 = cast[ptr UncheckedArray[char]](memory[parameters[1].i32].addr) + sub = newString(parameters[2].i32) + for i0 in 0 ..< sub.len: + sub[i0] = p0[i0] + start = convert(parameters[3].i64, int64) + let res = typesFind(instance, self[], sub, start) + let retArea = parameters[^1].i32 + cast[ptr int64](memory[retArea + 0].addr)[] = res.isSome.int64 + if res.isSome: + cast[ptr int64](memory[retArea + 8].addr)[] = res.get + if e.isErr: + return e block: let e = block: var ty: ptr WasmFunctypeT = newFunctype([WasmValkind.I32, WasmValkind.I32, @@ -970,7 +1243,56 @@ proc defineComponent*(linker: ptr LinkerT): WasmtimeResult[void] = return e block: let e = block: - var ty: ptr WasmFunctypeT = newFunctype([WasmValkind.I32], []) + var ty: ptr WasmFunctypeT = newFunctype( + [WasmValkind.I32, WasmValkind.I64], [WasmValkind.I64]) + linker.defineFuncUnchecked("nev:plugins/types", + "[method]rope.line-length", ty): + var instance = cast[ptr InstanceData](store.getData()) + var self: ptr RopeResource + var line: int64 + self = ?instance.resources.resourceHostData(parameters[0].i32, + RopeResource) + line = convert(parameters[1].i64, int64) + let res = typesLineLength(instance, self[], line) + parameters[0].i64 = cast[int64](res) + if e.isErr: + return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype( + [WasmValkind.I32, WasmValkind.I32, WasmValkind.I32], [WasmValkind.I32]) + linker.defineFuncUnchecked("nev:plugins/types", "[method]rope.rune-at", ty): + var instance = cast[ptr InstanceData](store.getData()) + var self: ptr RopeResource + var a: Cursor + self = ?instance.resources.resourceHostData(parameters[0].i32, + RopeResource) + a.line = convert(parameters[1].i32, int32) + a.column = convert(parameters[2].i32, int32) + let res = typesRuneAt(instance, self[], a) + parameters[0].i32 = cast[int32](res) + if e.isErr: + return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype( + [WasmValkind.I32, WasmValkind.I32, WasmValkind.I32], [WasmValkind.I32]) + linker.defineFuncUnchecked("nev:plugins/types", "[method]rope.byte-at", ty): + var instance = cast[ptr InstanceData](store.getData()) + var self: ptr RopeResource + var a: Cursor + self = ?instance.resources.resourceHostData(parameters[0].i32, + RopeResource) + a.line = convert(parameters[1].i32, int32) + a.column = convert(parameters[2].i32, int32) + let res = typesByteAt(instance, self[], a) + parameters[0].i32 = cast[int32](res) + if e.isErr: + return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype( + [WasmValkind.I32, WasmValkind.I32], []) linker.defineFuncUnchecked("nev:plugins/editor", "active-editor", ty): var instance = cast[ptr InstanceData](store.getData()) var mainMemory = caller.getExport("memory") @@ -985,7 +1307,9 @@ proc defineComponent*(linker: ptr LinkerT): WasmtimeResult[void] = mainMemory.get.of_field.memory.addr)) else: assert false - let res = editorActiveEditor(instance) + var options: ActiveEditorFlags + options = cast[ActiveEditorFlags](parameters[0].i32) + let res = editorActiveEditor(instance, options) let retArea = parameters[^1].i32 cast[ptr int64](memory[retArea + 0].addr)[] = res.isSome.int64 if res.isSome: @@ -1021,7 +1345,8 @@ proc defineComponent*(linker: ptr LinkerT): WasmtimeResult[void] = return e block: let e = block: - var ty: ptr WasmFunctypeT = newFunctype([WasmValkind.I32], []) + var ty: ptr WasmFunctypeT = newFunctype( + [WasmValkind.I32, WasmValkind.I32], []) linker.defineFuncUnchecked("nev:plugins/text-editor", "active-text-editor", ty): var instance = cast[ptr InstanceData](store.getData()) @@ -1037,7 +1362,9 @@ proc defineComponent*(linker: ptr LinkerT): WasmtimeResult[void] = mainMemory.get.of_field.memory.addr)) else: assert false - let res = textEditorActiveTextEditor(instance) + var options: ActiveEditorFlags + options = cast[ActiveEditorFlags](parameters[0].i32) + let res = textEditorActiveTextEditor(instance, options) let retArea = parameters[^1].i32 cast[ptr int64](memory[retArea + 0].addr)[] = res.isSome.int64 if res.isSome: @@ -1180,25 +1507,1220 @@ proc defineComponent*(linker: ptr LinkerT): WasmtimeResult[void] = return e block: let e = block: - var ty: ptr WasmFunctypeT = newFunctype([WasmValkind.I64, WasmValkind.I32, - WasmValkind.I32, WasmValkind.I32, WasmValkind.I32], []) - linker.defineFuncUnchecked("nev:plugins/text-editor", "set-selection", ty): + var ty: ptr WasmFunctypeT = newFunctype( + [WasmValkind.I64, WasmValkind.I32, WasmValkind.I32], []) + linker.defineFuncUnchecked("nev:plugins/text-editor", + "record-current-command", ty): + var instance = cast[ptr InstanceData](store.getData()) + var mainMemory = caller.getExport("memory") + if mainMemory.isNone: + mainMemory = instance.getMemoryFor(caller) + var memory: ptr UncheckedArray[uint8] = nil + if mainMemory.get.kind == WASMTIME_EXTERN_SHAREDMEMORY: + memory = cast[ptr UncheckedArray[uint8]](data( + mainMemory.get.of_field.sharedmemory)) + elif mainMemory.get.kind == WASMTIME_EXTERN_MEMORY: + memory = cast[ptr UncheckedArray[uint8]](store.data( + mainMemory.get.of_field.memory.addr)) + else: + assert false + var editor: TextEditor + var registers: seq[string] + editor.id = convert(parameters[0].i64, uint64) + block: + let p0 = cast[ptr UncheckedArray[uint8]](memory[parameters[1].i32].addr) + registers = newSeq[typeof(registers[0])](parameters[2].i32) + for i0 in 0 ..< registers.len: + block: + let p1 = cast[ptr UncheckedArray[char]](memory[ + cast[ptr int32](p0[i0 * 8 + 0].addr)[]].addr) + registers[i0] = newString(cast[ptr int32](p0[i0 * 8 + 4].addr)[]) + for i1 in 0 ..< registers[i0].len: + registers[i0][i1] = p1[i1] + textEditorRecordCurrentCommand(instance, editor, registers) + if e.isErr: + return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype( + [WasmValkind.I64, WasmValkind.I32], []) + linker.defineFuncUnchecked("nev:plugins/text-editor", + "clear-current-command-history", ty): + var instance = cast[ptr InstanceData](store.getData()) + var editor: TextEditor + var retainLast: bool + editor.id = convert(parameters[0].i64, uint64) + retainLast = parameters[1].i32.bool + textEditorClearCurrentCommandHistory(instance, editor, retainLast) + if e.isErr: + return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype([WasmValkind.I64], []) + linker.defineFuncUnchecked("nev:plugins/text-editor", + "save-current-command-history", ty): + var instance = cast[ptr InstanceData](store.getData()) + var editor: TextEditor + editor.id = convert(parameters[0].i64, uint64) + textEditorSaveCurrentCommandHistory(instance, editor) + if e.isErr: + return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype([WasmValkind.I64], []) + linker.defineFuncUnchecked("nev:plugins/text-editor", "hide-completions", + ty): + var instance = cast[ptr InstanceData](store.getData()) + var editor: TextEditor + editor.id = convert(parameters[0].i64, uint64) + textEditorHideCompletions(instance, editor) + if e.isErr: + return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype( + [WasmValkind.I64, WasmValkind.I32, WasmValkind.I32, WasmValkind.F32], + []) + linker.defineFuncUnchecked("nev:plugins/text-editor", "scroll-to-cursor", + ty): + var instance = cast[ptr InstanceData](store.getData()) + var editor: TextEditor + var behaviour: Option[ScrollBehaviour] + var relativePosition: float32 + editor.id = convert(parameters[0].i64, uint64) + if parameters[1].i32 != 0: + var temp: ScrollBehaviour + temp = cast[ScrollBehaviour](parameters[2].i32) + behaviour = temp.some + relativePosition = convert(parameters[3].f32, float32) + textEditorScrollToCursor(instance, editor, behaviour, relativePosition) + if e.isErr: + return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype( + [WasmValkind.I64, WasmValkind.I32], []) + linker.defineFuncUnchecked("nev:plugins/text-editor", + "set-next-snap-behaviour", ty): + var instance = cast[ptr InstanceData](store.getData()) + var editor: TextEditor + var behaviour: ScrollSnapBehaviour + editor.id = convert(parameters[0].i64, uint64) + behaviour = cast[ScrollSnapBehaviour](parameters[1].i32) + textEditorSetNextSnapBehaviour(instance, editor, behaviour) + if e.isErr: + return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype([WasmValkind.I64], []) + linker.defineFuncUnchecked("nev:plugins/text-editor", + "update-target-column", ty): + var instance = cast[ptr InstanceData](store.getData()) + var editor: TextEditor + editor.id = convert(parameters[0].i64, uint64) + textEditorUpdateTargetColumn(instance, editor) + if e.isErr: + return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype( + [WasmValkind.I64, WasmValkind.I32], []) + linker.defineFuncUnchecked("nev:plugins/text-editor", "get-usage", ty): + var instance = cast[ptr InstanceData](store.getData()) + var mainMemory = caller.getExport("memory") + if mainMemory.isNone: + mainMemory = instance.getMemoryFor(caller) + var memory: ptr UncheckedArray[uint8] = nil + if mainMemory.get.kind == WASMTIME_EXTERN_SHAREDMEMORY: + memory = cast[ptr UncheckedArray[uint8]](data( + mainMemory.get.of_field.sharedmemory)) + elif mainMemory.get.kind == WASMTIME_EXTERN_MEMORY: + memory = cast[ptr UncheckedArray[uint8]](store.data( + mainMemory.get.of_field.memory.addr)) + else: + assert false + let stackAllocFunc = caller.getExport("mem_stack_alloc").get.of_field.func_field + var editor: TextEditor + editor.id = convert(parameters[0].i64, uint64) + let res = textEditorGetUsage(instance, editor) + let retArea = parameters[^1].i32 + if res.len > 0: + let dataPtrWasm0 = int32(?stackAlloc(stackAllocFunc, store, + (res.len * 1).int32, 4)) + cast[ptr int32](memory[retArea + 0].addr)[] = cast[int32](dataPtrWasm0) + block: + for i0 in 0 ..< res.len: + memory[dataPtrWasm0 + i0] = cast[uint8](res[i0]) + else: + cast[ptr int32](memory[retArea + 0].addr)[] = 0.int32 + cast[ptr int32](memory[retArea + 4].addr)[] = cast[int32](res.len) + if e.isErr: + return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype([WasmValkind.I64], + [WasmValkind.I32]) + linker.defineFuncUnchecked("nev:plugins/text-editor", "get-revision", ty): + var instance = cast[ptr InstanceData](store.getData()) + var editor: TextEditor + editor.id = convert(parameters[0].i64, uint64) + let res = textEditorGetRevision(instance, editor) + parameters[0].i32 = cast[int32](res) + if e.isErr: + return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype( + [WasmValkind.I64, WasmValkind.I32, WasmValkind.I32, WasmValkind.I32], + []) + linker.defineFuncUnchecked("nev:plugins/text-editor", "set-mode", ty): var instance = cast[ptr InstanceData](store.getData()) + var mainMemory = caller.getExport("memory") + if mainMemory.isNone: + mainMemory = instance.getMemoryFor(caller) + var memory: ptr UncheckedArray[uint8] = nil + if mainMemory.get.kind == WASMTIME_EXTERN_SHAREDMEMORY: + memory = cast[ptr UncheckedArray[uint8]](data( + mainMemory.get.of_field.sharedmemory)) + elif mainMemory.get.kind == WASMTIME_EXTERN_MEMORY: + memory = cast[ptr UncheckedArray[uint8]](store.data( + mainMemory.get.of_field.memory.addr)) + else: + assert false + var editor: TextEditor + var mode: string + var exclusive: bool + editor.id = convert(parameters[0].i64, uint64) + block: + let p0 = cast[ptr UncheckedArray[char]](memory[parameters[1].i32].addr) + mode = newString(parameters[2].i32) + for i0 in 0 ..< mode.len: + mode[i0] = p0[i0] + exclusive = parameters[3].i32.bool + textEditorSetMode(instance, editor, mode, exclusive) + if e.isErr: + return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype( + [WasmValkind.I64, WasmValkind.I32], []) + linker.defineFuncUnchecked("nev:plugins/text-editor", "mode", ty): + var instance = cast[ptr InstanceData](store.getData()) + var mainMemory = caller.getExport("memory") + if mainMemory.isNone: + mainMemory = instance.getMemoryFor(caller) + var memory: ptr UncheckedArray[uint8] = nil + if mainMemory.get.kind == WASMTIME_EXTERN_SHAREDMEMORY: + memory = cast[ptr UncheckedArray[uint8]](data( + mainMemory.get.of_field.sharedmemory)) + elif mainMemory.get.kind == WASMTIME_EXTERN_MEMORY: + memory = cast[ptr UncheckedArray[uint8]](store.data( + mainMemory.get.of_field.memory.addr)) + else: + assert false + let stackAllocFunc = caller.getExport("mem_stack_alloc").get.of_field.func_field + var editor: TextEditor + editor.id = convert(parameters[0].i64, uint64) + let res = textEditorMode(instance, editor) + let retArea = parameters[^1].i32 + if res.len > 0: + let dataPtrWasm0 = int32(?stackAlloc(stackAllocFunc, store, + (res.len * 1).int32, 4)) + cast[ptr int32](memory[retArea + 0].addr)[] = cast[int32](dataPtrWasm0) + block: + for i0 in 0 ..< res.len: + memory[dataPtrWasm0 + i0] = cast[uint8](res[i0]) + else: + cast[ptr int32](memory[retArea + 0].addr)[] = 0.int32 + cast[ptr int32](memory[retArea + 4].addr)[] = cast[int32](res.len) + if e.isErr: + return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype( + [WasmValkind.I64, WasmValkind.I32], []) + linker.defineFuncUnchecked("nev:plugins/text-editor", "modes", ty): + var instance = cast[ptr InstanceData](store.getData()) + var mainMemory = caller.getExport("memory") + if mainMemory.isNone: + mainMemory = instance.getMemoryFor(caller) + var memory: ptr UncheckedArray[uint8] = nil + if mainMemory.get.kind == WASMTIME_EXTERN_SHAREDMEMORY: + memory = cast[ptr UncheckedArray[uint8]](data( + mainMemory.get.of_field.sharedmemory)) + elif mainMemory.get.kind == WASMTIME_EXTERN_MEMORY: + memory = cast[ptr UncheckedArray[uint8]](store.data( + mainMemory.get.of_field.memory.addr)) + else: + assert false + let stackAllocFunc = caller.getExport("mem_stack_alloc").get.of_field.func_field + var editor: TextEditor + editor.id = convert(parameters[0].i64, uint64) + let res = textEditorModes(instance, editor) + let retArea = parameters[^1].i32 + if res.len > 0: + let dataPtrWasm0 = int32(?stackAlloc(stackAllocFunc, store, + (res.len * 8).int32, 4)) + cast[ptr int32](memory[retArea + 0].addr)[] = cast[int32](dataPtrWasm0) + block: + for i0 in 0 ..< res.len: + if res[i0].len > 0: + let dataPtrWasm1 = int32(?stackAlloc(stackAllocFunc, store, + (res[i0].len * 1).int32, 4)) + cast[ptr int32](memory[dataPtrWasm0 + i0 * 8 + 0].addr)[] = cast[int32](dataPtrWasm1) + block: + for i1 in 0 ..< res[i0].len: + memory[dataPtrWasm1 + i1] = cast[uint8](res[i0][i1]) + else: + cast[ptr int32](memory[dataPtrWasm0 + i0 * 8 + 0].addr)[] = 0.int32 + cast[ptr int32](memory[dataPtrWasm0 + i0 * 8 + 4].addr)[] = cast[int32](res[ + i0].len) + else: + cast[ptr int32](memory[retArea + 0].addr)[] = 0.int32 + cast[ptr int32](memory[retArea + 4].addr)[] = cast[int32](res.len) + if e.isErr: + return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype([WasmValkind.I64], []) + linker.defineFuncUnchecked("nev:plugins/text-editor", "clear-tab-stops", + ty): + var instance = cast[ptr InstanceData](store.getData()) + var editor: TextEditor + editor.id = convert(parameters[0].i64, uint64) + textEditorClearTabStops(instance, editor) + if e.isErr: + return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype( + [WasmValkind.I64, WasmValkind.I32, WasmValkind.I32], []) + linker.defineFuncUnchecked("nev:plugins/text-editor", "undo", ty): + var instance = cast[ptr InstanceData](store.getData()) + var mainMemory = caller.getExport("memory") + if mainMemory.isNone: + mainMemory = instance.getMemoryFor(caller) + var memory: ptr UncheckedArray[uint8] = nil + if mainMemory.get.kind == WASMTIME_EXTERN_SHAREDMEMORY: + memory = cast[ptr UncheckedArray[uint8]](data( + mainMemory.get.of_field.sharedmemory)) + elif mainMemory.get.kind == WASMTIME_EXTERN_MEMORY: + memory = cast[ptr UncheckedArray[uint8]](store.data( + mainMemory.get.of_field.memory.addr)) + else: + assert false + var editor: TextEditor + var checkpoint: string + editor.id = convert(parameters[0].i64, uint64) + block: + let p0 = cast[ptr UncheckedArray[char]](memory[parameters[1].i32].addr) + checkpoint = newString(parameters[2].i32) + for i0 in 0 ..< checkpoint.len: + checkpoint[i0] = p0[i0] + textEditorUndo(instance, editor, checkpoint) + if e.isErr: + return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype( + [WasmValkind.I64, WasmValkind.I32, WasmValkind.I32], []) + linker.defineFuncUnchecked("nev:plugins/text-editor", "redo", ty): + var instance = cast[ptr InstanceData](store.getData()) + var mainMemory = caller.getExport("memory") + if mainMemory.isNone: + mainMemory = instance.getMemoryFor(caller) + var memory: ptr UncheckedArray[uint8] = nil + if mainMemory.get.kind == WASMTIME_EXTERN_SHAREDMEMORY: + memory = cast[ptr UncheckedArray[uint8]](data( + mainMemory.get.of_field.sharedmemory)) + elif mainMemory.get.kind == WASMTIME_EXTERN_MEMORY: + memory = cast[ptr UncheckedArray[uint8]](store.data( + mainMemory.get.of_field.memory.addr)) + else: + assert false + var editor: TextEditor + var checkpoint: string + editor.id = convert(parameters[0].i64, uint64) + block: + let p0 = cast[ptr UncheckedArray[char]](memory[parameters[1].i32].addr) + checkpoint = newString(parameters[2].i32) + for i0 in 0 ..< checkpoint.len: + checkpoint[i0] = p0[i0] + textEditorRedo(instance, editor, checkpoint) + if e.isErr: + return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype( + [WasmValkind.I64, WasmValkind.I32, WasmValkind.I32], []) + linker.defineFuncUnchecked("nev:plugins/text-editor", + "add-next-checkpoint", ty): + var instance = cast[ptr InstanceData](store.getData()) + var mainMemory = caller.getExport("memory") + if mainMemory.isNone: + mainMemory = instance.getMemoryFor(caller) + var memory: ptr UncheckedArray[uint8] = nil + if mainMemory.get.kind == WASMTIME_EXTERN_SHAREDMEMORY: + memory = cast[ptr UncheckedArray[uint8]](data( + mainMemory.get.of_field.sharedmemory)) + elif mainMemory.get.kind == WASMTIME_EXTERN_MEMORY: + memory = cast[ptr UncheckedArray[uint8]](store.data( + mainMemory.get.of_field.memory.addr)) + else: + assert false + var editor: TextEditor + var checkpoint: string + editor.id = convert(parameters[0].i64, uint64) + block: + let p0 = cast[ptr UncheckedArray[char]](memory[parameters[1].i32].addr) + checkpoint = newString(parameters[2].i32) + for i0 in 0 ..< checkpoint.len: + checkpoint[i0] = p0[i0] + textEditorAddNextCheckpoint(instance, editor, checkpoint) + if e.isErr: + return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype( + [WasmValkind.I64, WasmValkind.I32, WasmValkind.I32, WasmValkind.I32], + []) + linker.defineFuncUnchecked("nev:plugins/text-editor", "copy", ty): + var instance = cast[ptr InstanceData](store.getData()) + var mainMemory = caller.getExport("memory") + if mainMemory.isNone: + mainMemory = instance.getMemoryFor(caller) + var memory: ptr UncheckedArray[uint8] = nil + if mainMemory.get.kind == WASMTIME_EXTERN_SHAREDMEMORY: + memory = cast[ptr UncheckedArray[uint8]](data( + mainMemory.get.of_field.sharedmemory)) + elif mainMemory.get.kind == WASMTIME_EXTERN_MEMORY: + memory = cast[ptr UncheckedArray[uint8]](store.data( + mainMemory.get.of_field.memory.addr)) + else: + assert false + var editor: TextEditor + var register: string + var inclusiveEnd: bool + editor.id = convert(parameters[0].i64, uint64) + block: + let p0 = cast[ptr UncheckedArray[char]](memory[parameters[1].i32].addr) + register = newString(parameters[2].i32) + for i0 in 0 ..< register.len: + register[i0] = p0[i0] + inclusiveEnd = parameters[3].i32.bool + textEditorCopy(instance, editor, register, inclusiveEnd) + if e.isErr: + return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype([WasmValkind.I64, WasmValkind.I32, + WasmValkind.I32, WasmValkind.I32, WasmValkind.I32, WasmValkind.I32], + []) + linker.defineFuncUnchecked("nev:plugins/text-editor", "paste", ty): + var instance = cast[ptr InstanceData](store.getData()) + var mainMemory = caller.getExport("memory") + if mainMemory.isNone: + mainMemory = instance.getMemoryFor(caller) + var memory: ptr UncheckedArray[uint8] = nil + if mainMemory.get.kind == WASMTIME_EXTERN_SHAREDMEMORY: + memory = cast[ptr UncheckedArray[uint8]](data( + mainMemory.get.of_field.sharedmemory)) + elif mainMemory.get.kind == WASMTIME_EXTERN_MEMORY: + memory = cast[ptr UncheckedArray[uint8]](store.data( + mainMemory.get.of_field.memory.addr)) + else: + assert false + var editor: TextEditor + var selections: seq[Selection] + var register: string + var inclusiveEnd: bool + editor.id = convert(parameters[0].i64, uint64) + block: + let p0 = cast[ptr UncheckedArray[uint8]](memory[parameters[1].i32].addr) + selections = newSeq[typeof(selections[0])](parameters[2].i32) + for i0 in 0 ..< selections.len: + selections[i0].first.line = convert( + cast[ptr int32](p0[i0 * 16 + 0].addr)[], int32) + selections[i0].first.column = convert( + cast[ptr int32](p0[i0 * 16 + 4].addr)[], int32) + selections[i0].last.line = convert( + cast[ptr int32](p0[i0 * 16 + 8].addr)[], int32) + selections[i0].last.column = convert( + cast[ptr int32](p0[i0 * 16 + 12].addr)[], int32) + block: + let p0 = cast[ptr UncheckedArray[char]](memory[parameters[3].i32].addr) + register = newString(parameters[4].i32) + for i0 in 0 ..< register.len: + register[i0] = p0[i0] + inclusiveEnd = parameters[5].i32.bool + textEditorPaste(instance, editor, selections, register, inclusiveEnd) + if e.isErr: + return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype([WasmValkind.I64], []) + linker.defineFuncUnchecked("nev:plugins/text-editor", + "auto-show-completions", ty): + var instance = cast[ptr InstanceData](store.getData()) + var editor: TextEditor + editor.id = convert(parameters[0].i64, uint64) + textEditorAutoShowCompletions(instance, editor) + if e.isErr: + return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype([WasmValkind.I64], []) + linker.defineFuncUnchecked("nev:plugins/text-editor", + "toggle-line-comment", ty): + var instance = cast[ptr InstanceData](store.getData()) + var editor: TextEditor + editor.id = convert(parameters[0].i64, uint64) + textEditorToggleLineComment(instance, editor) + if e.isErr: + return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype( + [WasmValkind.I64, WasmValkind.I32, WasmValkind.I32, WasmValkind.I32], + []) + linker.defineFuncUnchecked("nev:plugins/text-editor", "insert-text", ty): + var instance = cast[ptr InstanceData](store.getData()) + var mainMemory = caller.getExport("memory") + if mainMemory.isNone: + mainMemory = instance.getMemoryFor(caller) + var memory: ptr UncheckedArray[uint8] = nil + if mainMemory.get.kind == WASMTIME_EXTERN_SHAREDMEMORY: + memory = cast[ptr UncheckedArray[uint8]](data( + mainMemory.get.of_field.sharedmemory)) + elif mainMemory.get.kind == WASMTIME_EXTERN_MEMORY: + memory = cast[ptr UncheckedArray[uint8]](store.data( + mainMemory.get.of_field.memory.addr)) + else: + assert false + var editor: TextEditor + var text: string + var autoIndent: bool + editor.id = convert(parameters[0].i64, uint64) + block: + let p0 = cast[ptr UncheckedArray[char]](memory[parameters[1].i32].addr) + text = newString(parameters[2].i32) + for i0 in 0 ..< text.len: + text[i0] = p0[i0] + autoIndent = parameters[3].i32.bool + textEditorInsertText(instance, editor, text, autoIndent) + if e.isErr: + return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype([WasmValkind.I64, WasmValkind.I32, + WasmValkind.I32, WasmValkind.I32, WasmValkind.I32], []) + linker.defineFuncUnchecked("nev:plugins/text-editor", "open-search-bar", + ty): + var instance = cast[ptr InstanceData](store.getData()) + var mainMemory = caller.getExport("memory") + if mainMemory.isNone: + mainMemory = instance.getMemoryFor(caller) + var memory: ptr UncheckedArray[uint8] = nil + if mainMemory.get.kind == WASMTIME_EXTERN_SHAREDMEMORY: + memory = cast[ptr UncheckedArray[uint8]](data( + mainMemory.get.of_field.sharedmemory)) + elif mainMemory.get.kind == WASMTIME_EXTERN_MEMORY: + memory = cast[ptr UncheckedArray[uint8]](store.data( + mainMemory.get.of_field.memory.addr)) + else: + assert false + var editor: TextEditor + var query: string + var scrollToPreview: bool + var selectResult: bool + editor.id = convert(parameters[0].i64, uint64) + block: + let p0 = cast[ptr UncheckedArray[char]](memory[parameters[1].i32].addr) + query = newString(parameters[2].i32) + for i0 in 0 ..< query.len: + query[i0] = p0[i0] + scrollToPreview = parameters[3].i32.bool + selectResult = parameters[4].i32.bool + textEditorOpenSearchBar(instance, editor, query, scrollToPreview, + selectResult) + if e.isErr: + return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype([WasmValkind.I64, WasmValkind.I32, + WasmValkind.I32, WasmValkind.I32, WasmValkind.I32, WasmValkind.I32, + WasmValkind.I32, WasmValkind.I32, WasmValkind.I32], []) + linker.defineFuncUnchecked("nev:plugins/text-editor", + "set-search-query-from-move", ty): + var instance = cast[ptr InstanceData](store.getData()) + var mainMemory = caller.getExport("memory") + if mainMemory.isNone: + mainMemory = instance.getMemoryFor(caller) + var memory: ptr UncheckedArray[uint8] = nil + if mainMemory.get.kind == WASMTIME_EXTERN_SHAREDMEMORY: + memory = cast[ptr UncheckedArray[uint8]](data( + mainMemory.get.of_field.sharedmemory)) + elif mainMemory.get.kind == WASMTIME_EXTERN_MEMORY: + memory = cast[ptr UncheckedArray[uint8]](store.data( + mainMemory.get.of_field.memory.addr)) + else: + assert false + var editor: TextEditor + var move: string + var count: int32 + var prefix: string + var suffix: string + editor.id = convert(parameters[0].i64, uint64) + block: + let p0 = cast[ptr UncheckedArray[char]](memory[parameters[1].i32].addr) + move = newString(parameters[2].i32) + for i0 in 0 ..< move.len: + move[i0] = p0[i0] + count = convert(parameters[3].i32, int32) + block: + let p0 = cast[ptr UncheckedArray[char]](memory[parameters[4].i32].addr) + prefix = newString(parameters[5].i32) + for i0 in 0 ..< prefix.len: + prefix[i0] = p0[i0] + block: + let p0 = cast[ptr UncheckedArray[char]](memory[parameters[6].i32].addr) + suffix = newString(parameters[7].i32) + for i0 in 0 ..< suffix.len: + suffix[i0] = p0[i0] + let res = textEditorSetSearchQueryFromMove(instance, editor, move, + count, prefix, suffix) + let retArea = parameters[^1].i32 + cast[ptr int32](memory[retArea + 0].addr)[] = res.first.line + cast[ptr int32](memory[retArea + 4].addr)[] = res.first.column + cast[ptr int32](memory[retArea + 8].addr)[] = res.last.line + cast[ptr int32](memory[retArea + 12].addr)[] = res.last.column + if e.isErr: + return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype([WasmValkind.I64, WasmValkind.I32, + WasmValkind.I32, WasmValkind.I32, WasmValkind.I32, WasmValkind.I32, + WasmValkind.I32, WasmValkind.I32], [WasmValkind.I32]) + linker.defineFuncUnchecked("nev:plugins/text-editor", "set-search-query", + ty): + var instance = cast[ptr InstanceData](store.getData()) + var mainMemory = caller.getExport("memory") + if mainMemory.isNone: + mainMemory = instance.getMemoryFor(caller) + var memory: ptr UncheckedArray[uint8] = nil + if mainMemory.get.kind == WASMTIME_EXTERN_SHAREDMEMORY: + memory = cast[ptr UncheckedArray[uint8]](data( + mainMemory.get.of_field.sharedmemory)) + elif mainMemory.get.kind == WASMTIME_EXTERN_MEMORY: + memory = cast[ptr UncheckedArray[uint8]](store.data( + mainMemory.get.of_field.memory.addr)) + else: + assert false + var editor: TextEditor + var query: string + var escapeRegex: bool + var prefix: string + var suffix: string + editor.id = convert(parameters[0].i64, uint64) + block: + let p0 = cast[ptr UncheckedArray[char]](memory[parameters[1].i32].addr) + query = newString(parameters[2].i32) + for i0 in 0 ..< query.len: + query[i0] = p0[i0] + escapeRegex = parameters[3].i32.bool + block: + let p0 = cast[ptr UncheckedArray[char]](memory[parameters[4].i32].addr) + prefix = newString(parameters[5].i32) + for i0 in 0 ..< prefix.len: + prefix[i0] = p0[i0] + block: + let p0 = cast[ptr UncheckedArray[char]](memory[parameters[6].i32].addr) + suffix = newString(parameters[7].i32) + for i0 in 0 ..< suffix.len: + suffix[i0] = p0[i0] + let res = textEditorSetSearchQuery(instance, editor, query, escapeRegex, + prefix, suffix) + parameters[0].i32 = cast[int32](res) + if e.isErr: + return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype( + [WasmValkind.I64, WasmValkind.I32], []) + linker.defineFuncUnchecked("nev:plugins/text-editor", "get-search-query", + ty): + var instance = cast[ptr InstanceData](store.getData()) + var mainMemory = caller.getExport("memory") + if mainMemory.isNone: + mainMemory = instance.getMemoryFor(caller) + var memory: ptr UncheckedArray[uint8] = nil + if mainMemory.get.kind == WASMTIME_EXTERN_SHAREDMEMORY: + memory = cast[ptr UncheckedArray[uint8]](data( + mainMemory.get.of_field.sharedmemory)) + elif mainMemory.get.kind == WASMTIME_EXTERN_MEMORY: + memory = cast[ptr UncheckedArray[uint8]](store.data( + mainMemory.get.of_field.memory.addr)) + else: + assert false + let stackAllocFunc = caller.getExport("mem_stack_alloc").get.of_field.func_field + var editor: TextEditor + editor.id = convert(parameters[0].i64, uint64) + let res = textEditorGetSearchQuery(instance, editor) + let retArea = parameters[^1].i32 + if res.len > 0: + let dataPtrWasm0 = int32(?stackAlloc(stackAllocFunc, store, + (res.len * 1).int32, 4)) + cast[ptr int32](memory[retArea + 0].addr)[] = cast[int32](dataPtrWasm0) + block: + for i0 in 0 ..< res.len: + memory[dataPtrWasm0 + i0] = cast[uint8](res[i0]) + else: + cast[ptr int32](memory[retArea + 0].addr)[] = 0.int32 + cast[ptr int32](memory[retArea + 4].addr)[] = cast[int32](res.len) + if e.isErr: + return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype([WasmValkind.I64, WasmValkind.I32, + WasmValkind.I32, WasmValkind.I32, WasmValkind.I32, WasmValkind.I32, + WasmValkind.I32, WasmValkind.I32, WasmValkind.I32, WasmValkind.I32, + WasmValkind.I32], []) + linker.defineFuncUnchecked("nev:plugins/text-editor", "apply-move", ty): + var instance = cast[ptr InstanceData](store.getData()) + var mainMemory = caller.getExport("memory") + if mainMemory.isNone: + mainMemory = instance.getMemoryFor(caller) + var memory: ptr UncheckedArray[uint8] = nil + if mainMemory.get.kind == WASMTIME_EXTERN_SHAREDMEMORY: + memory = cast[ptr UncheckedArray[uint8]](data( + mainMemory.get.of_field.sharedmemory)) + elif mainMemory.get.kind == WASMTIME_EXTERN_MEMORY: + memory = cast[ptr UncheckedArray[uint8]](store.data( + mainMemory.get.of_field.memory.addr)) + else: + assert false + let stackAllocFunc = caller.getExport("mem_stack_alloc").get.of_field.func_field + var editor: TextEditor + var selection: Selection + var move: string + var count: int32 + var wrap: bool + var includeEol: bool + editor.id = convert(parameters[0].i64, uint64) + selection.first.line = convert(parameters[1].i32, int32) + selection.first.column = convert(parameters[2].i32, int32) + selection.last.line = convert(parameters[3].i32, int32) + selection.last.column = convert(parameters[4].i32, int32) + block: + let p0 = cast[ptr UncheckedArray[char]](memory[parameters[5].i32].addr) + move = newString(parameters[6].i32) + for i0 in 0 ..< move.len: + move[i0] = p0[i0] + count = convert(parameters[7].i32, int32) + wrap = parameters[8].i32.bool + includeEol = parameters[9].i32.bool + let res = textEditorApplyMove(instance, editor, selection, move, count, + wrap, includeEol) + let retArea = parameters[^1].i32 + if res.len > 0: + let dataPtrWasm0 = int32(?stackAlloc(stackAllocFunc, store, + (res.len * 16).int32, 4)) + cast[ptr int32](memory[retArea + 0].addr)[] = cast[int32](dataPtrWasm0) + block: + for i0 in 0 ..< res.len: + cast[ptr int32](memory[dataPtrWasm0 + i0 * 16 + 0].addr)[] = res[ + i0].first.line + cast[ptr int32](memory[dataPtrWasm0 + i0 * 16 + 4].addr)[] = res[ + i0].first.column + cast[ptr int32](memory[dataPtrWasm0 + i0 * 16 + 8].addr)[] = res[ + i0].last.line + cast[ptr int32](memory[dataPtrWasm0 + i0 * 16 + 12].addr)[] = res[ + i0].last.column + else: + cast[ptr int32](memory[retArea + 0].addr)[] = 0.int32 + cast[ptr int32](memory[retArea + 4].addr)[] = cast[int32](res.len) + if e.isErr: + return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype([WasmValkind.I64, WasmValkind.I32, + WasmValkind.I32, WasmValkind.I32, WasmValkind.I32, WasmValkind.I32, + WasmValkind.I32, WasmValkind.I32, WasmValkind.I32], []) + linker.defineFuncUnchecked("nev:plugins/text-editor", "multi-move", ty): + var instance = cast[ptr InstanceData](store.getData()) + var mainMemory = caller.getExport("memory") + if mainMemory.isNone: + mainMemory = instance.getMemoryFor(caller) + var memory: ptr UncheckedArray[uint8] = nil + if mainMemory.get.kind == WASMTIME_EXTERN_SHAREDMEMORY: + memory = cast[ptr UncheckedArray[uint8]](data( + mainMemory.get.of_field.sharedmemory)) + elif mainMemory.get.kind == WASMTIME_EXTERN_MEMORY: + memory = cast[ptr UncheckedArray[uint8]](store.data( + mainMemory.get.of_field.memory.addr)) + else: + assert false + let stackAllocFunc = caller.getExport("mem_stack_alloc").get.of_field.func_field + var editor: TextEditor + var selections: seq[Selection] + var move: string + var count: int32 + var wrap: bool + var includeEol: bool + editor.id = convert(parameters[0].i64, uint64) + block: + let p0 = cast[ptr UncheckedArray[uint8]](memory[parameters[1].i32].addr) + selections = newSeq[typeof(selections[0])](parameters[2].i32) + for i0 in 0 ..< selections.len: + selections[i0].first.line = convert( + cast[ptr int32](p0[i0 * 16 + 0].addr)[], int32) + selections[i0].first.column = convert( + cast[ptr int32](p0[i0 * 16 + 4].addr)[], int32) + selections[i0].last.line = convert( + cast[ptr int32](p0[i0 * 16 + 8].addr)[], int32) + selections[i0].last.column = convert( + cast[ptr int32](p0[i0 * 16 + 12].addr)[], int32) + block: + let p0 = cast[ptr UncheckedArray[char]](memory[parameters[3].i32].addr) + move = newString(parameters[4].i32) + for i0 in 0 ..< move.len: + move[i0] = p0[i0] + count = convert(parameters[5].i32, int32) + wrap = parameters[6].i32.bool + includeEol = parameters[7].i32.bool + let res = textEditorMultiMove(instance, editor, selections, move, count, + wrap, includeEol) + let retArea = parameters[^1].i32 + if res.len > 0: + let dataPtrWasm0 = int32(?stackAlloc(stackAllocFunc, store, + (res.len * 16).int32, 4)) + cast[ptr int32](memory[retArea + 0].addr)[] = cast[int32](dataPtrWasm0) + block: + for i0 in 0 ..< res.len: + cast[ptr int32](memory[dataPtrWasm0 + i0 * 16 + 0].addr)[] = res[ + i0].first.line + cast[ptr int32](memory[dataPtrWasm0 + i0 * 16 + 4].addr)[] = res[ + i0].first.column + cast[ptr int32](memory[dataPtrWasm0 + i0 * 16 + 8].addr)[] = res[ + i0].last.line + cast[ptr int32](memory[dataPtrWasm0 + i0 * 16 + 12].addr)[] = res[ + i0].last.column + else: + cast[ptr int32](memory[retArea + 0].addr)[] = 0.int32 + cast[ptr int32](memory[retArea + 4].addr)[] = cast[int32](res.len) + if e.isErr: + return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype([WasmValkind.I64, WasmValkind.I32, + WasmValkind.I32, WasmValkind.I32, WasmValkind.I32], []) + linker.defineFuncUnchecked("nev:plugins/text-editor", "set-selection", ty): + var instance = cast[ptr InstanceData](store.getData()) + var editor: TextEditor + var s: Selection + editor.id = convert(parameters[0].i64, uint64) + s.first.line = convert(parameters[1].i32, int32) + s.first.column = convert(parameters[2].i32, int32) + s.last.line = convert(parameters[3].i32, int32) + s.last.column = convert(parameters[4].i32, int32) + textEditorSetSelection(instance, editor, s) + if e.isErr: + return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype( + [WasmValkind.I64, WasmValkind.I32, WasmValkind.I32], []) + linker.defineFuncUnchecked("nev:plugins/text-editor", "set-selections", ty): + var instance = cast[ptr InstanceData](store.getData()) + var mainMemory = caller.getExport("memory") + if mainMemory.isNone: + mainMemory = instance.getMemoryFor(caller) + var memory: ptr UncheckedArray[uint8] = nil + if mainMemory.get.kind == WASMTIME_EXTERN_SHAREDMEMORY: + memory = cast[ptr UncheckedArray[uint8]](data( + mainMemory.get.of_field.sharedmemory)) + elif mainMemory.get.kind == WASMTIME_EXTERN_MEMORY: + memory = cast[ptr UncheckedArray[uint8]](store.data( + mainMemory.get.of_field.memory.addr)) + else: + assert false + var editor: TextEditor + var s: seq[Selection] + editor.id = convert(parameters[0].i64, uint64) + block: + let p0 = cast[ptr UncheckedArray[uint8]](memory[parameters[1].i32].addr) + s = newSeq[typeof(s[0])](parameters[2].i32) + for i0 in 0 ..< s.len: + s[i0].first.line = convert(cast[ptr int32](p0[i0 * 16 + 0].addr)[], + int32) + s[i0].first.column = convert( + cast[ptr int32](p0[i0 * 16 + 4].addr)[], int32) + s[i0].last.line = convert(cast[ptr int32](p0[i0 * 16 + 8].addr)[], + int32) + s[i0].last.column = convert(cast[ptr int32](p0[i0 * 16 + 12].addr)[], + int32) + textEditorSetSelections(instance, editor, s) + if e.isErr: + return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype( + [WasmValkind.I64, WasmValkind.I32], []) + linker.defineFuncUnchecked("nev:plugins/text-editor", "get-selection", ty): + var instance = cast[ptr InstanceData](store.getData()) + var mainMemory = caller.getExport("memory") + if mainMemory.isNone: + mainMemory = instance.getMemoryFor(caller) + var memory: ptr UncheckedArray[uint8] = nil + if mainMemory.get.kind == WASMTIME_EXTERN_SHAREDMEMORY: + memory = cast[ptr UncheckedArray[uint8]](data( + mainMemory.get.of_field.sharedmemory)) + elif mainMemory.get.kind == WASMTIME_EXTERN_MEMORY: + memory = cast[ptr UncheckedArray[uint8]](store.data( + mainMemory.get.of_field.memory.addr)) + else: + assert false + var editor: TextEditor + editor.id = convert(parameters[0].i64, uint64) + let res = textEditorGetSelection(instance, editor) + let retArea = parameters[^1].i32 + cast[ptr int32](memory[retArea + 0].addr)[] = res.first.line + cast[ptr int32](memory[retArea + 4].addr)[] = res.first.column + cast[ptr int32](memory[retArea + 8].addr)[] = res.last.line + cast[ptr int32](memory[retArea + 12].addr)[] = res.last.column + if e.isErr: + return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype( + [WasmValkind.I64, WasmValkind.I32], []) + linker.defineFuncUnchecked("nev:plugins/text-editor", "get-selections", ty): + var instance = cast[ptr InstanceData](store.getData()) + var mainMemory = caller.getExport("memory") + if mainMemory.isNone: + mainMemory = instance.getMemoryFor(caller) + var memory: ptr UncheckedArray[uint8] = nil + if mainMemory.get.kind == WASMTIME_EXTERN_SHAREDMEMORY: + memory = cast[ptr UncheckedArray[uint8]](data( + mainMemory.get.of_field.sharedmemory)) + elif mainMemory.get.kind == WASMTIME_EXTERN_MEMORY: + memory = cast[ptr UncheckedArray[uint8]](store.data( + mainMemory.get.of_field.memory.addr)) + else: + assert false + let stackAllocFunc = caller.getExport("mem_stack_alloc").get.of_field.func_field + var editor: TextEditor + editor.id = convert(parameters[0].i64, uint64) + let res = textEditorGetSelections(instance, editor) + let retArea = parameters[^1].i32 + if res.len > 0: + let dataPtrWasm0 = int32(?stackAlloc(stackAllocFunc, store, + (res.len * 16).int32, 4)) + cast[ptr int32](memory[retArea + 0].addr)[] = cast[int32](dataPtrWasm0) + block: + for i0 in 0 ..< res.len: + cast[ptr int32](memory[dataPtrWasm0 + i0 * 16 + 0].addr)[] = res[ + i0].first.line + cast[ptr int32](memory[dataPtrWasm0 + i0 * 16 + 4].addr)[] = res[ + i0].first.column + cast[ptr int32](memory[dataPtrWasm0 + i0 * 16 + 8].addr)[] = res[ + i0].last.line + cast[ptr int32](memory[dataPtrWasm0 + i0 * 16 + 12].addr)[] = res[ + i0].last.column + else: + cast[ptr int32](memory[retArea + 0].addr)[] = 0.int32 + cast[ptr int32](memory[retArea + 4].addr)[] = cast[int32](res.len) + if e.isErr: + return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype( + [WasmValkind.I64, WasmValkind.I32], [WasmValkind.I32]) + linker.defineFuncUnchecked("nev:plugins/text-editor", "line-length", ty): + var instance = cast[ptr InstanceData](store.getData()) + var editor: TextEditor + var line: int32 + editor.id = convert(parameters[0].i64, uint64) + line = convert(parameters[1].i32, int32) + let res = textEditorLineLength(instance, editor, line) + parameters[0].i32 = cast[int32](res) + if e.isErr: + return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype([WasmValkind.I32], + [WasmValkind.I32]) + linker.defineFuncUnchecked("nev:plugins/text-editor", + "add-mode-changed-handler", ty): + var instance = cast[ptr InstanceData](store.getData()) + var fun: uint32 + fun = convert(parameters[0].i32, uint32) + let res = textEditorAddModeChangedHandler(instance, fun) + parameters[0].i32 = cast[int32](res) + if e.isErr: + return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype( + [WasmValkind.I64, WasmValkind.I32, WasmValkind.I32, WasmValkind.I32], + []) + linker.defineFuncUnchecked("nev:plugins/text-editor", "get-setting-raw", + ty): + var instance = cast[ptr InstanceData](store.getData()) + var mainMemory = caller.getExport("memory") + if mainMemory.isNone: + mainMemory = instance.getMemoryFor(caller) + var memory: ptr UncheckedArray[uint8] = nil + if mainMemory.get.kind == WASMTIME_EXTERN_SHAREDMEMORY: + memory = cast[ptr UncheckedArray[uint8]](data( + mainMemory.get.of_field.sharedmemory)) + elif mainMemory.get.kind == WASMTIME_EXTERN_MEMORY: + memory = cast[ptr UncheckedArray[uint8]](store.data( + mainMemory.get.of_field.memory.addr)) + else: + assert false + let stackAllocFunc = caller.getExport("mem_stack_alloc").get.of_field.func_field + var editor: TextEditor + var name: string + editor.id = convert(parameters[0].i64, uint64) + block: + let p0 = cast[ptr UncheckedArray[char]](memory[parameters[1].i32].addr) + name = newString(parameters[2].i32) + for i0 in 0 ..< name.len: + name[i0] = p0[i0] + let res = textEditorGetSettingRaw(instance, editor, name) + let retArea = parameters[^1].i32 + if res.len > 0: + let dataPtrWasm0 = int32(?stackAlloc(stackAllocFunc, store, + (res.len * 1).int32, 4)) + cast[ptr int32](memory[retArea + 0].addr)[] = cast[int32](dataPtrWasm0) + block: + for i0 in 0 ..< res.len: + memory[dataPtrWasm0 + i0] = cast[uint8](res[i0]) + else: + cast[ptr int32](memory[retArea + 0].addr)[] = 0.int32 + cast[ptr int32](memory[retArea + 4].addr)[] = cast[int32](res.len) + if e.isErr: + return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype([WasmValkind.I64, WasmValkind.I32, + WasmValkind.I32, WasmValkind.I32, WasmValkind.I32], []) + linker.defineFuncUnchecked("nev:plugins/text-editor", "set-setting-raw", + ty): + var instance = cast[ptr InstanceData](store.getData()) + var mainMemory = caller.getExport("memory") + if mainMemory.isNone: + mainMemory = instance.getMemoryFor(caller) + var memory: ptr UncheckedArray[uint8] = nil + if mainMemory.get.kind == WASMTIME_EXTERN_SHAREDMEMORY: + memory = cast[ptr UncheckedArray[uint8]](data( + mainMemory.get.of_field.sharedmemory)) + elif mainMemory.get.kind == WASMTIME_EXTERN_MEMORY: + memory = cast[ptr UncheckedArray[uint8]](store.data( + mainMemory.get.of_field.memory.addr)) + else: + assert false + var editor: TextEditor + var name: string + var value: string + editor.id = convert(parameters[0].i64, uint64) + block: + let p0 = cast[ptr UncheckedArray[char]](memory[parameters[1].i32].addr) + name = newString(parameters[2].i32) + for i0 in 0 ..< name.len: + name[i0] = p0[i0] + block: + let p0 = cast[ptr UncheckedArray[char]](memory[parameters[3].i32].addr) + value = newString(parameters[4].i32) + for i0 in 0 ..< value.len: + value[i0] = p0[i0] + textEditorSetSettingRaw(instance, editor, name, value) + if e.isErr: + return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype([WasmValkind.I64, WasmValkind.I32, + WasmValkind.I32, WasmValkind.I32, WasmValkind.I32, WasmValkind.I32, + WasmValkind.I32, WasmValkind.I32, WasmValkind.I32], []) + linker.defineFuncUnchecked("nev:plugins/text-editor", + "evaluate-expressions", ty): + var instance = cast[ptr InstanceData](store.getData()) + var mainMemory = caller.getExport("memory") + if mainMemory.isNone: + mainMemory = instance.getMemoryFor(caller) + var memory: ptr UncheckedArray[uint8] = nil + if mainMemory.get.kind == WASMTIME_EXTERN_SHAREDMEMORY: + memory = cast[ptr UncheckedArray[uint8]](data( + mainMemory.get.of_field.sharedmemory)) + elif mainMemory.get.kind == WASMTIME_EXTERN_MEMORY: + memory = cast[ptr UncheckedArray[uint8]](store.data( + mainMemory.get.of_field.memory.addr)) + else: + assert false + var editor: TextEditor + var selections: seq[Selection] + var inclusive: bool + var prefix: string + var suffix: string + var addSelectionIndex: bool + editor.id = convert(parameters[0].i64, uint64) + block: + let p0 = cast[ptr UncheckedArray[uint8]](memory[parameters[1].i32].addr) + selections = newSeq[typeof(selections[0])](parameters[2].i32) + for i0 in 0 ..< selections.len: + selections[i0].first.line = convert( + cast[ptr int32](p0[i0 * 16 + 0].addr)[], int32) + selections[i0].first.column = convert( + cast[ptr int32](p0[i0 * 16 + 4].addr)[], int32) + selections[i0].last.line = convert( + cast[ptr int32](p0[i0 * 16 + 8].addr)[], int32) + selections[i0].last.column = convert( + cast[ptr int32](p0[i0 * 16 + 12].addr)[], int32) + inclusive = parameters[3].i32.bool + block: + let p0 = cast[ptr UncheckedArray[char]](memory[parameters[4].i32].addr) + prefix = newString(parameters[5].i32) + for i0 in 0 ..< prefix.len: + prefix[i0] = p0[i0] + block: + let p0 = cast[ptr UncheckedArray[char]](memory[parameters[6].i32].addr) + suffix = newString(parameters[7].i32) + for i0 in 0 ..< suffix.len: + suffix[i0] = p0[i0] + addSelectionIndex = parameters[8].i32.bool + textEditorEvaluateExpressions(instance, editor, selections, inclusive, + prefix, suffix, addSelectionIndex) + if e.isErr: + return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype( + [WasmValkind.I64, WasmValkind.I32], []) + linker.defineFuncUnchecked("nev:plugins/text-editor", "indent", ty): + var instance = cast[ptr InstanceData](store.getData()) + var editor: TextEditor + var delta: int32 + editor.id = convert(parameters[0].i64, uint64) + delta = convert(parameters[1].i32, int32) + textEditorIndent(instance, editor, delta) + if e.isErr: + return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype([WasmValkind.I64], + [WasmValkind.I32]) + linker.defineFuncUnchecked("nev:plugins/text-editor", "get-command-count", + ty): + var instance = cast[ptr InstanceData](store.getData()) + var editor: TextEditor + editor.id = convert(parameters[0].i64, uint64) + let res = textEditorGetCommandCount(instance, editor) + parameters[0].i32 = cast[int32](res) + if e.isErr: + return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype( + [WasmValkind.I64, WasmValkind.I32, WasmValkind.I32, WasmValkind.F32], + []) + linker.defineFuncUnchecked("nev:plugins/text-editor", + "set-cursor-scroll-offset", ty): + var instance = cast[ptr InstanceData](store.getData()) + var editor: TextEditor + var cursor: Cursor + var scrollOffset: float32 + editor.id = convert(parameters[0].i64, uint64) + cursor.line = convert(parameters[1].i32, int32) + cursor.column = convert(parameters[2].i32, int32) + scrollOffset = convert(parameters[3].f32, float32) + textEditorSetCursorScrollOffset(instance, editor, cursor, scrollOffset) + if e.isErr: + return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype([WasmValkind.I64], + [WasmValkind.I32]) + linker.defineFuncUnchecked("nev:plugins/text-editor", + "get-visible-line-count", ty): + var instance = cast[ptr InstanceData](store.getData()) + var editor: TextEditor + editor.id = convert(parameters[0].i64, uint64) + let res = textEditorGetVisibleLineCount(instance, editor) + parameters[0].i32 = cast[int32](res) + if e.isErr: + return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype( + [WasmValkind.I64, WasmValkind.I32, WasmValkind.I32, WasmValkind.I32], + []) + linker.defineFuncUnchecked("nev:plugins/text-editor", "create-anchors", ty): + var instance = cast[ptr InstanceData](store.getData()) + var mainMemory = caller.getExport("memory") + if mainMemory.isNone: + mainMemory = instance.getMemoryFor(caller) + var memory: ptr UncheckedArray[uint8] = nil + if mainMemory.get.kind == WASMTIME_EXTERN_SHAREDMEMORY: + memory = cast[ptr UncheckedArray[uint8]](data( + mainMemory.get.of_field.sharedmemory)) + elif mainMemory.get.kind == WASMTIME_EXTERN_MEMORY: + memory = cast[ptr UncheckedArray[uint8]](store.data( + mainMemory.get.of_field.memory.addr)) + else: + assert false + let stackAllocFunc = caller.getExport("mem_stack_alloc").get.of_field.func_field var editor: TextEditor - var s: Selection + var selections: seq[Selection] editor.id = convert(parameters[0].i64, uint64) - s.first.line = convert(parameters[1].i32, int32) - s.first.column = convert(parameters[2].i32, int32) - s.last.line = convert(parameters[3].i32, int32) - s.last.column = convert(parameters[4].i32, int32) - textEditorSetSelection(instance, editor, s) + block: + let p0 = cast[ptr UncheckedArray[uint8]](memory[parameters[1].i32].addr) + selections = newSeq[typeof(selections[0])](parameters[2].i32) + for i0 in 0 ..< selections.len: + selections[i0].first.line = convert( + cast[ptr int32](p0[i0 * 16 + 0].addr)[], int32) + selections[i0].first.column = convert( + cast[ptr int32](p0[i0 * 16 + 4].addr)[], int32) + selections[i0].last.line = convert( + cast[ptr int32](p0[i0 * 16 + 8].addr)[], int32) + selections[i0].last.column = convert( + cast[ptr int32](p0[i0 * 16 + 12].addr)[], int32) + let res = textEditorCreateAnchors(instance, editor, selections) + let retArea = parameters[^1].i32 + if res.len > 0: + let dataPtrWasm0 = int32(?stackAlloc(stackAllocFunc, store, + (res.len * 28).int32, 4)) + cast[ptr int32](memory[retArea + 0].addr)[] = cast[int32](dataPtrWasm0) + block: + for i0 in 0 ..< res.len: + cast[ptr uint16](memory[dataPtrWasm0 + i0 * 28 + 0].addr)[] = res[ + i0][0].timestamp.replicaId + cast[ptr uint32](memory[dataPtrWasm0 + i0 * 28 + 4].addr)[] = res[ + i0][0].timestamp.value + cast[ptr uint32](memory[dataPtrWasm0 + i0 * 28 + 8].addr)[] = res[ + i0][0].offset + cast[ptr int8](memory[dataPtrWasm0 + i0 * 28 + 12].addr)[] = cast[int8](res[ + i0][0].bias) + cast[ptr uint16](memory[dataPtrWasm0 + i0 * 28 + 14].addr)[] = res[ + i0][1].timestamp.replicaId + cast[ptr uint32](memory[dataPtrWasm0 + i0 * 28 + 16].addr)[] = res[ + i0][1].timestamp.value + cast[ptr uint32](memory[dataPtrWasm0 + i0 * 28 + 20].addr)[] = res[ + i0][1].offset + cast[ptr int8](memory[dataPtrWasm0 + i0 * 28 + 24].addr)[] = cast[int8](res[ + i0][1].bias) + else: + cast[ptr int32](memory[retArea + 0].addr)[] = 0.int32 + cast[ptr int32](memory[retArea + 4].addr)[] = cast[int32](res.len) if e.isErr: return e block: let e = block: var ty: ptr WasmFunctypeT = newFunctype( - [WasmValkind.I64, WasmValkind.I32], []) - linker.defineFuncUnchecked("nev:plugins/text-editor", "get-selection", ty): + [WasmValkind.I64, WasmValkind.I32, WasmValkind.I32, WasmValkind.I32], + []) + linker.defineFuncUnchecked("nev:plugins/text-editor", "resolve-anchors", + ty): var instance = cast[ptr InstanceData](store.getData()) var mainMemory = caller.getExport("memory") if mainMemory.isNone: @@ -1212,34 +2734,54 @@ proc defineComponent*(linker: ptr LinkerT): WasmtimeResult[void] = mainMemory.get.of_field.memory.addr)) else: assert false + let stackAllocFunc = caller.getExport("mem_stack_alloc").get.of_field.func_field var editor: TextEditor + var anchors: seq[(Anchor, Anchor)] editor.id = convert(parameters[0].i64, uint64) - let res = textEditorGetSelection(instance, editor) + block: + let p0 = cast[ptr UncheckedArray[uint8]](memory[parameters[1].i32].addr) + anchors = newSeq[typeof(anchors[0])](parameters[2].i32) + for i0 in 0 ..< anchors.len: + anchors[i0][0].timestamp.replicaId = convert( + cast[ptr uint16](p0[i0 * 28 + 0].addr)[], uint16) + anchors[i0][0].timestamp.value = convert( + cast[ptr uint32](p0[i0 * 28 + 4].addr)[], uint32) + anchors[i0][0].offset = convert( + cast[ptr uint32](p0[i0 * 28 + 8].addr)[], uint32) + anchors[i0][0].bias = cast[Bias](cast[ptr int8](p0[i0 * 28 + 12].addr)[]) + anchors[i0][1].timestamp.replicaId = convert( + cast[ptr uint16](p0[i0 * 28 + 14].addr)[], uint16) + anchors[i0][1].timestamp.value = convert( + cast[ptr uint32](p0[i0 * 28 + 16].addr)[], uint32) + anchors[i0][1].offset = convert( + cast[ptr uint32](p0[i0 * 28 + 20].addr)[], uint32) + anchors[i0][1].bias = cast[Bias](cast[ptr int8](p0[i0 * 28 + 24].addr)[]) + let res = textEditorResolveAnchors(instance, editor, anchors) let retArea = parameters[^1].i32 - cast[ptr int32](memory[retArea + 0].addr)[] = res.first.line - cast[ptr int32](memory[retArea + 4].addr)[] = res.first.column - cast[ptr int32](memory[retArea + 8].addr)[] = res.last.line - cast[ptr int32](memory[retArea + 12].addr)[] = res.last.column - if e.isErr: - return e - block: - let e = block: - var ty: ptr WasmFunctypeT = newFunctype([WasmValkind.I32], - [WasmValkind.I32]) - linker.defineFuncUnchecked("nev:plugins/text-editor", - "add-mode-changed-handler", ty): - var instance = cast[ptr InstanceData](store.getData()) - var fun: uint32 - fun = convert(parameters[0].i32, uint32) - let res = textEditorAddModeChangedHandler(instance, fun) - parameters[0].i32 = cast[int32](res) + if res.len > 0: + let dataPtrWasm0 = int32(?stackAlloc(stackAllocFunc, store, + (res.len * 16).int32, 4)) + cast[ptr int32](memory[retArea + 0].addr)[] = cast[int32](dataPtrWasm0) + block: + for i0 in 0 ..< res.len: + cast[ptr int32](memory[dataPtrWasm0 + i0 * 16 + 0].addr)[] = res[ + i0].first.line + cast[ptr int32](memory[dataPtrWasm0 + i0 * 16 + 4].addr)[] = res[ + i0].first.column + cast[ptr int32](memory[dataPtrWasm0 + i0 * 16 + 8].addr)[] = res[ + i0].last.line + cast[ptr int32](memory[dataPtrWasm0 + i0 * 16 + 12].addr)[] = res[ + i0].last.column + else: + cast[ptr int32](memory[retArea + 0].addr)[] = 0.int32 + cast[ptr int32](memory[retArea + 4].addr)[] = cast[int32](res.len) if e.isErr: return e block: let e = block: var ty: ptr WasmFunctypeT = newFunctype([WasmValkind.I64, WasmValkind.I32, - WasmValkind.I32, WasmValkind.I32, WasmValkind.I32, WasmValkind.I32], - []) + WasmValkind.I32, WasmValkind.I32, WasmValkind.I32, WasmValkind.I32, + WasmValkind.I32], []) linker.defineFuncUnchecked("nev:plugins/text-editor", "edit", ty): var instance = cast[ptr InstanceData](store.getData()) var mainMemory = caller.getExport("memory") @@ -1258,6 +2800,7 @@ proc defineComponent*(linker: ptr LinkerT): WasmtimeResult[void] = var editor: TextEditor var selections: seq[Selection] var contents: seq[string] + var inclusive: bool editor.id = convert(parameters[0].i64, uint64) block: let p0 = cast[ptr UncheckedArray[uint8]](memory[parameters[1].i32].addr) @@ -1281,7 +2824,9 @@ proc defineComponent*(linker: ptr LinkerT): WasmtimeResult[void] = contents[i0] = newString(cast[ptr int32](p0[i0 * 8 + 4].addr)[]) for i1 in 0 ..< contents[i0].len: contents[i0][i1] = p1[i1] - let res = textEditorEdit(instance, editor, selections, contents) + inclusive = parameters[5].i32.bool + let res = textEditorEdit(instance, editor, selections, contents, + inclusive) let retArea = parameters[^1].i32 if res.len > 0: let dataPtrWasm0 = int32(?stackAlloc(stackAllocFunc, store, @@ -1302,6 +2847,38 @@ proc defineComponent*(linker: ptr LinkerT): WasmtimeResult[void] = cast[ptr int32](memory[retArea + 4].addr)[] = cast[int32](res.len) if e.isErr: return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype( + [WasmValkind.I32, WasmValkind.I32, WasmValkind.I32, WasmValkind.I32], + []) + linker.defineFuncUnchecked("nev:plugins/text-editor", "define-move", ty): + var instance = cast[ptr InstanceData](store.getData()) + var mainMemory = caller.getExport("memory") + if mainMemory.isNone: + mainMemory = instance.getMemoryFor(caller) + var memory: ptr UncheckedArray[uint8] = nil + if mainMemory.get.kind == WASMTIME_EXTERN_SHAREDMEMORY: + memory = cast[ptr UncheckedArray[uint8]](data( + mainMemory.get.of_field.sharedmemory)) + elif mainMemory.get.kind == WASMTIME_EXTERN_MEMORY: + memory = cast[ptr UncheckedArray[uint8]](store.data( + mainMemory.get.of_field.memory.addr)) + else: + assert false + var move: string + var fun: uint32 + var data: uint32 + block: + let p0 = cast[ptr UncheckedArray[char]](memory[parameters[0].i32].addr) + move = newString(parameters[1].i32) + for i0 in 0 ..< move.len: + move[i0] = p0[i0] + fun = convert(parameters[2].i32, uint32) + data = convert(parameters[3].i32, uint32) + textEditorDefineMove(instance, move, fun, data) + if e.isErr: + return e block: let e = block: var ty: ptr WasmFunctypeT = newFunctype([WasmValkind.I64], @@ -1401,6 +2978,19 @@ proc defineComponent*(linker: ptr LinkerT): WasmtimeResult[void] = layoutFocus(instance, slot) if e.isErr: return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype( + [WasmValkind.I32, WasmValkind.I32], []) + linker.defineFuncUnchecked("nev:plugins/layout", "close-active-view", ty): + var instance = cast[ptr InstanceData](store.getData()) + var closeOpenPopup: bool + var restoreHidden: bool + closeOpenPopup = parameters[0].i32.bool + restoreHidden = parameters[1].i32.bool + layoutCloseActiveView(instance, closeOpenPopup, restoreHidden) + if e.isErr: + return e block: let e = block: var ty: ptr WasmFunctypeT = newFunctype([], [WasmValkind.I32]) @@ -2755,3 +4345,200 @@ proc defineComponent*(linker: ptr LinkerT): WasmtimeResult[void] = parameters[0].i32 = ?instance.resources.resourceNew(store, res) if e.isErr: return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype([], [WasmValkind.I32]) + linker.defineFuncUnchecked("nev:plugins/registers", + "is-replaying-commands", ty): + var instance = cast[ptr InstanceData](store.getData()) + let res = registersIsReplayingCommands(instance) + parameters[0].i32 = cast[int32](res) + if e.isErr: + return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype( + [WasmValkind.I32, WasmValkind.I32], [WasmValkind.I32]) + linker.defineFuncUnchecked("nev:plugins/registers", + "is-recording-commands", ty): + var instance = cast[ptr InstanceData](store.getData()) + var mainMemory = caller.getExport("memory") + if mainMemory.isNone: + mainMemory = instance.getMemoryFor(caller) + var memory: ptr UncheckedArray[uint8] = nil + if mainMemory.get.kind == WASMTIME_EXTERN_SHAREDMEMORY: + memory = cast[ptr UncheckedArray[uint8]](data( + mainMemory.get.of_field.sharedmemory)) + elif mainMemory.get.kind == WASMTIME_EXTERN_MEMORY: + memory = cast[ptr UncheckedArray[uint8]](store.data( + mainMemory.get.of_field.memory.addr)) + else: + assert false + var register: string + block: + let p0 = cast[ptr UncheckedArray[char]](memory[parameters[0].i32].addr) + register = newString(parameters[1].i32) + for i0 in 0 ..< register.len: + register[i0] = p0[i0] + let res = registersIsRecordingCommands(instance, register) + parameters[0].i32 = cast[int32](res) + if e.isErr: + return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype( + [WasmValkind.I32, WasmValkind.I32, WasmValkind.I32, WasmValkind.I32], + []) + linker.defineFuncUnchecked("nev:plugins/registers", "set-register-text", + ty): + var instance = cast[ptr InstanceData](store.getData()) + var mainMemory = caller.getExport("memory") + if mainMemory.isNone: + mainMemory = instance.getMemoryFor(caller) + var memory: ptr UncheckedArray[uint8] = nil + if mainMemory.get.kind == WASMTIME_EXTERN_SHAREDMEMORY: + memory = cast[ptr UncheckedArray[uint8]](data( + mainMemory.get.of_field.sharedmemory)) + elif mainMemory.get.kind == WASMTIME_EXTERN_MEMORY: + memory = cast[ptr UncheckedArray[uint8]](store.data( + mainMemory.get.of_field.memory.addr)) + else: + assert false + var text: string + var register: string + block: + let p0 = cast[ptr UncheckedArray[char]](memory[parameters[0].i32].addr) + text = newString(parameters[1].i32) + for i0 in 0 ..< text.len: + text[i0] = p0[i0] + block: + let p0 = cast[ptr UncheckedArray[char]](memory[parameters[2].i32].addr) + register = newString(parameters[3].i32) + for i0 in 0 ..< register.len: + register[i0] = p0[i0] + registersSetRegisterText(instance, text, register) + if e.isErr: + return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype( + [WasmValkind.I32, WasmValkind.I32, WasmValkind.I32], []) + linker.defineFuncUnchecked("nev:plugins/registers", "get-register-text", + ty): + var instance = cast[ptr InstanceData](store.getData()) + var mainMemory = caller.getExport("memory") + if mainMemory.isNone: + mainMemory = instance.getMemoryFor(caller) + var memory: ptr UncheckedArray[uint8] = nil + if mainMemory.get.kind == WASMTIME_EXTERN_SHAREDMEMORY: + memory = cast[ptr UncheckedArray[uint8]](data( + mainMemory.get.of_field.sharedmemory)) + elif mainMemory.get.kind == WASMTIME_EXTERN_MEMORY: + memory = cast[ptr UncheckedArray[uint8]](store.data( + mainMemory.get.of_field.memory.addr)) + else: + assert false + let stackAllocFunc = caller.getExport("mem_stack_alloc").get.of_field.func_field + var register: string + block: + let p0 = cast[ptr UncheckedArray[char]](memory[parameters[0].i32].addr) + register = newString(parameters[1].i32) + for i0 in 0 ..< register.len: + register[i0] = p0[i0] + let res = registersGetRegisterText(instance, register) + let retArea = parameters[^1].i32 + if res.len > 0: + let dataPtrWasm0 = int32(?stackAlloc(stackAllocFunc, store, + (res.len * 1).int32, 4)) + cast[ptr int32](memory[retArea + 0].addr)[] = cast[int32](dataPtrWasm0) + block: + for i0 in 0 ..< res.len: + memory[dataPtrWasm0 + i0] = cast[uint8](res[i0]) + else: + cast[ptr int32](memory[retArea + 0].addr)[] = 0.int32 + cast[ptr int32](memory[retArea + 4].addr)[] = cast[int32](res.len) + if e.isErr: + return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype( + [WasmValkind.I32, WasmValkind.I32], []) + linker.defineFuncUnchecked("nev:plugins/registers", + "start-recording-commands", ty): + var instance = cast[ptr InstanceData](store.getData()) + var mainMemory = caller.getExport("memory") + if mainMemory.isNone: + mainMemory = instance.getMemoryFor(caller) + var memory: ptr UncheckedArray[uint8] = nil + if mainMemory.get.kind == WASMTIME_EXTERN_SHAREDMEMORY: + memory = cast[ptr UncheckedArray[uint8]](data( + mainMemory.get.of_field.sharedmemory)) + elif mainMemory.get.kind == WASMTIME_EXTERN_MEMORY: + memory = cast[ptr UncheckedArray[uint8]](store.data( + mainMemory.get.of_field.memory.addr)) + else: + assert false + var register: string + block: + let p0 = cast[ptr UncheckedArray[char]](memory[parameters[0].i32].addr) + register = newString(parameters[1].i32) + for i0 in 0 ..< register.len: + register[i0] = p0[i0] + registersStartRecordingCommands(instance, register) + if e.isErr: + return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype( + [WasmValkind.I32, WasmValkind.I32], []) + linker.defineFuncUnchecked("nev:plugins/registers", + "stop-recording-commands", ty): + var instance = cast[ptr InstanceData](store.getData()) + var mainMemory = caller.getExport("memory") + if mainMemory.isNone: + mainMemory = instance.getMemoryFor(caller) + var memory: ptr UncheckedArray[uint8] = nil + if mainMemory.get.kind == WASMTIME_EXTERN_SHAREDMEMORY: + memory = cast[ptr UncheckedArray[uint8]](data( + mainMemory.get.of_field.sharedmemory)) + elif mainMemory.get.kind == WASMTIME_EXTERN_MEMORY: + memory = cast[ptr UncheckedArray[uint8]](store.data( + mainMemory.get.of_field.memory.addr)) + else: + assert false + var register: string + block: + let p0 = cast[ptr UncheckedArray[char]](memory[parameters[0].i32].addr) + register = newString(parameters[1].i32) + for i0 in 0 ..< register.len: + register[i0] = p0[i0] + registersStopRecordingCommands(instance, register) + if e.isErr: + return e + block: + let e = block: + var ty: ptr WasmFunctypeT = newFunctype( + [WasmValkind.I32, WasmValkind.I32], []) + linker.defineFuncUnchecked("nev:plugins/registers", "replay-commands", ty): + var instance = cast[ptr InstanceData](store.getData()) + var mainMemory = caller.getExport("memory") + if mainMemory.isNone: + mainMemory = instance.getMemoryFor(caller) + var memory: ptr UncheckedArray[uint8] = nil + if mainMemory.get.kind == WASMTIME_EXTERN_SHAREDMEMORY: + memory = cast[ptr UncheckedArray[uint8]](data( + mainMemory.get.of_field.sharedmemory)) + elif mainMemory.get.kind == WASMTIME_EXTERN_MEMORY: + memory = cast[ptr UncheckedArray[uint8]](store.data( + mainMemory.get.of_field.memory.addr)) + else: + assert false + var register: string + block: + let p0 = cast[ptr UncheckedArray[char]](memory[parameters[0].i32].addr) + register = newString(parameters[1].i32) + for i0 in 0 ..< register.len: + register[i0] = p0[i0] + registersReplayCommands(instance, register) + if e.isErr: + return e diff --git a/src/input.nim b/src/input.nim index 7025b81e9..04f36061b 100644 --- a/src/input.nim +++ b/src/input.nim @@ -10,9 +10,11 @@ export input_api logCategory "input" type + CaptureFlags = enum None, Char, Any Transition = object state: int capture: string + captureFlags: CaptureFlags functionIndices: BitSet function: string @@ -48,6 +50,7 @@ type Left, Middle, Right, DoubleClick, TripleClick, Unknown proc inputToString*(input: int64, modifiers: Modifiers = {}): string +proc inputToCharString*(input: int64, modifiers: Modifiers = {}): string let capturePattern = re"<(.*?)>" proc fillCaptures(dfa: CommandDFA, state: CommandState, args: string): string = @@ -122,7 +125,13 @@ proc stepInput(dfa: CommandDFA, state: CommandState, currentInput: int64, mods: var newState = state newState.current = transition.state newState.functionIndices.bitSetIntersect transition.functionIndices - newState.captures.mgetOrPut(transition.capture, "").add(inputToString(currentInput, mods)) + let captureText = case transition.captureFlags + of None, Any: + inputToString(currentInput, mods) + of Char: + inputToCharString(currentInput, mods) + + newState.captures.mgetOrPut(transition.capture, "").add(captureText) if dfa.states[transition.state].transitions.len > 0 or dfa.states[transition.state].epsilonTransitions.len == 0: result.add newState @@ -292,7 +301,25 @@ proc inputToString*(inputs: Slice[int64], modifiers: Modifiers = {}): string = if special: result.add ">" -proc linkStates(dfa: var CommandDFA, currentState: int, nextState: int, inputCodes: Slice[int64], mods: Modifiers, functionIndex: int, capture: string): bool = +proc inputToCharString*(input: int64, modifiers: Modifiers = {}): string = + if modifiers != {} and modifiers != {Shift}: + return inputToString(input, modifiers) + case input + of INPUT_SPACE: + return " " + of INPUT_ENTER: + return "\n" + of INPUT_TAB: + return "\t" + else: + if input <= 0: + return inputToString(input, modifiers) + else: + result = $input.Rune + if Shift in modifiers: + result = result.toUpper + +proc linkStates(dfa: var CommandDFA, currentState: int, nextState: int, inputCodes: Slice[int64], mods: Modifiers, functionIndex: int, capture: string, captureFlags: CaptureFlags): bool = if not (inputCodes in dfa.states[currentState].transitions): dfa.states[currentState].transitions[inputCodes] = DFAInput() if mods in dfa.states[currentState].transitions[inputCodes].next: @@ -304,14 +331,15 @@ proc linkStates(dfa: var CommandDFA, currentState: int, nextState: int, inputCod assert current.state == nextState assert current.capture == capture + assert current.captureFlags == captureFlags dfa.states[currentState].transitions[inputCodes].next[mods].functionIndices.bitSetIncl functionIndex return true else: # echo &"link states {currentState} -> {nextState}, {inputToString(inputCodes, mods)}, {functionIndex}, {capture}" - dfa.states[currentState].transitions[inputCodes].next[mods] = Transition(state: nextState, functionIndices: [functionIndex].toBitSet, capture: capture) + dfa.states[currentState].transitions[inputCodes].next[mods] = Transition(state: nextState, functionIndices: [functionIndex].toBitSet, capture: capture, captureFlags: captureFlags) return true -proc linkStates(dfa: var CommandDFA, currentState: int, nextState: int, functionIndex: int, capture: string, function: string) = +proc linkStates(dfa: var CommandDFA, currentState: int, nextState: int, functionIndex: int, capture: string, captureFlags: CaptureFlags, function: string) = for transition in dfa.states[currentState].epsilonTransitions.mitems: if transition.state == nextState: # echo &"link states {currentState} -> {nextState}, {functionIndex}, {capture}, {transition.function} -> {function}" @@ -320,9 +348,9 @@ proc linkStates(dfa: var CommandDFA, currentState: int, nextState: int, function transition.functionIndices.bitSetIncl functionIndex return - dfa.states[currentState].epsilonTransitions.add Transition(state: nextState, functionIndices: [functionIndex].toBitSet, capture: capture, function: function) + dfa.states[currentState].epsilonTransitions.add Transition(state: nextState, functionIndices: [functionIndex].toBitSet, capture: capture, captureFlags: captureFlags, function: function) -proc createOrUpdateState(dfa: var CommandDFA, currentState: int, inputCodes: Slice[int64], mods: Modifiers, persistent: bool, loop: bool, capture: string, functionIndex: int): Option[int] = +proc createOrUpdateState(dfa: var CommandDFA, currentState: int, inputCodes: Slice[int64], mods: Modifiers, persistent: bool, loop: bool, capture: string, captureFlags: CaptureFlags, functionIndex: int): Option[int] = let nextState = if loop: currentState elif inputCodes in dfa.states[currentState].transitions: @@ -331,7 +359,7 @@ proc createOrUpdateState(dfa: var CommandDFA, currentState: int, inputCodes: Sli else: dfa.states.add DFAState() # echo &"init states {currentState} -> {dfa.states.len-1}, {inputToString(inputCodes, mods)}, {functionIndex}, {capture}" - dfa.states[currentState].transitions[inputCodes].next[mods] = Transition(state: dfa.states.len - 1, functionIndices: [functionIndex].toBitSet, capture: capture) + dfa.states[currentState].transitions[inputCodes].next[mods] = Transition(state: dfa.states.len - 1, functionIndices: [functionIndex].toBitSet, capture: capture, captureFlags: captureFlags) dfa.states.len - 1 else: dfa.states.add DFAState() @@ -340,7 +368,7 @@ proc createOrUpdateState(dfa: var CommandDFA, currentState: int, inputCodes: Sli dfa.states[nextState].persistent = persistent # echo &"update state {nextState}, {dfa.states[nextState].capture} -> {capture}" dfa.states[nextState].capture = capture - if not linkStates(dfa, currentState, nextState, inputCodes, mods, functionIndex, capture): + if not linkStates(dfa, currentState, nextState, inputCodes, mods, functionIndex, capture, captureFlags): return int.none return nextState.some @@ -376,6 +404,7 @@ proc handleNextInput( leaders: Table[string, seq[(int64, Modifiers)]], functionIndex: int, capture = "", + captureFlags = CaptureFlags.None, depth = 0, subGraphCounts = newTable[string, int](), ): seq[int] = @@ -408,37 +437,38 @@ proc handleNextInput( subGraphCounts[inputName] = subGraphCount + 1 let subCapture = if capture.len > 0: capture & "." & inputName else: inputName + let subCaptureFlags = CaptureFlags.None # echo "| ".repeat(depth) & &"sub graph {inputName}, {subGraphCounts[]}" let subGraphKey = (inputName, capture, subGraphCount) if dfa.subGraphStates.contains(subGraphKey): # echo "| ".repeat(depth) & &"sub graph {inputName} found -> {dfa.subGraphStates[subGraphKey]}" let (nextStartState, nextEndState) = dfa.subGraphStates[subGraphKey] - dfa.linkStates(currentState, nextStartState, functionIndex, capture, "") + dfa.linkStates(currentState, nextStartState, functionIndex, capture, captureFlags, "") fillTransitionFunctionIndicesRec(dfa, nextStartState, [functionIndex].toBitSet, nextEndState) - result = handleNextInput(dfa, commands, input, function, nextIndex, nextEndState, defaultState, leaders, functionIndex, capture, depth + 1, subGraphCounts) + result = handleNextInput(dfa, commands, input, function, nextIndex, nextEndState, defaultState, leaders, functionIndex, capture, captureFlags, depth + 1, subGraphCounts) if Optional in flags: - dfa.linkStates(currentState, nextEndState, functionIndex, capture, "") + dfa.linkStates(currentState, nextEndState, functionIndex, capture, captureFlags, "") return dfa.states.add DFAState() let subState = dfa.states.len - 1 dfa.states.add DFAState() let endState = dfa.states.len - 1 - dfa.linkStates(currentState, subState, functionIndex, capture, "") + dfa.linkStates(currentState, subState, functionIndex, capture, captureFlags, "") for command in commands[inputName].pairs: let (subInput, function) = command # echo "| ".repeat(depth) & &"subInput: {subInput}, function: {function}" - let nextEndStates = handleNextInput(dfa, commands, subInput.toRunes, function, index = 0, currentState = subState, defaultState = defaultState, leaders = leaders, functionIndex, subCapture, depth + 1, subGraphCounts[].neww) + let nextEndStates = handleNextInput(dfa, commands, subInput.toRunes, function, index = 0, currentState = subState, defaultState = defaultState, leaders = leaders, functionIndex, subCapture, subCaptureFlags, depth + 1, subGraphCounts[].neww) # echo "| ".repeat(depth) & &"-> endStates: {nextEndStates}" for es in nextEndStates: - dfa.linkStates(es, endState, functionIndex, subCapture, function) + dfa.linkStates(es, endState, functionIndex, subCapture, subCaptureFlags, function) - result = handleNextInput(dfa, commands, input, function, nextIndex, endState, defaultState, leaders, functionIndex, capture, depth + 1, subGraphCounts) + result = handleNextInput(dfa, commands, input, function, nextIndex, endState, defaultState, leaders, functionIndex, capture, captureFlags, depth + 1, subGraphCounts) if Optional in flags: - dfa.linkStates(currentState, endState, functionIndex, capture, "") + dfa.linkStates(currentState, endState, functionIndex, capture, captureFlags, "") dfa.subGraphStates[subGraphKey] = (subState, endState) return @@ -461,27 +491,33 @@ proc handleNextInput( for key in keys: let nextState = if inputName == "CHAR" or inputName == "ANY": let subCapture = if capture.len > 0: capture & "." & inputName else: inputName - let nextState = createOrUpdateState(dfa, currentState, key.inputCodes, key.mods, persistent, Loop in flags, subCapture, functionIndex).getOr: + var subCaptureFlags: CaptureFlags = None + if inputName == "CHAR": + subCaptureFlags = Char + elif inputName == "ANY": + subCaptureFlags = Any + + let nextState = createOrUpdateState(dfa, currentState, key.inputCodes, key.mods, persistent, Loop in flags, subCapture, subCaptureFlags, functionIndex).getOr: log lvlError, fmt"""Ambigious keybinding '{input.join("")}' at {index} ({inputToString(key.inputCodes, key.mods)})""" continue # echo "| ".repeat(depth) & &"create next state {nextState}, {key.inputCodes}, {key.mods}, current state {currentState}" if inputName == "CHAR": - discard linkStates(dfa, currentState, nextState, key.inputCodes, {Shift}, functionIndex, subCapture) - discard linkStates(dfa, currentState, nextState, key.inputCodes, {}, functionIndex, subCapture) + discard linkStates(dfa, currentState, nextState, key.inputCodes, {Shift}, functionIndex, subCapture, subCaptureFlags) + discard linkStates(dfa, currentState, nextState, key.inputCodes, {}, functionIndex, subCapture, subCaptureFlags) - if inputName == "ANY": + elif inputName == "ANY": for modsInt in 0..pow(2.float32, Modifier.high.ord.float32).int: var mods: Modifiers = {} for i in 0.. 0: + docs.add "\n" + docs.add &"[{info.context}] {info.keys} -> {info.command}" + docs.add "\n\n" + + docs.add command.description + + completions.add CompletionItem( + label: name, + kind: CompletionKind.Function, + detail: command.signature.some, + documentation: CompletionItemDocumentationVariant.init(docs).some, + ) + else: {.gcsafe.}: for (name, command) in self.commands.commands.pairs: diff --git a/src/layout.nim b/src/layout.nim index 1036c2bcd..0eff592e8 100644 --- a/src/layout.nim +++ b/src/layout.nim @@ -687,7 +687,7 @@ proc showView*(self: LayoutService, viewId: int32, slot: string = "", focus: boo proc showEditor*(self: LayoutService, editorId: EditorId, slot: string = "", focus: bool = true) {.expose("layout").} = ## Make the given editor visible - let editor = self.editors.getEditorForId(editorId).getOr: + let editor = self.editors.getEditorForId(editorId.EditorIdNew).getOr: log lvlError, &"No editor with id {editorId} exists" return @@ -715,7 +715,7 @@ proc getOrOpenEditor*(self: LayoutService, path: string): Option[EditorId] {.exp return EditorId.none if self.editors.createEditorForDocument(document).getSome(editor): - return editor.id.some + return editor.id.EditorId.some return EditorId.none @@ -732,7 +732,7 @@ proc tryOpenExisting*(self: LayoutService, path: string, appFile: bool = false, proc tryOpenExisting*(self: LayoutService, editor: EditorId, addToHistory = true, slot: string = ""): Option[DocumentEditor] = # debugf"tryOpenExisting '{editor}'" for i, view in self.allViews: - if view of EditorView and view.EditorView.editor.id == editor: + if view of EditorView and view.EditorView.editor.id == editor.EditorIdNew: log(lvlInfo, fmt"Reusing open editor in view {i}") self.showView(view, slot = slot) return view.EditorView.editor.some diff --git a/src/libvterm/screen.c b/src/libvterm/screen.c index 09715a3ef..a22379a94 100644 --- a/src/libvterm/screen.c +++ b/src/libvterm/screen.c @@ -805,7 +805,7 @@ static int resize(int new_rows, int new_cols, VTermStateFields *fields, void *us return 1; } -static int setlineinfo(int row, const VTermLineInfo *newinfo, const VTermLineInfo *oldinfo, void *user) +static int setlineinfo(int row, VTermLineInfo *newinfo, VTermLineInfo *oldinfo, void *user) { VTermScreen *screen = user; diff --git a/src/libvterm/state.c b/src/libvterm/state.c index daa88e2b2..8357652b3 100644 --- a/src/libvterm/state.c +++ b/src/libvterm/state.c @@ -270,7 +270,7 @@ static void set_lineinfo(VTermState *state, int row, int force, int dwl, int dhl state->lineinfo[row] = info; } -static int on_text(const char bytes[], size_t len, void *user) +static int on_text(char bytes[], size_t len, void *user) { VTermState *state = user; @@ -589,7 +589,7 @@ static void savecursor(VTermState *state, int save) } } -static int on_escape(const char *bytes, size_t len, void *user) +static int on_escape(char *bytes, size_t len, void *user) { VTermState *state = user; @@ -928,7 +928,7 @@ static void request_version_string(VTermState *state) VTERM_VERSION_MAJOR, VTERM_VERSION_MINOR); } -static int on_csi(const char *leader, const long args[], int argcount, const char *intermed, char command, void *user) +static int on_csi(char *leader, long args[], int argcount, char *intermed, char command, void *user) { VTermState *state = user; int leader_byte = 0; @@ -1913,7 +1913,7 @@ static void request_status_string(VTermState *state, VTermStringFragment frag) vterm_push_output_sprintf_str(state->vt, C1_DCS, true, "0$r"); } -static int on_dcs(const char *command, size_t commandlen, VTermStringFragment frag, void *user) +static int on_dcs(char *command, size_t commandlen, VTermStringFragment frag, void *user) { VTermState *state = user; diff --git a/src/libvterm/vterm.h b/src/libvterm/vterm.h index 264ab027f..7aa90bec5 100644 --- a/src/libvterm/vterm.h +++ b/src/libvterm/vterm.h @@ -354,7 +354,7 @@ void vterm_set_utf8(VTerm *vt, int is_utf8); size_t vterm_input_write(VTerm *vt, const char *bytes, size_t len); /* Setting output callback will override the buffer logic */ -typedef void VTermOutputCallback(const char *s, size_t len, void *user); +typedef void VTermOutputCallback(char *s, size_t len, void *user); void vterm_output_set_callback(VTerm *vt, VTermOutputCallback *func, void *user); /* These buffer functions only work if output callback is NOT set @@ -402,12 +402,12 @@ int vterm_get_mouse_flags(VTerm *vt); #define CSI_ARG_COUNT(a) (CSI_ARG(a) == CSI_ARG_MISSING || CSI_ARG(a) == 0 ? 1 : CSI_ARG(a)) typedef struct { - int (*text)(const char *bytes, size_t len, void *user); + int (*text)(char *bytes, size_t len, void *user); int (*control)(unsigned char control, void *user); - int (*escape)(const char *bytes, size_t len, void *user); - int (*csi)(const char *leader, const long args[], int argcount, const char *intermed, char command, void *user); + int (*escape)(char *bytes, size_t len, void *user); + int (*csi)(char *leader, long args[], int argcount, char *intermed, char command, void *user); int (*osc)(int command, VTermStringFragment frag, void *user); - int (*dcs)(const char *command, size_t commandlen, VTermStringFragment frag, void *user); + int (*dcs)(char *command, size_t commandlen, VTermStringFragment frag, void *user); int (*apc)(VTermStringFragment frag, void *user); int (*pm)(VTermStringFragment frag, void *user); int (*sos)(VTermStringFragment frag, void *user); @@ -437,15 +437,15 @@ typedef struct { int (*settermprop)(VTermProp prop, VTermValue *val, void *user); int (*bell)(void *user); int (*resize)(int rows, int cols, VTermStateFields *fields, void *user); - int (*setlineinfo)(int row, const VTermLineInfo *newinfo, const VTermLineInfo *oldinfo, void *user); + int (*setlineinfo)(int row, VTermLineInfo *newinfo, VTermLineInfo *oldinfo, void *user); int (*sb_clear)(void *user); } VTermStateCallbacks; typedef struct { int (*control)(unsigned char control, void *user); - int (*csi)(const char *leader, const long args[], int argcount, const char *intermed, char command, void *user); + int (*csi)(char *leader, long args[], int argcount, char *intermed, char command, void *user); int (*osc)(int command, VTermStringFragment frag, void *user); - int (*dcs)(const char *command, size_t commandlen, VTermStringFragment frag, void *user); + int (*dcs)(char *command, size_t commandlen, VTermStringFragment frag, void *user); int (*apc)(VTermStringFragment frag, void *user); int (*pm)(VTermStringFragment frag, void *user); int (*sos)(VTermStringFragment frag, void *user); @@ -545,7 +545,7 @@ typedef struct { int (*settermprop)(VTermProp prop, VTermValue *val, void *user); int (*bell)(void *user); int (*resize)(int rows, int cols, void *user); - int (*sb_pushline)(int cols, const VTermScreenCell *cells, void *user); + int (*sb_pushline)(int cols, VTermScreenCell *cells, void *user); int (*sb_popline)(int cols, VTermScreenCell *cells, void *user); int (*sb_clear)(void* user); } VTermScreenCallbacks; diff --git a/src/lisp.nim b/src/lisp.nim new file mode 100644 index 000000000..f30e66ef0 --- /dev/null +++ b/src/lisp.nim @@ -0,0 +1,1118 @@ + +import std/[json, sequtils, strutils, strformat, lexbase, unicode, streams, tables, math] +import misc/[util, myjsonutils, custom_logger] + +{.push gcsafe.} + +logCategory "lisp" + +type + LispValKind* = enum + Nil, Number, Bool, Symbol, String, List, Array, Map, Func, Lambda, Macro + + Env* = ref object + parent*: Env + env*: Table[string, LispVal] + onUndefinedSymbol*: proc(env: Env, name: string): LispVal {.gcsafe, raises: [].} + + LispError* = object of CatchableError + + LispVal* = ref object + case kind*: LispValKind + of Nil: + discard + of Number: + num*: float + of Bool: + bol*: bool + of Symbol: + sym*: string + of String: + str*: string + of List, Array: + elems*: seq[LispVal] + of Map: + fields*: OrderedTable[string, LispVal] + of Func: + name*: string + evalArgs*: bool = true + fn*: proc (args: seq[LispVal]): LispVal {.gcsafe, raises: [LispError].} + of Lambda, Macro: + params*: seq[string] + body*: LispVal + env*: Env + +proc `$`*(val: LispVal): string {.raises: [].} = + if val == nil: + return "" + case val.kind + of Nil: $"nil" + of Number: + if val.num.int.float == val.num: + $val.num.int + else: + $val.num + of Bool: $val.bol + of Symbol: val.sym + of String: val.str + of List: "(" & val.elems.mapIt($it).join(" ") & ")" + of Array: "[" & val.elems.mapIt($it).join(" ") & "]" + of Map: + var res = "{" + var i = 0 + for key, val in val.fields.pairs: + if i > 0: + res.add ", " + inc i + res.add key + res.add ": " + res.add $val + res.add "} " + res + of Func: &"" + of Lambda: &"({val.params}) -> {val.body})" + of Macro: &"!({val.params}) -> {val.body})" + +proc newNil*(): LispVal = + LispVal(kind: Nil) + +proc newNumber*(n: float): LispVal = + LispVal(kind: Number, num: n) + +proc newNumber*(n: int): LispVal = + LispVal(kind: Number, num: n.float) + +proc newBool*(n: bool): LispVal = + LispVal(kind: Bool, bol: n) + +proc newSymbol*(s: string): LispVal = + LispVal(kind: Symbol, sym: s) + +proc newString*(s: string): LispVal = + LispVal(kind: String, str: s) + +proc newList*(elems: seq[LispVal] = @[]): LispVal = + LispVal(kind: List, elems: elems) + +proc newArray*(elems: seq[LispVal] = @[]): LispVal = + LispVal(kind: Array, elems: elems) + +proc newMap*(fields: OrderedTable[string, LispVal] = initOrderedTable[string, LispVal]()): LispVal = + LispVal(kind: Map, fields: fields) + +proc newFunc*(name: string, evalArgs: bool, fn: proc(args: seq[LispVal]): LispVal {.gcsafe, raises: [LispError].}): LispVal = + LispVal(kind: Func, name: name, evalArgs: evalArgs, fn: fn) + +proc newFunc*(name: string, fn: proc(args: seq[LispVal]): LispVal {.gcsafe, raises: [LispError].}): LispVal = + LispVal(kind: Func, name: name, evalArgs: true, fn: fn) + +proc newFunc*(fn: proc(args: seq[LispVal]): LispVal {.gcsafe, raises: [LispError].}): LispVal = + LispVal(kind: Func, evalArgs: true, fn: fn) + +proc newLambda*(params: seq[string], body: LispVal, env: Env): LispVal = + LispVal(kind: Lambda, params: params, body: body, env: env) + +proc newMacro*(params: seq[string], body: LispVal, env: Env): LispVal = + LispVal(kind: Macro, params: params, body: body, env: env) + +proc createChild*(env: Env): Env = + result = Env(parent: env) + +proc `[]`*(env: Env, key: string): LispVal = + env.env.withValue(key, value): + return value[] + + if env.parent != nil: + result = env.parent[key] + if result != nil: + return + + if env.onUndefinedSymbol != nil: + result = env.onUndefinedSymbol(env, key) + if result != nil: + return + + return nil + +proc `[]=`*(env: Env, key: string, val: LispVal) = + env.env[key] = val + +proc set*(env: Env, key: string, val: LispVal): bool = + env.env.withValue(key, value): + value[] = val + return true + + if env.parent != nil: + return env.parent.set(key, val) + + return false + +proc toJsonHook*(val: LispVal, opt = initToJsonOptions()): JsonNode {.raises: [].} = + case val.kind + of Nil: newJNull() + of Number: + if val.num.int.float == val.num: + newJInt(val.num.int) + else: + newJFloat(val.num) + of Bool: newJBool(val.bol) + of Symbol: newJString(val.sym) + of String: newJString(val.str) + of List, Array: val.elems.toJson + of Map: + var res = newJObject() + for key, value in val.fields.pairs: + res[key] = value.toJson + res + of Func: newJString(&"") + of Lambda: newJString(&"({val.params}) -> {val.body})") + of Macro: newJString(&"!({val.params}) -> {val.body})") + +proc fromJsonHook*(val: var LispVal, jsonNode: JsonNode, opt = Joptions()) {.raises: [ValueError].} = + case jsonNode.kind + of JNull: + val = newNil() + of JBool: + val = newBool(jsonNode.getBool) + of JInt: + val = newNumber(jsonNode.getInt.float) + of JFloat: + val = newNumber(jsonNode.getFloat) + of JString: + val = newString(jsonNode.getStr) + of JObject: + val = newMap() + for key, value in jsonNode.fields.pairs: + val.fields[key] = value.jsonTo(LispVal) + of JArray: + val = newArray(jsonNode.elems.mapIt(it.jsonTo(LispVal))) + +type + LispEventKind* = enum ## enumeration of all events that may occur when parsing + lispError, ## an error occurred during parsing + lispEof, ## end of file reached + lispString, ## a string literal + lispSymbol, ## a symbol + lispInt, ## an integer literal + lispFloat, ## a float literal + lispTrue, ## the value `true` + lispFalse, ## the value `false` + lispNull, ## the value `null` + lispObjectStart, ## start of an object: the `{` token + lispObjectEnd, ## end of an object: the `}` token + lispArrayStart, ## start of an array: the `[` token + lispArrayEnd ## end of an array: the `]` token + lispListStart, ## start of an array: the `(` token + lispListEnd, ## end of an array: the `)` token + lispListColon, ## : in list + + TokKind* = enum # must be synchronized with TLispEventKind! + tkError, + tkEof, + tkString, + tkSymbol, + tkInt, + tkFloat, + tkTrue, + tkFalse, + tkNull, + tkParenLe, + tkParenRi, + tkCurlyLe, + tkCurlyRi, + tkBracketLe, + tkBracketRi, + tkColon, + tkComma, + tkCommaAt, + tkBacktick, # {()}@*789/?[<>]=+456-!#~|&.0123%; + + ParserState = enum + stateEof, stateStart, stateObject, stateArray, stateList, stateExpectArrayComma, + stateExpectObjectComma, stateExpectColon, stateExpectValue + + LispParserError* = enum ## enumeration that lists all errors that can occur + errNone, ## no error + errInvalidToken, ## invalid token + errStringExpected, ## string expected + errColonExpected, ## `:` expected + errCommaExpected, ## `,` expected + errBracketRiExpected, ## `]` expected + errParenRiExpected, ## `)` expected + errCurlyRiExpected, ## `}` expected + errQuoteExpected, ## `"` or `'` expected + errEOC_Expected, ## `*/` expected + errEofExpected, ## EOF expected + errExprExpected ## expr expected + + LispParser* = object of BaseLexer ## the parser object. + a*: string + tok*: TokKind + kind: LispEventKind + err: LispParserError + state: seq[ParserState] + filename: string + rawStringLiterals: bool + + LispKindError* = object of ValueError ## raised by the `to` macro if the + ## Lisp kind is incorrect. + LispParsingError* = object of ValueError ## is raised for a Lisp error + +const + errorMessages*: array[LispParserError, string] = [ + "no error", + "invalid token", + "string expected", + "':' expected", + "',' expected", + "']' expected", + "')' expected", + "'}' expected", + "'\"' or \"'\" expected", + "'*/' expected", + "EOF expected", + "expression expected" + ] + tokToStr: array[TokKind, string] = [ + "invalid token", + "EOF", + "string literal", + "symbol", + "int literal", + "float literal", + "true", + "false", + "nil", + "(", ")", "{", "}", "[", "]", ":", ",", ",@", "`" + ] + +proc open*(my: var LispParser, input: Stream, filename: string; rawStringLiterals = false) = + ## initializes the parser with an input stream. `Filename` is only used + ## for nice error messages. If `rawStringLiterals` is true, string literals + ## are kept with their surrounding quotes and escape sequences in them are + ## left untouched too. + lexbase.open(my, input) + my.filename = filename + my.state = @[stateStart] + my.kind = lispError + my.a = "" + my.rawStringLiterals = rawStringLiterals + +proc close*(my: var LispParser) {.inline.} = + ## closes the parser `my` and its associated input stream. + lexbase.close(my) + +proc str*(my: LispParser): string {.inline.} = + ## returns the character data for the events: `lispInt`, `lispFloat`, + ## `lispString` + assert(my.kind in {lispInt, lispFloat, lispString, lispSymbol}) + return my.a + +proc getInt*(my: LispParser): BiggestInt {.inline.} = + ## returns the number for the event: `lispInt` + assert(my.kind == lispInt) + return parseBiggestInt(my.a) + +proc getFloat*(my: LispParser): float {.inline.} = + ## returns the number for the event: `lispFloat` + assert(my.kind == lispFloat) + return parseFloat(my.a) + +proc kind*(my: LispParser): LispEventKind {.inline.} = + ## returns the current event type for the Lisp parser + return my.kind + +proc getColumn*(my: LispParser): int {.inline.} = + ## get the current column the parser has arrived at. + result = getColNumber(my, my.bufpos) + +proc getLine*(my: LispParser): int {.inline.} = + ## get the current line the parser has arrived at. + result = my.lineNumber + +proc getFilename*(my: LispParser): string {.inline.} = + ## get the filename of the file that the parser processes. + result = my.filename + +proc errorMsg*(my: LispParser): string = + ## returns a helpful error message for the event `lispError` + assert(my.kind == lispError) + result = "$1($2, $3) Error: $4" % [ + my.filename, $getLine(my), $getColumn(my), errorMessages[my.err]] + +proc errorMsgExpected*(my: LispParser, e: string): string = + ## returns an error message "`e` expected" in the same format as the + ## other error messages + result = "$1($2, $3) Error: $4" % [ + my.filename, $getLine(my), $getColumn(my), e & " expected"] + +proc handleHexChar*(c: char, x: var int): bool {.inline.} = + ## Converts `%xx` hexadecimal to the ordinal number and adds the result to `x`. + ## Returns `true` if `c` is hexadecimal. + ## + ## When `c` is hexadecimal, the proc is equal to `x = x shl 4 + hex2Int(c)`. + result = true + case c + of '0'..'9': x = (x shl 4) or (ord(c) - ord('0')) + of 'a'..'f': x = (x shl 4) or (ord(c) - ord('a') + 10) + of 'A'..'F': x = (x shl 4) or (ord(c) - ord('A') + 10) + else: + result = false + +proc parseEscapedUTF16*(buf: cstring, pos: var int): int = + result = 0 + #UTF-16 escape is always 4 bytes. + for _ in 0..3: + # if char in '0' .. '9', 'a' .. 'f', 'A' .. 'F' + if handleHexChar(buf[pos], result): + inc(pos) + else: + return -1 + +proc parseSymbol(my: var LispParser): TokKind = + result = tkSymbol + var pos = my.bufpos + while true: + case my.buf[pos] + of ')', '}', ']', ',', ' ', '\n', ':': + break + of '\c': + break + # of '\L': + # break + else: + add(my.a, my.buf[pos]) + inc(pos) + my.bufpos = pos # store back + +proc parseString(my: var LispParser, endd: char): TokKind = + result = tkString + var pos = my.bufpos + 1 + if my.rawStringLiterals: + add(my.a, endd) + while true: + let c = my.buf[pos] + case c + of '\0': + my.err = errQuoteExpected + result = tkError + break + of '\\': + if my.rawStringLiterals: + add(my.a, '\\') + case my.buf[pos+1] + of '\\', '"', '\'', '/': + add(my.a, my.buf[pos+1]) + inc(pos, 2) + of 'b': + add(my.a, '\b') + inc(pos, 2) + of 'f': + add(my.a, '\f') + inc(pos, 2) + of 'n': + add(my.a, '\L') + inc(pos, 2) + of 'r': + add(my.a, '\C') + inc(pos, 2) + of 't': + add(my.a, '\t') + inc(pos, 2) + of 'v': + add(my.a, '\v') + inc(pos, 2) + of 'u': + if my.rawStringLiterals: + add(my.a, 'u') + inc(pos, 2) + var pos2 = pos + var r = parseEscapedUTF16(cstring(my.buf), pos) + if r < 0: + my.err = errInvalidToken + break + # Deal with surrogates + if (r and 0xfc00) == 0xd800: + if my.buf[pos] != '\\' or my.buf[pos+1] != 'u': + my.err = errInvalidToken + break + inc(pos, 2) + var s = parseEscapedUTF16(cstring(my.buf), pos) + if (s and 0xfc00) == 0xdc00 and s > 0: + r = 0x10000 + (((r - 0xd800) shl 10) or (s - 0xdc00)) + else: + my.err = errInvalidToken + break + if my.rawStringLiterals: + let length = pos - pos2 + for i in 1 .. length: + if my.buf[pos2] in {'0'..'9', 'A'..'F', 'a'..'f'}: + add(my.a, my.buf[pos2]) + inc pos2 + else: + break + else: + add(my.a, toUTF8(Rune(r))) + else: + # don't bother with the error + add(my.a, my.buf[pos]) + inc(pos) + of '\c': + pos = lexbase.handleCR(my, pos) + add(my.a, '\c') + of '\L': + pos = lexbase.handleLF(my, pos) + add(my.a, '\L') + else: + if c == endd: + if my.rawStringLiterals: + add(my.a, endd) + inc(pos) + break + add(my.a, my.buf[pos]) + inc(pos) + my.bufpos = pos # store back + +proc skip(my: var LispParser) = + var pos = my.bufpos + while true: + case my.buf[pos] + of ';': + if true or my.buf[pos+1] == '/': + # skip line comment: + inc(pos, 2) + while true: + case my.buf[pos] + of '\0': + break + of '\c': + pos = lexbase.handleCR(my, pos) + break + of '\L': + pos = lexbase.handleLF(my, pos) + break + else: + inc(pos) + elif my.buf[pos+1] == '*': + # skip long comment: + inc(pos, 2) + while true: + case my.buf[pos] + of '\0': + my.err = errEOC_Expected + break + of '\c': + pos = lexbase.handleCR(my, pos) + of '\L': + pos = lexbase.handleLF(my, pos) + of '*': + inc(pos) + if my.buf[pos] == '/': + inc(pos) + break + else: + inc(pos) + else: + break + of ' ', '\t': + inc(pos) + of '\c': + pos = lexbase.handleCR(my, pos) + of '\L': + pos = lexbase.handleLF(my, pos) + else: + break + my.bufpos = pos + +proc parseNumber(my: var LispParser) = + var pos = my.bufpos + if my.buf[pos] == '-': + add(my.a, '-') + inc(pos) + if my.buf[pos] == '.': + add(my.a, "0.") + inc(pos) + else: + while my.buf[pos] in Digits: + add(my.a, my.buf[pos]) + inc(pos) + if my.buf[pos] == '.': + add(my.a, '.') + inc(pos) + # digits after the dot: + while my.buf[pos] in Digits: + add(my.a, my.buf[pos]) + inc(pos) + if my.buf[pos] in {'E', 'e'}: + add(my.a, my.buf[pos]) + inc(pos) + if my.buf[pos] in {'+', '-'}: + add(my.a, my.buf[pos]) + inc(pos) + while my.buf[pos] in Digits: + add(my.a, my.buf[pos]) + inc(pos) + my.bufpos = pos + +proc parseName(my: var LispParser) = + var pos = my.bufpos + if my.buf[pos] in IdentStartChars: + while my.buf[pos] in IdentChars: + add(my.a, my.buf[pos]) + inc(pos) + my.bufpos = pos + +proc getTok(my: var LispParser): TokKind = + setLen(my.a, 0) + skip(my) # skip whitespace, comments + case my.buf[my.bufpos] + of '-': + if my.buf[my.bufpos + 1] != ' ': + parseNumber(my) + if {'.', 'e', 'E'} in my.a: + result = tkFloat + else: + result = tkInt + else: + result = parseSymbol(my) + of '0'..'9': + parseNumber(my) + if {'.', 'e', 'E'} in my.a: + result = tkFloat + else: + result = tkInt + of '"': + result = parseString(my, '"') + of '\'': + result = parseString(my, '\'') + of '[': + inc(my.bufpos) + result = tkBracketLe + of '(': + inc(my.bufpos) + result = tkParenLe + of '{': + inc(my.bufpos) + result = tkCurlyLe + of ']': + inc(my.bufpos) + result = tkBracketRi + of ')': + inc(my.bufpos) + result = tkParenRi + of '}': + inc(my.bufpos) + result = tkCurlyRi + of ',': + inc(my.bufpos) + if my.buf[my.bufpos] == '@': + inc(my.bufpos) + result = tkCommaAt + else: + result = tkComma + of '`': + inc(my.bufpos) + result = tkBacktick + of ':': + inc(my.bufpos) + result = tkColon + of '\0': + result = tkEof + else: + result = parseSymbol(my) + case my.a + of "nil": result = tkNull + of "true": result = tkTrue + of "false": result = tkFalse + + my.tok = result + +proc raiseParseErr(p: LispParser, msg: string) {.noinline, noreturn.} = + ## raises an `ELispParsingError` exception. + raise newException(LispParsingError, errorMsgExpected(p, msg)) + +proc eat(p: var LispParser, tok: TokKind) = + if p.tok == tok: discard getTok(p) + else: raiseParseErr(p, tokToStr[tok]) + +proc parseLisp*(p: var LispParser; depth = 0, depthLimit = 1024): LispVal = + ## Parses JSON from a JSON Parser `p`. + case p.tok + of tkString: + result = newString(move p.a) + discard getTok(p) + of tkSymbol: + result = newSymbol(move p.a) + discard getTok(p) + of tkBacktick: + discard getTok(p) + result = newList(@[newSymbol("quasiquote"), parseLisp(p, depth + 1)]) + of tkColon: + discard getTok(p) + result = newSymbol(":") + of tkComma: + discard getTok(p) + result = newList(@[newSymbol("unquote"), parseLisp(p, depth + 1)]) + of tkCommaAt: + discard getTok(p) + result = newList(@[newSymbol("unquote-splicing"), parseLisp(p, depth + 1)]) + of tkInt: + try: + result = newNumber(parseBiggestInt(p.a).float) + except ValueError: + raiseParseErr(p, "number too big") + discard getTok(p) + of tkFloat: + try: + result = newNumber(parseFloat(p.a)) + except ValueError: + raiseParseErr(p, "number too big") + discard getTok(p) + of tkTrue: + result = newBool(true) + discard getTok(p) + of tkFalse: + result = newBool(false) + discard getTok(p) + of tkNull: + result = newNil() + discard getTok(p) + of tkCurlyLe: + if depth > depthLimit: + raiseParseErr(p, "}") + result = newMap() + discard getTok(p) + while p.tok != tkCurlyRi: + if p.tok notin {tkString, tkSymbol}: + raiseParseErr(p, "string literal as key") + var key = p.a + discard getTok(p) + eat(p, tkColon) + var val = parseLisp(p, depth+1) + result.fields[key] = val + if p.tok != tkComma: break + discard getTok(p) + eat(p, tkCurlyRi) + of tkBracketLe: + if depth > depthLimit: + raiseParseErr(p, "]") + result = newArray() + discard getTok(p) + while p.tok != tkBracketRi: + result.elems.add(parseLisp(p, depth+1)) + if p.tok != tkComma: break + discard getTok(p) + eat(p, tkBracketRi) + of tkParenLe: + if depth > depthLimit: + raiseParseErr(p, ")") + result = newList() + discard getTok(p) + while p.tok != tkParenRi: + result.elems.add(parseLisp(p, depth+1)) + if p.tok == tkParenRi: break + eat(p, tkParenRi) + else: + raiseParseErr(p, "{") + +iterator parseLispFragments*(s: Stream, filename: string = ""): LispVal = + var p: LispParser + p.open(s, filename) + try: + discard getTok(p) # read first token + while p.tok != tkEof: + yield p.parseLisp() + finally: + p.close() + +proc parseLispSingle*(str: string): LispVal = + var p: LispParser + p.open(newStringStream(str), "repl") + try: + discard getTok(p) # read first token + while p.tok != tkEof: + result = p.parseLisp() + return + finally: + p.close() + +proc parseLisp*(str: string): LispVal = + var p: LispParser + p.open(newStringStream(str), "repl") + result = newList(@[newSymbol("list")]) + try: + discard getTok(p) # read first token + while p.tok != tkEof: + result.elems.add p.parseLisp() + finally: + p.close() + +proc parseLispValues*(str: string): seq[LispVal] = + var p: LispParser + p.open(newStringStream(str), "repl") + try: + discard getTok(p) # read first token + while p.tok != tkEof: + result.add p.parseLisp() + finally: + p.close() + +proc isTruthy*(val: LispVal): bool = + case val.kind + of Nil: false + of Number: val.num != 0 + of Bool: val.bol + of Symbol: true + of String: true + of List: true + of Array: true + of Map: true + of Func: true + of Lambda: true + of Macro: true + +proc eval*(expr: LispVal, env: var Env): LispVal {.raises: [LispError].} + +proc evalQuasiquote(expr: LispVal, env: var Env): LispVal = + if expr.kind == List and expr.elems.len > 0: + let head = expr.elems[0] + if head.kind == Symbol: + case head.sym + of "unquote": + return eval(expr.elems[1], env) + of "unquote-splicing": + raise newException(LispError, "unquote-splicing not allowed here") # must be handled inside list + if expr.kind in {List, Array}: + var resultElems: seq[LispVal] = @[] + for el in expr.elems: + if el.kind == List and el.elems.len > 0 and + el.elems[0].kind == Symbol and el.elems[0].sym == "unquote-splicing": + let spliceVal = eval(el.elems[1], env) + if spliceVal.kind != expr.kind: + raise newException(LispError, "unquote-splicing must return a list") + resultElems.add(spliceVal.elems) + else: + resultElems.add(evalQuasiquote(el, env)) + return newList(resultElems) + elif expr.kind == Map: + result = newMap() + for key, el in expr.fields.pairs: + if el.kind == List and el.elems.len > 0 and + el.elems[0].kind == Symbol and el.elems[0].sym == "unquote-splicing": + let spliceVal = eval(el.elems[1], env) + if spliceVal.kind != Map: + raise newException(LispError, "unquote-splicing must return a map") + for key2, val in spliceVal.fields.pairs: + result.fields[key2] = val + else: + result.fields[key] = evalQuasiquote(el, env) + return result + else: + return expr + +proc eval(expr: LispVal, env: var Env): LispVal {.raises: [LispError].} = + + case expr.kind + of Nil, Number, Bool, String, Func, Lambda, Macro: + return expr + of Symbol: + if expr.sym.startsWith("'"): + return newSymbol(expr.sym[1..^1]) + result = env[expr.sym] + if result == nil: + raise newException(LispError, "undefined symbol: '" & expr.sym & "'") + + of Array: + return newArray(expr.elems.mapIt(eval(it, env))) + + of Map: + result = newMap() + for key, value in expr.fields.pairs: + result.fields[key] = eval(value, env) + + of List: + if expr.elems.len == 0: + return expr + + let first = expr.elems[0] + if first == nil: + raise newException(LispError, "Failed to evaluate first element of list: nil") + + if first.kind == Symbol: + case first.sym + of "quote": + return expr.elems[1] + of "let": + let sym = expr.elems[1] + let value = eval(expr.elems[2], env) + env[sym.sym] = value + return value + of "set": + let sym = expr.elems[1] + if sym.kind != Symbol: + raise newException(LispError, "not a symbol: '" & $sym & "'") + + let value = eval(expr.elems[2], env) + if not env.set(sym.sym, value): + raise newException(LispError, "undefined symbol: '" & sym.sym & "'") + + return value + of "eval": + let sub = expr.elems[1] + let value = eval(sub, env) + return eval(value, env) + of "lambda": + let params = expr.elems[1].elems.mapIt(it.sym) + let body = expr.elems[2] + return newLambda(params, body, env) + of "defmacro": + let name = expr.elems[1].sym + let params = expr.elems[2].elems.mapIt(it.sym) + let body = expr.elems[3] + env[name] = newMacro(params, body, env) + return env[name] + of "quasiquote": + return evalQuasiquote(expr.elems[1], env) + of "if": + var i = 1 + while i + 1 < expr.elems.len: + let cond = eval(expr.elems[i], env) + if cond.isTruthy: + return eval(expr.elems[i + 1], env) + i = i + 2 + if i < expr.elems.len: + return eval(expr.elems[i], env) + return newNil() + of "floor": + let val = eval(expr.elems[1], env) + if val.kind != Number: + raise newException(LispError, "floor takes a number, got " & $val) + return newNumber(val.num.floor) + of "repeat": + let name = expr.elems[1].sym + let count = eval(expr.elems[2], env) + if count.kind != Number: + raise newException(LispError, "Count must be a number, got " & $count) + + var res = newList() + for i in 0.. 0: + return args.last + return newNil() + ) + result["eq"] = newFunc("eq", proc(args: seq[LispVal]): LispVal = + newBool(args[0].kind == args[1].kind and $args[0] == $args[1])) # todo: don't use $ + result[">"] = newFunc(">", proc(args: seq[LispVal]): LispVal = + newBool(args[0].num > args[1].num)) + result["<"] = newFunc("<", proc(args: seq[LispVal]): LispVal = + newBool(args[0].num < args[1].num)) + result["list"] = newFunc("list", proc(args: seq[LispVal]): LispVal = + newList(args)) + result["do"] = newFunc("do", proc(args: seq[LispVal]): LispVal = + if args.len > 0: + args.last + else: + newNil()) + result["head"] = newFunc("head", proc(args: seq[LispVal]): LispVal = + if args[0].kind != List: raise newException(LispError, "head needs list") + else: args[0].elems[0]) + result["tail"] = newFunc("tail", proc(args: seq[LispVal]): LispVal = + if args[0].kind != List: raise newException(LispError, "tail needs list") + else: newList(args[0].elems[1..^1])) + result["cons"] = newFunc("cons", proc(args: seq[LispVal]): LispVal = + if args[1].kind != List: raise newException(LispError, "cons needs list") + else: newList(@[args[0]] & args[1].elems)) + + result["add"] = newFunc("add", proc(args: seq[LispVal]): LispVal = + if args[0].kind notin {List, Array}: raise newException(LispError, "add needs list or array") + for i in 1..args.high: + args[0].elems.add args[i] + ) + + # result["append"] = newFunc("append", proc(args: seq[LispVal]): LispVal = + # if args[0].kind notin {List, Array}: raise newException(LispError, "append needs list or array") + # for i in 1..args.high: + # if args[i].kind notin {List, Array}: + # raise newException(LispError, "append needs list or array") + # args[0].elems.add args[i].elems + # ) + + # result["info"] = newFunc("info", proc(args: seq[LispVal]): LispVal = + # var str = "" + # for i, arg in args: + # if i > 0: + # str.add " " + # str.add $arg + # debugf"{str}" + # ) + + # result["echo"] = newFunc("echo", proc(args: seq[LispVal]): LispVal = + # var str = "" + # for i, arg in args: + # if i > 0: + # str.add " " + # str.add $arg + # debugf"lisp: {str}" + # ) + + # result["build-str"] = newFunc("build-str", proc(args: seq[LispVal]): LispVal = + # var str = "" + # for i, arg in args: + # str.add $arg + # return newString(str) + # ) + + # result["join-str"] = newFunc("join-str", proc(args: seq[LispVal]): LispVal = + # if args.len < 1: raise newException(LispError, "join-str needs a seperator") + # if args[0].kind notin {String, Symbol}: raise newException(LispError, "join-str needs a seperator") + # let sep = $args[0] + # var str = "" + # for i in 1..args.high: + # if i > 1: + # str.add sep + # str.add $args[i] + # return newString(str) + # ) + +globalEnv = baseEnv() diff --git a/src/misc/binary_encoder.nim b/src/misc/binary_encoder.nim index 5b5dc9a34..355c6e4fc 100644 --- a/src/misc/binary_encoder.nim +++ b/src/misc/binary_encoder.nim @@ -3,6 +3,9 @@ type BinaryEncoder* = object buffer*: seq[byte] +template toOpenArray*(self: BinaryEncoder): openArray[uint8] = + self.buffer.toOpenArray(0, self.buffer.high) + macro getByte(v: typed, i: static[int]): untyped = let shift = i * 8 result = genAst(v, shift): diff --git a/src/misc/custom_regex.nim b/src/misc/custom_regex.nim new file mode 100644 index 000000000..efb56aae7 --- /dev/null +++ b/src/misc/custom_regex.nim @@ -0,0 +1,2 @@ +import "./regex" +export regex diff --git a/src/misc/generational_seq.nim b/src/misc/generational_seq.nim index 9c1ef85a2..134f7206d 100644 --- a/src/misc/generational_seq.nim +++ b/src/misc/generational_seq.nim @@ -1,4 +1,4 @@ -import std/[sequtils, options] +import std/[options] type GenerationalSeq*[T; K] = object ## Even generation means empty slot, odd means it's filled diff --git a/src/misc/macro_utils.nim b/src/misc/macro_utils.nim index fbd233421..4f15ba606 100644 --- a/src/misc/macro_utils.nim +++ b/src/misc/macro_utils.nim @@ -81,7 +81,7 @@ proc argHasPragma*(def: NimNode, arg: int, pragma: string): bool = proc isVarargs*(def: NimNode, arg: int): bool = def.argHasPragma(arg, "varargs") proc argType*(def: NimNode, arg: int): NimNode = def[3][arg + 1][1] proc argDefaultValue*(def: NimNode, arg: int): Option[NimNode] = - if def[3][arg + 1][2].kind != nnkEMpty: + if def[3][arg + 1][2].kind != nnkEmpty: return def[3][arg + 1][2].some return NimNode.none diff --git a/src/misc/rope_utils.nim b/src/misc/rope_utils.nim index e9bb78da4..97777ffc4 100644 --- a/src/misc/rope_utils.nim +++ b/src/misc/rope_utils.nim @@ -259,14 +259,20 @@ func runeIndex*(self: RopeSlice, offset: int): RuneIndex = ## Convert byte offset to rune index return self.convert(offset, Count).RuneIndex -proc getEnclosing*(text: RopeSlice, column: int, predicate: proc(c: char): bool {.gcsafe, raises: [].}): (int, int) = +proc getEnclosing*(text: RopeSlice, column: int, inclusive: bool, predicate: proc(c: char): bool {.gcsafe, raises: [].}): (int, int) = var cf = text.cursor(column) var cb = cf.clone() - while cf.offset < text.len - 1: + while cf.offset < text.len: cf.seekNextRune() + if cf.atEnd: + if inclusive: + cf.seekPrevRune() + break if not predicate(cf.currentChar()): - cf.seekPrevRune() + if inclusive: + cf.seekPrevRune() break + while cb.offset > 0: cb.seekPrevRune() if not predicate(cb.currentChar()): diff --git a/src/move_database.nim b/src/move_database.nim new file mode 100644 index 000000000..ff7d28b32 --- /dev/null +++ b/src/move_database.nim @@ -0,0 +1,736 @@ +import std/[strutils, sequtils, sugar, strformat, tables, json] +import scripting_api except DocumentEditor, TextDocumentEditor, AstDocumentEditor +from scripting_api as sca import nil +import misc/[util, custom_logger, custom_unicode, rope_utils, custom_async, myjsonutils] +import service +import text/[wrap_map, display_map] +import nimsumtree/[rope] +import lisp + +{.push gcsafe, raises: [].} + +logCategory "moves" + +type + MoveImpl* = proc(rope: Rope, move: string, selections: openArray[Selection], count: int, includeEol: bool): seq[Selection] {.gcsafe, raises: [].} + MoveDatabase* = ref object of Service + moves: Table[string, MoveImpl] + env: Env + debugMoves: bool + +func serviceName*(_: typedesc[MoveDatabase]): string = "MoveDatabase" + +addBuiltinService(MoveDatabase) + +method init*(self: MoveDatabase): Future[Result[void, ref CatchableError]] {.async: (raises: []).} = + self.env = baseEnv() + return ok() + +proc toggleDebugMoves*(self: MoveDatabase) = + self.debugMoves = not self.debugMoves + +proc vimMotionWord*(text: Rope, cursor: Cursor, inclusive: bool): Selection = + const AlphaNumeric = {'A'..'Z', 'a'..'z', '0'..'9', '_'} + + var line = text.getLine(cursor.line) + if line.len == 0: + return (cursor.line, 0).toSelection + + let c = line.charAt(cursor.column.clamp(0, line.len - 1)) + if c in Whitespace: + let (startColumn, endColumn) = line.getEnclosing(cursor.column, inclusive, (c) => c in Whitespace) + return ((cursor.line, startColumn), (cursor.line, endColumn)) + + elif c in AlphaNumeric: + let (startColumn, endColumn) = line.getEnclosing(cursor.column, inclusive, (c) => c in AlphaNumeric) + return ((cursor.line, startColumn), (cursor.line, endColumn)) + + else: + let (startColumn, endColumn) = line.getEnclosing(cursor.column, inclusive, (c) => c notin Whitespace and c notin AlphaNumeric) + return ((cursor.line, startColumn), (cursor.line, endColumn)) + +type VimWordCharCategory {.pure.} = enum Word, Whitespace, Other + +proc vimWordCharCategory*(c: Rune): VimWordCharCategory = + if c.int < 128: + const AlphaNumeric = {'A'..'Z', 'a'..'z', '0'..'9', '_'} + if c.char in Whitespace: + return VimWordCharCategory.Whitespace + if c.char in AlphaNumeric: + return VimWordCharCategory.Word + return VimWordCharCategory.Other + if c.isWhitespace: + return VimWordCharCategory.Whitespace + if c.isAlpha: + return VimWordCharCategory.Word + return VimWordCharCategory.Other + +proc vimMotionWordBack*(text: Rope, cursor: Cursor, inclusive: bool): Selection = + if cursor.column == 0: + return cursor.toSelection + + let prevCursor = text.clipPoint(point(cursor.line, cursor.column - 1), Left).toCursor + let current = text.runeAt(cursor.toPoint) + let prev = text.runeAt(prevCursor.toPoint) + if current.vimWordCharCategory == prev.vimWordCharCategory: + return vimMotionWord(text, cursor, inclusive) + return vimMotionWord(text, prevCursor, inclusive) + +proc vimMotionWordBig*(text: Rope, cursor: Cursor, inclusive: bool): Selection = + var line = text.getLine(cursor.line) + if line.len == 0: + return (cursor.line, 0).toSelection + + let c = line.charAt(cursor.column.clamp(0, line.len - 1)) + if c in Whitespace: + let (startColumn, endColumn) = line.getEnclosing(cursor.column, inclusive, (c) => c in Whitespace) + return ((cursor.line, startColumn), (cursor.line, endColumn)) + + else: + let (startColumn, endColumn) = line.getEnclosing(cursor.column, inclusive, (c) => c notin Whitespace) + return ((cursor.line, startColumn), (cursor.line, endColumn)) + +proc findNext*(text: Rope, cursor: Cursor, target: Rune): Cursor = + var c = text.cursorT(cursor.toPoint) + c.seekNextRune() + while not c.atEnd and c.currentRune != target: + c.seekNextRune() + return c.position.toCursor + +proc clampCursor*(text: Rope, cursor: Cursor, includeAfter: bool = true): Cursor = + var cursor = cursor + cursor.line = clamp(cursor.line, 0, text.lines - 1) + + var res = text.clipPoint(cursor.toPoint, Bias.Left).toCursor + var c = text.cursorT(res.toPoint) + if not includeAfter and c.currentRune == '\n'.Rune and res.column > 0: + c.seekPrevRune() + res = c.position.toCursor + return res + +proc moveCursorColumn(text: Rope, cursor: Cursor, offset: int, wrap: bool = true, includeEol: bool = true): Cursor = + var cursor = cursor + + if cursor.line notin 0.. 0: + for i in 0..= lastIndex: + if not wrap: + break + if cursor.line < text.lines - 1: + cursor.line = cursor.line + 1 + cursor.column = 0 + lastIndex = text.lastValidIndex(cursor.line, includeEol) + c.seekForward(point(cursor.line, 0)) + continue + else: + cursor.column = lastIndex + break + + c.seekNextRune() + cursor = c.position.toCursor + + elif offset < 0: + for i in 0..<(-offset): + if cursor.column == 0: + if not wrap: + break + if cursor.line > 0: + cursor.line = cursor.line - 1 + lastIndex = text.lastValidIndex(cursor.line, includeEol) + c.seekPrevRune() + if not includeEol: + c.seekPrevRune() + cursor.column = lastIndex + continue + else: + cursor.column = 0 + break + + c.seekPrevRune() + cursor = c.position.toCursor + + return text.clampCursor(cursor, includeEol) + +proc findSurroundStart*(rope: Rope, cursor: Cursor, c0: char, c1: char, depth: int = 1): Option[Cursor] = + var depth = depth + var res = cursor + + # todo: use RopeCursor + while res.line >= 0: + let line = rope.getLine(res.line) + res.column = min(res.column, line.len - 1) + while line.len > 0 and res.column >= 0: + let c = line.charAt(res.column) + # debugf"findSurroundStart: {res} -> {depth}, '{c}'" + if c == c1 and (depth < 1 or c0 != c1): + inc depth + if depth == 0: + return res.some + elif c == c0: + dec depth + if depth == 0: + return res.some + dec res.column + + if res.line == 0: + return Cursor.none + + res = (res.line - 1, rope.lineLen(res.line - 1) - 1) + + return Cursor.none + +proc findSurroundEnd*(rope: Rope, cursor: Cursor, c0: char, c1: char, depth: int = 1): Option[Cursor] = + let lineCount = rope.lines + var depth = depth + var res = cursor + + # todo: use RopeCursor + while res.line < lineCount: + let line = rope.getLine(res.line) + res.column = min(res.column, line.len - 1) + while line.len > 0 and res.column < line.len: + let c = line.charAt(res.column) + # echo &"findSurroundEnd: {res} -> {depth}, '{c}'" + if c == c0 and (depth < 1 or c0 != c1): + inc depth + if depth == 0: + return res.some + elif c == c1: + dec depth + if depth == 0: + return res.some + inc res.column + + if res.line == lineCount - 1: + return Cursor.none + + res = (res.line + 1, 0) + + return Cursor.none + +proc getSurrounding*(rope: Rope, selection: Selection, c0: char, c1: char, inside: bool): Selection = + if selection.isBackwards: + return rope.getSurrounding(selection.reverse, c0, c1, inside).reverse + result = selection + while true: + let lastChar = rope.charAt(result.last.toPoint) + let (startDepth, endDepth) = if lastChar == c0: + (1, 0) + elif lastChar == c1: + (0, 1) + else: + (1, 1) + + if rope.findSurroundStart(result.first, c0, c1, startDepth).getSome(opening) and rope.findSurroundEnd(result.last, c0, c1, endDepth).getSome(closing): + result = (opening, closing) + if inside: + result.first = rope.moveCursorColumn(result.first, 1) + result.last = rope.moveCursorColumn(result.last, -1) + return + + if rope.findSurroundEnd(result.first, c0, c1, -1).getSome(opening) and rope.findSurroundEnd(opening, c0, c1, 0).getSome(closing): + result = (opening, closing) + if inside: + result.first = rope.moveCursorColumn(result.first, 1) + result.last = rope.moveCursorColumn(result.last, -1) + return + else: + return + +proc moveCursorVisualLine(displayMap: DisplayMap, cursor: Cursor, offset: int, wrap: bool = false, includeAfter: bool = false, targetColumn: int): Cursor = + let rope {.cursor.} = displayMap.buffer.visibleText + let wrapPointOld = displayMap.toWrapPoint(cursor.toPoint) + let endWrapPoint = displayMap.wrapMap.endWrapPoint + let wrapPoint = wrapPoint(max(wrapPointOld.row.int + offset, 0), targetColumn).clamp(wrapPoint()...endWrapPoint) + let newCursor = displayMap.toPoint(wrapPoint, if offset < 0: Bias.Left else: Bias.Right).toCursor + if offset < 0 and newCursor.line > 0 and newCursor.line == cursor.line and displayMap.toWrapPoint(newCursor.toPoint).row == wrapPointOld.row: + let newCursor2 = point(cursor.line - 1, rope.lineLen(cursor.line - 1)) + let displayPoint = displayMap.toDisplayPoint(newCursor2) + let displayPoint2 = displayPoint(displayPoint.row, targetColumn.uint32) + let point = displayMap.toPoint(displayPoint2) + + # echo &"moveCursorVisualLine {cursor}, {offset} -> {newCursor2} -> {displayPoint} -> {displayPoint2} -> {point}" + return point.toCursor + elif offset > 0: + # go to wrap point and back to point one more time because if we land inside of e.g an overlay then the position will + # be clamped which can screw up the target column we set before, so we need to calculate the target column again. + let wrapPoint2 = wrapPoint(displayMap.toWrapPoint(newCursor.toPoint).row, targetColumn).clamp(wrapPoint()...endWrapPoint) + let newCursor2 = displayMap.toPoint(wrapPoint2, if offset < 0: Bias.Left else: Bias.Right).toCursor + + # echo &"moveCursorVisualLine {cursor}, {offset} -> {newCursor}, wp: {wrapPointOld} -> {wrapPoint} -> {displayMap.toWrapPoint(newCursor.toPoint)}, {wrapPoint2} -> {newCursor2}" + if newCursor2.line >= rope.lines: + return cursor + return rope.clampCursor(newCursor2, includeAfter) + + if newCursor.line >= rope.lines: + return cursor + return rope.clampCursor(newCursor, includeAfter) + +proc moveCursorLine(text: Rope, displayMap: DisplayMap, cursor: Cursor, offset: int, targetColumn: int, wrap: bool, includeEol: bool): Cursor = + var cursor = cursor + let line = cursor.line + offset + if line < 0: + cursor = (0, cursor.column) + elif line >= text.lines: + cursor = (text.lines - 1, cursor.column) + else: + cursor.line = line + let wrapPoint = displayMap.toWrapPoint(Point.init(line, 0)) + cursor.column = displayMap.toPoint(wrapPoint(wrapPoint.row.int, targetColumn)).column.int + return text.clampCursor(cursor, includeEol) + +type MoveFunction* = proc(move: string, selections: openArray[Selection], count: int): seq[Selection] {.gcsafe, raises: [].} + +proc getCount(env: Env): int = + let val = env["count"] + if val != nil: + case val.kind + of Number: + if val.num.int == 0: + return 1 + else: + return val.num.int + else: + log lvlError, "Can't convert env.count (" & $val & ") to type int" + + return 1 + +proc applyMoveImpl(self: MoveDatabase, displayMap: DisplayMap, move: string, selections: openArray[Selection], fallback: MoveFunction, args: openArray[LispVal], env: Env): seq[Selection] = + if self.debugMoves: + debugf"applyMoveImpl '{move}' {args}, {env.env}" + + template getEnv(name: string, typ: untyped, default: untyped): untyped = + block: + let val = env[name] + if val != nil: + try: + val.toJson().to(typ) + except CatchableError as e: + log lvlError, "In move '" & move & "': Failed to convert env." & name & " (" & $val & ") to typ " & $typ & ": " & e.msg + default + else: + default + + template getArg(index: int, typ: untyped, default: untyped): untyped = + block: + if index < args.len: + try: + args[index].toJson().to(typ) + except CatchableError as e: + log lvlError, "In move '" & move & "': Failed to convert argument " & $index & " to typ " & $typ & ": " & e.msg + default + else: + default + + var count = env.getCount() + assert count != 0 + + let targetColumn = getEnv("target-column", int, 0) + let includeEol = getEnv("include-eol", bool, true) + let wrap = getEnv("wrap", bool, true) + + let rope {.cursor.} = displayMap.buffer.visibleText + + if move in self.moves: + let impl = self.moves[move] + return impl(rope, move, selections, count, includeEol) + + case move + of "vim.word": + result = selections.mapIt(vimMotionWord(rope, it.last, false)) + for _ in 1.. 0: + res.first = (cursor.line - 1, rope.lineLen(cursor.line - 1)) + if cursor.column == line.len and cursor.line < rope.lines - 1: + res.last = (cursor.line + 1, 0) + res + + of "word-line-back": + return selections.mapIt: + let cursor = it.last + let line = rope.getLine cursor.line + var res = vimMotionWordBack(rope, cursor, false) + if cursor.column == 0 and cursor.line > 0: + res.first = (cursor.line - 1, rope.lineLen(cursor.line - 1)) + if cursor.column == line.len and cursor.line < rope.lines - 1: + res.last = (cursor.line + 1, 0) + res + + # of "line-back": + # let first = if cursor.line > 0 and cursor.column == 0: + # (cursor.line - 1, self.document.lineLength(cursor.line - 1)) + # else: + # (cursor.line, 0) + # result = (first, (cursor.line, self.document.lineLength(cursor.line))) + + of "line-num": + return @[(getArg(0, int, 0), 0).toSelection] + + of "line": + return selections.mapIt(block: + let lineLen = rope.lineLen(it.last.line) + var res: Selection = ((it.last.line, 0), (it.last.line, lineLen)) + if not includeEol and res.last.column == lineLen: + res.last = rope.moveCursorColumn(res.last, -1, wrap = false) + res + ) + + of "visual-line": + return selections.mapIt(block: + let lineLen = rope.lineLen(it.last.line) + let wrapPoint = displayMap.toWrapPoint(it.last.toPoint) + let displayLineStart = wrapPoint(wrapPoint.row) + let displayLineEnd = wrapPoint(wrapPoint.row + 1) + var res: Selection = ( + displayMap.toPoint(displayLineStart, Right).toCursor, + displayMap.toPoint(displayLineEnd, Right).toCursor, + ) + if res[1].column == 0: + res[1].line -= 1 + res[1].column = rope.lineLen(res[1].line) + + if not includeEol: + if res.last.column == lineLen: + res.last = rope.moveCursorColumn(res.last, -1, wrap = false) + elif res.last.column < rope.lineLen(it.last.line): # This is the case if we're not in the last visual sub line + res.last = rope.moveCursorColumn(res.last, -1, wrap = false) + + res + ) + + of "visual-line-up", "visual-line-down", "visual-page": + var minLine = int.high + var maxLine = int.low + for s in selections: + minLine = min(minLine, s.last.line) + maxLine = max(maxLine, s.last.line) + + let direction = if move == "visual-line-down": + count + elif move == "visual-line-up": + -count + else: + ((count * getEnv("screen-lines", int, 55)) div 100) + + proc doMoveCursor(numSelections: int, cursor: Cursor, offset: int, includeAfter: bool): Cursor = + let targetColumn = if maxLine - minLine + 1 < numSelections: + displayMap.toDisplayPoint(cursor.toPoint).column.int + else: + targetColumn + moveCursorVisualLine(displayMap, cursor, offset, false, includeAfter, targetColumn) + return selections.mapIt(doMoveCursor(selections.len, it.last, direction, includeEol).toSelection) + + # of "line-next": + # result = ((cursor.line, 0), (cursor.line, self.document.lineLength(cursor.line))) + # if result.last.line + 1 < self.document.numLines: + # result.last = (result.last.line + 1, 0) + # for _ in 1.. 0: + # result.first = (result.first.line - 1, self.document.lineLength(result.first.line - 1)) + # for _ in 1.. 0: + # result.first = (result.first.line - 1, self.document.lineLength(result.first.line - 1)) + + of "line-no-indent": + result = selections.mapIt ((it.last.line, rope.indentBytes(it.last.line)), (it.last.line, rope.lineLen(it.last.line))) + + of "file": + result = @[((0, 0), (rope.lines - 1, rope.lineLen(rope.lines - 1)))] + + of "column": + let dir = getArg(0, int, 1) + return selections.mapIt(rope.moveCursorColumn(it.last, count * dir, wrap, includeEol).toSelection) + + of "inclusive": + return selections.mapIt(if it.isEmpty: it else: (it.first, rope.moveCursorColumn(it.last, -1, false, true))) + + of "line-up", "line-down": + let direction = if move == "line-down": 1 else: -1 + # return selections.mapIt((it.last, moveCursorLine(rope, displayMap, it.last, direction * count, targetColumn, false, includeEol))) + return selections.mapIt(moveCursorLine(rope, displayMap, it.last, direction * count, targetColumn, false, includeEol).toSelection) + + of "grow": + let dir = getArg(0, int, 1) * count + return selections.mapIt: + if dir < 0 and it.first.line == it.last.line and abs(it.first.column - it.last.column) < 2: + it + else: + (rope.moveCursorColumn(it.first, -dir, wrap, includeEol), rope.moveCursorColumn(it.last, dir, wrap, includeEol)) + + of "number": + result = selections.mapIt: + var r = it.last.toPoint...it.last.toPoint + var c = rope.cursorT(it.last.toPoint) + while c.currentChar in {'0'..'9'}: + c.seekNextRune() + r.b = c.position + + if r.a.column > 0: + c = rope.cursorT(it.last.toPoint) + while c.position.column > 0: + c.seekPrevRune() + if c.currentChar == '-': + r.a = c.position + break + + if c.currentChar notin {'0'..'9'}: + c.seekNextRune() + break + r.a = c.position + + r.toSelection + + of "target-column": + return selections.mapIt(rope.clampCursor((it.last.line, targetColumn)).toSelection) + + of "surround": + var c0 = getArg(0, string, "") + var c1 = getArg(1, string, "") + let inside = getArg(2, bool, false) + if c0.len > 0 and c1.len > 0: + result = selections.mapIt(rope.getSurrounding(it, c0[0], c1[0], inside)) + elif c0.len > 0: + result = selections.mapIt(rope.getSurrounding(it, c0[0], c0[0], inside)) + else: + result = selections.mapIt: + let c = rope.charAt(it.last.toPoint) + let (open, close, isOpen) = case c + of '(': ('(', ')', true) + of '{': ('{', '}', true) + of '[': ('[', ']', true) + of '<': ('<', '>', true) + of ')': ('(', ')', false) + of '}': ('{', '}', false) + of ']': ('[', ']', false) + of '>': ('<', '>', false) + of '"': ('"', '"', true) + of '\'': ('\'', '\'', true) + else: return + let selection = rope.getSurrounding(it, open, close, inside) + if isOpen: + selection + else: + selection.reverse + + of "move-to": + let c = getArg(0, string, "") + if c.len > 0: + let r = c.runeAt(0) + return selections.mapIt((it.first, rope.findNext(it.last, r))) + return @selections + + else: + if fallback != nil: + return fallback(move, selections, count) + log lvlError, &"Unknown move '{move}'" + return @selections + +proc applyMoveLisp(self: MoveDatabase, displayMap: DisplayMap, move: string, originalSelections: openArray[Selection], env: Env, fallback: MoveFunction): seq[Selection] = + try: + var env = env + if self.debugMoves: + log lvlDebug, &"applyMoveLisp '{move}', {env.env}, {originalSelections}" + + let originalSelections = @originalSelections + var lastSelections = originalSelections + var selections = originalSelections + + var expr = move.parseLisp() + + type Selector = enum OriginalStart, OriginalEnd, LastStart, LastEnd, CurrentStart, CurrentEnd + proc parseSelector(val: LispVal, default: Selector): Selector = + if val.kind == Symbol: + case val.sym + of "orig-start": OriginalStart + of "orig-end": OriginalEnd + of "last-start": LastStart + of "last-end": LastEnd + of "curr-start": CurrentStart + of "curr-end": CurrentEnd + of ".": default + else: + log lvlError, &"Unknown cursor selector '{val.sym}'" + default + else: + log lvlError, &"Failed to parse cursor selector '{val}'. Expected Symbol, got {val.kind}" + default + + proc selectCursor(selector: Selector, i: int, default: Cursor): Cursor = + case selector + of OriginalStart: + if i in 0.. ", selections + ) + + case name + of "num-lines": + newNumber(displayMap.buffer.visibleText.lines) + of "num-bytes": + newNumber(displayMap.buffer.visibleText.bytes) + of "same?": + newBool(selections == originalSelections) + of "original": + impl: + selections = originalSelections + of "push": + newFunc(name, proc(args {.inject.}: seq[LispVal]): LispVal = + stack.add selections + ) + of "pop": + impl: + if stack.len > 0: + selections = stack.pop() + of "start", "first": + impl: + selections = selections.mapIt(it.first.toSelection) + of "end", "last": + impl: + selections = selections.mapIt(it.last.toSelection) + of "count*": + newFunc(name, false, proc(args {.inject.}: seq[LispVal]): LispVal = + if args.len == 0 or args[0].kind != Number: + return newNil() + var count = env.getCount() + assert count != 0 + env["count"] = newNumber(count.float * args[0].num) + return newNil() + ) + of "merge": + newFunc(name, false, proc(args {.inject.}: seq[LispVal]): LispVal = + if selections.len > 0: + for i in 0.. 0: + parseSelector(args[0], OriginalStart) + else: + OriginalStart + let endSelector = if args.len > 1: + parseSelector(args[1], CurrentEnd) + else: + CurrentEnd + + if selections.len > 0: + for i in 0.. 0 and instance.host.layout.popups.last.getActiveEditor().getSome(editor): + return Editor(id: editor.id.uint64).some if instance.host.layout.tryGetCurrentEditorView().getSome(view): - return Editor(id: view.editor.DocumentEditor.idNew.uint64).some + return Editor(id: view.editor.DocumentEditor.id.uint64).some return Editor.none proc editorGetDocument(instance: ptr InstanceData; editor: Editor): Option[Document] = @@ -376,11 +411,16 @@ proc editorGetDocument(instance: ptr InstanceData; editor: Editor): Option[Docum return Document(id: document.id.uint64).some return Document.none -proc textEditorActiveTextEditor(instance: ptr InstanceData): Option[TextEditor] = +proc textEditorActiveTextEditor(instance: ptr InstanceData, options: ActiveEditorFlags): Option[TextEditor] = if instance.host == nil: return + if ActiveEditorFlag.IncludeCommandLine in options and instance.host.commands.commandLineMode() and instance.host.commands.commandLineEditor of TextDocumentEditor: + let editor = instance.host.commands.commandLineEditor + return TextEditor(id: instance.host.commands.commandLineEditor.id.uint64).some + if ActiveEditorFlag.IncludePopups in options and instance.host.layout.popups.len > 0 and instance.host.layout.popups.last.getActiveEditor().getSome(editor) and editor of TextDocumentEditor: + return TextEditor(id: editor.id.uint64).some if instance.host.layout.tryGetCurrentEditorView().getSome(view) and view.editor of TextDocumentEditor: - return TextEditor(id: view.editor.TextDocumentEditor.idNew.uint64).some + return TextEditor(id: view.editor.TextDocumentEditor.id.uint64).some return TextEditor.none proc textEditorGetDocument(instance: ptr InstanceData; editor: TextEditor): Option[TextDocument] = @@ -396,7 +436,7 @@ proc textEditorAsTextEditor(instance: ptr InstanceData; editor: Editor): Option[ if instance.host == nil: return if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor: - return TextEditor(id: editor.TextDocumentEditor.idNew.uint64).some + return TextEditor(id: editor.TextDocumentEditor.id.uint64).some return TextEditor.none proc textEditorAsTextDocument(instance: ptr InstanceData; document: Document): Option[TextDocument] = @@ -406,6 +446,68 @@ proc textEditorAsTextDocument(instance: ptr InstanceData; document: Document): O return TextDocument(id: text_document.TextDocument(document).id.uint64).some return TextDocument.none +proc textEditorLineLength(instance: ptr InstanceData; editor: TextEditor; line: int32): int32 = + if instance.host == nil: + return + if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor: + return editor.TextDocumentEditor.lineLength(line.int).int32 + +proc textEditorClearTabStops(instance: ptr InstanceData; editor: TextEditor): void = + if instance.host == nil: + return + if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor: + editor.TextDocumentEditor.clearTabStops() + +proc textEditorUndo(instance: ptr InstanceData; editor: TextEditor, checkpoint: sink string): void = + if instance.host == nil: + return + if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor: + editor.TextDocumentEditor.undo(checkpoint) + +proc textEditorRedo(instance: ptr InstanceData; editor: TextEditor, checkpoint: sink string): void = + if instance.host == nil: + return + if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor: + editor.TextDocumentEditor.redo(checkpoint) + +proc textEditorAddNextCheckpoint(instance: ptr InstanceData; editor: TextEditor, checkpoint: sink string): void = + if instance.host == nil: + return + if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor: + editor.TextDocumentEditor.addNextCheckpoint(checkpoint) + +proc textEditorCopy(instance: ptr InstanceData; editor: TextEditor, register: sink string, inclusiveEnd: bool): void = + if instance.host == nil: + return + if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor: + editor.TextDocumentEditor.copy(register, inclusiveEnd) + +proc textEditorPaste(instance: ptr InstanceData; editor: TextEditor; selections: sink seq[Selection], register: sink string, inclusiveEnd: bool): void = + if instance.host == nil: + return + if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor: + asyncSpawn editor.TextDocumentEditor.pasteAsync(selections.mapIt(it.toInternal), register, inclusiveEnd) + +proc textEditorAutoShowCompletions(instance: ptr InstanceData; editor: TextEditor): void = + if instance.host == nil: + return + if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor: + editor.TextDocumentEditor.autoShowCompletions() + +proc textEditorApplyMove(instance: ptr InstanceData; editor: TextEditor; selection: Selection; move: sink string; count: int32; wrap: bool; includeEol: bool): seq[Selection] = + if instance.host == nil: + return + if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor: + let textEditor = editor.TextDocumentEditor + return textEditor.getSelectionsForMove(@[selection.toInternal], move, count, includeEol, wrap).mapIt(it.toWasm) + +proc textEditorMultiMove(instance: ptr InstanceData; editor: TextEditor; selections: sink seq[Selection]; move: sink string; count: int32; wrap: bool; includeEol: bool): seq[Selection] = + if instance.host == nil: + return + if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor: + let textEditor = editor.TextDocumentEditor + return textEditor.getSelectionsForMove(selections.mapIt(it.toInternal), move, count, includeEol, wrap).mapIt(it.toWasm) + proc textEditorSetSelection(instance: ptr InstanceData; editor: TextEditor; s: Selection): void = if instance.host == nil: return @@ -413,6 +515,14 @@ proc textEditorSetSelection(instance: ptr InstanceData; editor: TextEditor; s: S let textEditor = editor.TextDocumentEditor textEditor.selection = ((s.first.line.int, s.first.column.int), (s.last.line.int, s.last.column.int)) +proc textEditorSetSelections(instance: ptr InstanceData; editor: TextEditor; s: sink seq[Selection]): void = + if instance.host == nil: + return + if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor: + let textEditor = editor.TextDocumentEditor + if s.len > 0: + textEditor.selections = s.mapIt(it.toInternal) + proc textEditorGetSelection(instance: ptr InstanceData; editor: TextEditor): Selection = if instance.host == nil: return @@ -423,15 +533,41 @@ proc textEditorGetSelection(instance: ptr InstanceData; editor: TextEditor): Sel else: Selection(first: Cursor(line: 1, column: 2), last: Cursor(line: 6, column: 9)) -proc textEditorEdit(instance: ptr InstanceData; editor: TextEditor; selections: sink seq[Selection]; contents: sink seq[string]): seq[Selection] = +proc textEditorGetSelections(instance: ptr InstanceData; editor: TextEditor): seq[Selection] = + if instance.host == nil: + return + if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor: + let textEditor = editor.TextDocumentEditor + let s = textEditor.selection + return editor.TextDocumentEditor.selections.mapIt(it.toWasm) + +proc textEditorEdit(instance: ptr InstanceData; editor: TextEditor; selections: sink seq[Selection]; contents: sink seq[string], inclusive: bool): seq[Selection] = if instance.host == nil: return if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor: let selections = selections.mapIt(it.toInternal) - let res = editor.TextDocumentEditor.edit(selections, contents) + let res = editor.TextDocumentEditor.edit(selections, contents, inclusiveEnd = inclusive) return res.mapIt(it.toWasm) return selections +proc textEditorDefineMove(instance: ptr InstanceData; move: sink string; fun: uint32; data: uint32): void = + if instance.host == nil: + return + + proc moveImpl(rope: Rope, move: string, selections: openArray[sca.Selection], count: int, includeEol: bool): seq[sca.Selection] {.gcsafe, raises: [].} = + var self: ptr ProcessResource + var ropeRes = RopeResource(rope: rope.slice().suffix(Point())) + let index = instance.resources.resourceNew(instance.store.context, ropeRes) + if index.isOk: + let res = instance.funcs.handleMove(fun, data, index.val.uint32, selections.mapIt(it.toWasm), count.int32, includeEol) + if res.isErr: + log lvlError, "Failed to call handleMove: " & res.err.msg + else: + return res.val.mapIt(it.toInternal) + return @[] + + instance.host.moves.registerMove(move, moveImpl) + proc textEditor_addModeChangedHandler(instance: ptr InstanceData, fun: uint32): int32 = if instance.host == nil: return @@ -443,6 +579,60 @@ proc textEditor_addModeChangedHandler(instance: ptr InstanceData, fun: uint32): log lvlError, "Failed to call handleModeChanged: " & res.err.msg return 0 +proc textEditorSetMode(instance: ptr InstanceData; editor: TextEditor, mode: sink string, exclusive: bool): void = + if instance.host == nil: + return + if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor: + editor.TextDocumentEditor.setMode(mode, exclusive) + +proc textEditorMode(instance: ptr InstanceData; editor: TextEditor): string = + if instance.host == nil: + return + if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor: + return editor.TextDocumentEditor.mode() + +proc textEditorModes(instance: ptr InstanceData; editor: TextEditor): seq[string] = + if instance.host == nil: + return + if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor: + return editor.TextDocumentEditor.modes() + +proc textEditorClearCurrentCommandHistory(instance: ptr InstanceData; editor: TextEditor, retainLast: bool) = + if instance.host == nil: + return + if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor: + editor.TextDocumentEditor.clearCurrentCommandHistory(retainLast) + +proc textEditorSaveCurrentCommandHistory(instance: ptr InstanceData; editor: TextEditor) = + if instance.host == nil: + return + if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor: + editor.TextDocumentEditor.saveCurrentCommandHistory() + +proc textEditorHideCompletions(instance: ptr InstanceData; editor: TextEditor) = + if instance.host == nil: + return + if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor: + editor.TextDocumentEditor.hideCompletions() + +proc textEditorScrollToCursor(instance: ptr InstanceData; editor: TextEditor; behaviour: Option[ScrollBehaviour]; relativePosition: float32): void = + if instance.host == nil: + return + if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor: + editor.TextDocumentEditor.scrollToCursor(sca.SelectionCursor.Last, scrollBehaviour = behaviour.mapIt(it.toInternal), relativePosition=relativePosition) + +proc textEditorSetNextSnapBehaviour(instance: ptr InstanceData; editor: TextEditor; behaviour: ScrollSnapBehaviour): void = + if instance.host == nil: + return + if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor: + editor.TextDocumentEditor.setNextSnapBehaviour(behaviour.toInternal) + +proc textEditorUpdateTargetColumn(instance: ptr InstanceData; editor: TextEditor): void = + if instance.host == nil: + return + if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor: + editor.TextDocumentEditor.updateTargetColumn() + proc textEditorCommand(instance: ptr InstanceData; editor: TextEditor, name: sink string, arguments: sink string): Result[string, CommandError] = if instance.host == nil: return @@ -454,6 +644,24 @@ proc textEditorCommand(instance: ptr InstanceData; editor: TextEditor, name: sin return results.ok($res) result.err(CommandError.NotFound) +proc textEditorRecordCurrentCommand(instance: ptr InstanceData; editor: TextEditor; registers: sink seq[string]): void = + if instance.host == nil: + return + if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor: + editor.TextDocumentEditor.recordCurrentCommand(registers) + +proc textEditorGetUsage(instance: ptr InstanceData; editor: TextEditor): string = + if instance.host == nil: + return + if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor: + return editor.TextDocumentEditor.getUsage() + +proc textEditorGetRevision(instance: ptr InstanceData; editor: TextEditor): int32 = + if instance.host == nil: + return + if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor: + return editor.TextDocumentEditor.getRevision().int32 + proc textEditorContent(instance: ptr InstanceData; editor: TextEditor): RopeResource = if instance.host == nil: return @@ -471,6 +679,106 @@ proc textDocumentContent(instance: ptr InstanceData; document: TextDocument): Ro return RopeResource(rope: textDocument.rope.clone().slice().suffix(Point())) return RopeResource(rope: createRope("").slice().suffix(Point())) +proc textEditorGetSettingRaw(instance: ptr InstanceData, editor: TextEditor, name: sink string): string = + if instance.host == nil: + return + if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor: + return $editor.TextDocumentEditor.config.get(name, newJexNull()) + +proc textEditorSetSettingRaw(instance: ptr InstanceData, editor: TextEditor, name: sink string, value: sink string) = + if instance.host == nil: + return + if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor: + try: + # todo: permissions + editor.TextDocumentEditor.config.set(name, parseJsonex(value)) + except CatchableError as e: + log lvlError, "set-setting-raw: Failed to set setting '{name}' to {value}: {e.msg}" + +proc textEditorSetSearchQueryFromMove(instance: ptr InstanceData, editor: TextEditor, move: sink string, count: int32, prefix: sink string, suffix: sink string): Selection = + if instance.host == nil: + return + if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor: + return editor.TextDocumentEditor.setSearchQueryFromMove(move, count, prefix, suffix) + +proc textEditorSetSearchQuery(instance: ptr InstanceData, editor: TextEditor, query: sink string, escapeRegex: bool, prefix: sink string, suffix: sink string): bool = + if instance.host == nil: + return + if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor: + return editor.TextDocumentEditor.setSearchQuery(query, escapeRegex, prefix, suffix) + +proc textEditorGetSearchQuery(instance: ptr InstanceData, editor: TextEditor): string = + if instance.host == nil: + return "" + if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor: + return editor.TextDocumentEditor.getSearchQuery() + return "" + +proc textEditorToggleLineComment(instance: ptr InstanceData, editor: TextEditor) = + if instance.host == nil: + return + if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor: + editor.TextDocumentEditor.toggleLineComment() + +proc textEditorInsertText(instance: ptr InstanceData, editor: TextEditor, text: sink string, autoIndent: bool) = + if instance.host == nil: + return + if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor: + editor.TextDocumentEditor.insertText(text, autoIndent) + +proc textEditorOpenSearchBar(instance: ptr InstanceData; editor: TextEditor; query: sink string; scrollToPreview: bool; selectResult: bool): void = + if instance.host == nil: + return + if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor: + editor.TextDocumentEditor.openSearchBar(query, scrollToPreview, selectResult) + +proc textEditorEvaluateExpressions(instance: ptr InstanceData; editor: TextEditor; selections: sink seq[Selection]; inclusive: bool; prefix: sink string; suffix: sink string; addSelectionIndex: bool): void = + if instance.host == nil: + return + if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor: + editor.TextDocumentEditor.evaluateExpressions(selections.mapIt(it.toInternal), inclusive, prefix, suffix, addSelectionIndex) + +proc textEditorIndent(instance: ptr InstanceData; editor: TextEditor; delta: int32): void = + if instance.host == nil: + return + if instance.host.editors.getEditor(editor.id.EditorIdNew).getSome(editor) and editor of TextDocumentEditor: + if delta >= 0: + for i in 0..= 0: + return i.some + return int64.none + +proc typesRuneAt(instance: ptr InstanceData; self: var RopeResource; a: Cursor): Rune = + return self.rope.runeAt(a.toInternal.toPoint) + +proc typesByteAt(instance: ptr InstanceData; self: var RopeResource; a: Cursor): uint8 = + return self.rope.charAt(a.toInternal.toPoint).uint8 + proc isAllowed*(permissions: FilesystemPermissions, path: string, vfs: VFS): bool = if permissions.disallowAll.get(false): return false @@ -627,6 +959,41 @@ proc coreSpawnBackground(instance: ptr InstanceData, args: sink string, executor proc coreFinishBackground(instance: ptr InstanceData) = instance.destroyRequested = true +proc registersIsReplayingCommands(instance: ptr InstanceData): bool = + if instance.host == nil: + return false + return instance.host.registers.isReplayingCommands() + +proc registersIsRecordingCommands(instance: ptr InstanceData; register: sink string): bool = + if instance.host == nil: + return false + return instance.host.registers.isRecordingCommands(register) + +proc registersSetRegisterText(instance: ptr InstanceData; text: sink string; register: sink string): void = + if instance.host == nil: + return + instance.host.registers.setRegisterText(text, register) + +proc registersGetRegisterText(instance: ptr InstanceData; register: sink string): string = + if instance.host == nil: + return + return instance.host.registers.getRegisterText(register) + +proc registersStartRecordingCommands(instance: ptr InstanceData; register: sink string): void = + if instance.host == nil: + return + instance.host.registers.startRecordingCommands(register) + +proc registersStopRecordingCommands(instance: ptr InstanceData; register: sink string): void = + if instance.host == nil: + return + instance.host.registers.stopRecordingCommands(register) + +proc registersReplayCommands(instance: ptr InstanceData; register: sink string): void = + if instance.host == nil: + return + instance.host.registers.replayCommands(register) + proc commandsDefineCommand(instance: ptr InstanceData, name: sink string, active: bool, docs: sink string, params: sink seq[(string, string)], returnType: sink string, context: sink string; fun: uint32; data: uint32): void = if instance.host == nil: @@ -644,7 +1011,10 @@ proc commandsDefineCommand(instance: ptr InstanceData, name: sink string, active return res ), ) - instance.commands.add(instance.host.commands.registerCommand(command, override = true)) + if active: + instance.commands.add(instance.host.commands.registerActiveCommand(command, override = true)) + else: + instance.commands.add(instance.host.commands.registerCommand(command, override = true)) proc commandsRunCommand(instance: ptr InstanceData, name: sink string, arguments: sink string): Result[string, CommandError] = if instance.host == nil: @@ -656,6 +1026,11 @@ proc commandsRunCommand(instance: ptr InstanceData, name: sink string, arguments return results.ok(res) result.err(CommandError.NotFound) +proc commandsExitCommandLine(instance: ptr InstanceData) = + if instance.host == nil: + return + instance.host.commands.exitCommandLine() + proc settingsGetSettingRaw(instance: ptr InstanceData, name: sink string): string = return $instance.host.settings.get(name, JsonNodeEx) @@ -680,6 +1055,9 @@ proc layoutClose(instance: ptr InstanceData; v: View, keepHidden: bool, restoreH proc layoutFocus(instance: ptr InstanceData, slot: sink string) = instance.host.layout.focusView(slot.ensureMove) +proc layoutCloseActiveView(instance: ptr InstanceData; closeOpenPopup: bool; restoreHidden: bool): void = + instance.host.layout.closeActiveView(closeOpenPopup, restoreHidden) + proc renderRenderViewFromUserId(instance: ptr InstanceData; id: sink string): Option[RenderViewResource] = if renderViewFromUserId(instance.host.layout, id).getSome(view): return RenderViewResource(view: view).some diff --git a/src/register.nim b/src/register.nim index e78c535b9..e9da3653c 100644 --- a/src/register.nim +++ b/src/register.nim @@ -2,7 +2,7 @@ import std/[strutils, tables, options] import nimsumtree/rope import scripting/[expose] import misc/[custom_logger, custom_async, util, rope_utils, array_set] -import clipboard, service, dispatch_tables +import clipboard, service, dispatch_tables, command_service {.push gcsafe.} {.push raises: [].} @@ -98,6 +98,9 @@ proc getRegisterAsync*(self: Registers, register: string, res: ptr Register): Fu return false proc recordCommand*(self: Registers, command: string, args: string, registers: openArray[string] = []) = + if self.bIsReplayingCommands: + return + template iterate(commands: untyped) = for register in commands: if not self.registers.contains(register) or self.registers[register].kind != RegisterKind.Text: @@ -159,4 +162,22 @@ proc isReplayingKeys*(self: Registers): bool {.expose("registers").} = proc isRecordingCommands*(self: Registers, registry: string): bool {.expose("registers").} = self.recordingCommands.contains(registry) +proc replayCommands*(self: Registers, register: string) {.expose("registers").} = + if not self.registers.contains(register) or self.registers[register].kind != RegisterKind.Text: + log lvlError, fmt"No commands recorded in register '{register}'" + return + + if self.bIsReplayingCommands: + log lvlError, fmt"replayCommands '{register}': Already replaying commands" + return + + log lvlInfo, &"replayCommands '{register}':\n{self.registers[register].text}" + self.bIsReplayingCommands = true + defer: + self.bIsReplayingCommands = false + + let commandService = self.services.getService(CommandService).get + for command in self.registers[register].text.splitLines: + discard commandService.handleCommand(command) + addGlobalDispatchTable "registers", genDispatchTable("registers") diff --git a/src/scripting/expose.nim b/src/scripting/expose.nim index bb9ca4d12..14c460889 100644 --- a/src/scripting/expose.nim +++ b/src/scripting/expose.nim @@ -8,8 +8,6 @@ const mapperFunctions = CacheTable"MapperFunctions" # Maps from type name (refer const typeWrapper = CacheTable"TypeWrapper" # Maps from type name (referring to nim type) to type name of the api type (from scripting_api) const functions = CacheTable"DispatcherFunctions" # Maps from scope name to list of tuples of name and wrapper const injectors = CacheTable"Injectors" # Maps from type name (referring to nim type) to function -const exposedFunctions* = CacheTable"ExposedFunctions" # Maps from type name (referring to nim type) to type name of the api type (from scripting_api) -const wasmImportedFunctions* = CacheTable"WasmImportedFunctions" template varargs*() {.pragma.} @@ -20,14 +18,6 @@ macro addTypeMap*(source: untyped, wrapper: typed, mapperFunction: typed) = macro addInjector*(name: untyped, function: typed) = injectors[$name] = function -macro addWasmImportedFunction*(moduleName: static string, name: untyped, thisSide: untyped, wasmSide: untyped) = - let n = nnkStmtList.newTree(name, thisSide, wasmSide) - for name, _ in wasmImportedFunctions: - if name == moduleName: - wasmImportedFunctions[name].add n - return - wasmImportedFunctions[moduleName] = nnkStmtList.newTree(n) - macro addFunction(name: untyped, original: typed, wrapper: typed, moduleName: static string, docs: typed) = ## Registers the nim function `name` in the module `moduleName`. `script` is a symbol referring ## to the version of this function with the 'Script' suffix, which is exported to the nim script. @@ -39,13 +29,9 @@ macro addFunction(name: untyped, original: typed, wrapper: typed, moduleName: st return functions[moduleName] = nnkStmtList.newTree(n) -macro addScriptWrapper(name: untyped, moduleName: static string, lineNumber: static int) = - let val = nnkStmtList.newTree(name, newLit($lineNumber)) - for list, _ in exposedFunctions: - if list == moduleName: - exposedFunctions[list].add val - return - exposedFunctions[moduleName] = nnkStmtList.newTree(val) +macro printDispatchStats*() = + for moduleName, functions in functions: + echo &"module '{moduleName}': {functions.len} functions" proc generateUniqueName*(moduleName: string, def: NimNode): string = result = moduleName @@ -77,18 +63,9 @@ proc removePragmas(node: var NimNode) = param[0] = name macro expose*(moduleName: static string, def: untyped): untyped = - # echo moduleName, "::", def.name.repr if not exposeScriptingApi: return def - defer: - discard - # echo result.repr - # echo "====================================================================" - - # echo def.repr - # echo def.treeRepr - var def = def let uniqueName = generateUniqueName(moduleName, def) @@ -116,40 +93,17 @@ macro expose*(moduleName: static string, def: untyped): untyped = if pureFunctionNameStr == entry[0].repr: suffix.add("2") - # defer: - # if pureFunctionNameStr == "setMove": - # echo def.treeRepr - # echo result.repr - # The wrapper function which takes JSON arguments and returns JSON and internally calls the Nim function let jsonWrapperFunctionName = ident(uniqueName & "_json") # The script function is a wrapper around impl which translates some argument types - # and inserts some arguments automatically using injectors. This function will be called from the NimScript. + # and inserts some arguments automatically using injectors. This function will be called from the json wrapper. # This function has a unique name, otherwise we can't call it from nimscript let scriptFunctionSym = ident(uniqueName & "_impl") var scriptFunction = def.copy scriptFunction[0] = nnkPostfix.newTree(ident"*", scriptFunctionSym) var callImplFromScriptFunction = nnkCall.newTree(functionName) - # Wrapper function for the script function which is inserted into NimScript. - # This has the same name as the original function and is used to get function overloading back - var scriptFunctionWrapper = def.copy - scriptFunctionWrapper[0] = nnkPostfix.newTree(ident"*", pureFunctionName) - var callScriptFuncFromScriptFuncWrapper = nnkCall.newTree(scriptFunctionSym) - - # Wrapper function for wasm code in the nim wasm wrapper library - let jsonStringWrapperFunctionName = ident(uniqueName & "_wasm") - var jsonStringWrapperFunctionWasm = def.copy - jsonStringWrapperFunctionWasm[0] = nnkPostfix.newTree(ident"*", pureFunctionName) - var callJsonStringWrapperFunctionWasmArr = ident"argsJson" - var callJsonStringWrapperFunctionWasmRes = ident"res" - var callJsonStringWrapperFunctionWasm = genAst(f=jsonStringWrapperFunctionName, res=callJsonStringWrapperFunctionWasmRes, argsJson=callJsonStringWrapperFunctionWasmArr, - argsJsonString="argsJsonString".ident): - var argsJson = newJArray() - let argsJsonString = $argsJson - let res {.used.} = f(argsJsonString.cstring) - var callScriptFuncFromJson = nnkCall.newTree(scriptFunctionSym) var mappedArgIndices = initTable[int, int]() @@ -167,7 +121,7 @@ macro expose*(moduleName: static string, def: untyped): untyped = # Argument of the JSON wrapper which calls the script function. Defined here so we can use it in the loop. let jsonArg = nskParam.genSym - # Go through each parameter in reverse, fill out the args in `callImplFromScriptFunction`, `callScriptFuncFromScriptFuncWrapper` + # Go through each parameter in reverse, fill out the args in `callImplFromScriptFunction` # and `callScriptFuncFromJson` for k in 1..argCount: let i = argCount - k @@ -184,8 +138,6 @@ macro expose*(moduleName: static string, def: untyped): untyped = if source == mappedArgumentType.repr: mappedArgumentType = target scriptFunction[3][i + 1][1] = target - scriptFunctionWrapper[3][i + 1][1] = target - jsonStringWrapperFunctionWasm[3][i + 1][1] = target break # The argument for the call to scriptFunction in the wrapper @@ -253,8 +205,6 @@ macro expose*(moduleName: static string, def: untyped): untyped = if mappedArgumentType.repr == typeName: wasInjected = true scriptFunction[3].del(i + 1) - scriptFunctionWrapper[3].del(i + 1) - jsonStringWrapperFunctionWasm[3].del(i + 1) callFromScriptArg = quote do: block: let r = `function`() @@ -265,110 +215,42 @@ macro expose*(moduleName: static string, def: untyped): untyped = if not wasInjected: callScriptFuncFromJson.insert(1, resWrapper) - callScriptFuncFromScriptFuncWrapper.insert(1, scriptFunctionWrapper.argName(i)) - - let callJsonStringWrapperFunctionWasmArg = genAst(argsJson=callJsonStringWrapperFunctionWasmArr, arg = jsonStringWrapperFunctionWasm.argName(i)): - argsJson.add arg.toJson() - - callJsonStringWrapperFunctionWasm.insert(1, callJsonStringWrapperFunctionWasmArg) callImplFromScriptFunction.insert(1, callFromScriptArg) scriptFunction[6] = quote do: `callImplFromScriptFunction` - var scriptFunctionWrapperBody = nnkStmtList.newTree() - if documentation.isSome: - scriptFunctionWrapperBody.add documentation.get - for n in runnableExampls: - scriptFunctionWrapperBody.add n - scriptFunctionWrapperBody.add callScriptFuncFromScriptFuncWrapper - scriptFunctionWrapper[6] = scriptFunctionWrapperBody - - let scriptFunctionWrapperRepr = scriptFunctionWrapper.repr - let lineNumber = def.lineInfoObj.line - - if returnType.isSome: - let returnNode = genAst(res=callJsonStringWrapperFunctionWasmRes): - try: - result = parseJson($res).jsonTo(typeof(result)) - except CatchableError: - raiseAssert(getCurrentExceptionMsg()) - callJsonStringWrapperFunctionWasm.add returnNode - - jsonStringWrapperFunctionWasm[6] = callJsonStringWrapperFunctionWasm - let jsonWrapperFunction = createJsonWrapper(scriptFunction, jsonWrapperFunctionName) # todo: why do we remove pragmas again? removePragmas(def) removePragmas(scriptFunction) - removePragmas(scriptFunctionWrapper) - removePragmas(jsonStringWrapperFunctionWasm) jsonWrapperFunction.addPragma(ident"gcsafe") scriptFunction.addPragma(ident"gcsafe") def.addPragma(ident"gcsafe") - jsonStringWrapperFunctionWasm.addPragma(ident"gcsafe") scriptFunction.addPragma(nnkExprColonExpr.newTree(ident"raises", nnkBracket.newTree())) def.addPragma(nnkExprColonExpr.newTree(ident"raises", nnkBracket.newTree())) - jsonStringWrapperFunctionWasm.addPragma(nnkExprColonExpr.newTree(ident"raises", nnkBracket.newTree())) result = quote do: `def` `scriptFunction` - static: - # This causes the function wrapper to be emitted in a file, so it can be imported in configs - addScriptWrapper(`scriptFunctionWrapperRepr`, `moduleName`, `lineNumber`) - if not def.hasCustomPragma("nojsonwrapper"): - let jsonStringWrapperFunctionReturnValue = genSym(nskVar, functionName.strVal & "WasmReturnValue") - let arg = ident"arg" - result.add jsonWrapperFunction - result.add quote do: - var `jsonStringWrapperFunctionReturnValue`: string = "" - proc `jsonStringWrapperFunctionName`*(arg: cstring): cstring {.exportc, used, gcsafe, raises: [].} = - try: - let argJson = parseJson($arg) - let res = `jsonWrapperFunctionName`(argJson) - {.gcsafe.}: - if res.isNil: - `jsonStringWrapperFunctionReturnValue` = "" - else: - `jsonStringWrapperFunctionReturnValue` = $res - return `jsonStringWrapperFunctionReturnValue`.cstring - except CatchableError: - let name = `pureFunctionNameStr` - {.push warning[BareExcept]:off.} - try: - logging.log lvlError, "Failed to run function " & name & &": Invalid arguments: {getCurrentExceptionMsg()}\n{getStackTrace()}" - except Exception: - discard - {.pop.} - return "null" - - static: - addWasmImportedFunction(`moduleName`, `jsonStringWrapperFunctionName`, `jsonStringWrapperFunctionWasm`): - proc `jsonStringWrapperFunctionName`(`arg`: cstring): cstring {.importc.} - result.add quote do: static: # This makes the function dispatchable addFunction(`pureFunctionName`, `signature`, `jsonWrapperFunctionName`, `moduleName`, `documentationStr`) - # echo result[result.len - 1].repr + # echo "===========================" + # echo result.repr macro genDispatchTable*(moduleName: static string): untyped = - defer: - discard - # echo result.repr - # echo result.treeRepr - var funcs = genSym(nskVar, "functionList") let blk = nnkStmtList.newTree() @@ -443,40 +325,3 @@ macro genDispatcher*(moduleName: static string): untyped = return quote do: proc dispatch(`command`: string, `arg`: JsonNode): Option[JsonNode] {.gcsafe, raises: [JsonCallError].} = result = `switch` - -proc generateScriptingApiPerModule*() {.compileTime.} = - var imports_content = "import \"../src/scripting_api\"\nexport scripting_api\n\n## This file is auto generated, don't modify.\n\n" - - for moduleName, list in exposedFunctions: - var script_api_content_wasm = """ -import std/[json, options] -import scripting_api, misc/myjsonutils - -## This file is auto generated, don't modify. - -""" - - for m, list in wasmImportedFunctions: - if moduleName != m: - continue - for f in list: - script_api_content_wasm.add f[2].repr - script_api_content_wasm.add "\n" - script_api_content_wasm.add f[1].repr - script_api_content_wasm.add "\n" - - let file_name = moduleName.replace(".", "_") - - echo fmt"Writing scripting/{file_name}_api_wasm.nim" - writeFile(fmt"scripting/{file_name}_api_wasm.nim", script_api_content_wasm) - - imports_content.add fmt"import {file_name}_api_wasm" & "\n" - imports_content.add fmt"export {file_name}_api_wasm" & "\n" - - when enableAst: - imports_content.add "\nconst enableAst* = true\n" - else: - imports_content.add "\nconst enableAst* = false\n" - - echo fmt"Writing scripting/plugin_api.nim" - writeFile(fmt"scripting/plugin_api.nim", imports_content) diff --git a/src/scripting/scripting_wasm.nim b/src/scripting/scripting_wasm.nim deleted file mode 100644 index ebf07147d..000000000 --- a/src/scripting/scripting_wasm.nim +++ /dev/null @@ -1,218 +0,0 @@ -import std/[macros, macrocache, genasts, json, strutils, os, sugar] -import misc/[custom_logger, custom_async, util] -import expose, vfs, plugin_service -import wasm -import wasm3, wasm3/wasmconversions - -export wasm - -{.push gcsafe.} - -logCategory "scripting-wasm" - -type - ScriptContextWasm* = ref object of PluginSystem - modules: seq[WasmModule] - - postInitializeCallbacks: seq[tuple[module: WasmModule, pfun: PFunction, callback: proc(module: WasmModule, pfun: PFunction): bool {.gcsafe.}]] - handleCallbackCallbacks: seq[tuple[module: WasmModule, pfun: PFunction, callback: proc(module: WasmModule, pfun: PFunction, id: int32, args: cstring): bool {.gcsafe.}]] - handleAnyCallbackCallbacks: seq[tuple[module: WasmModule, pfun: PFunction, callback: proc(module: WasmModule, pfun: PFunction, id: int32, args: cstring): cstring {.gcsafe.}]] - handleScriptActionCallbacks: seq[tuple[module: WasmModule, pfun: PFunction, callback: proc(module: WasmModule, pfun: PFunction, name: cstring, args: cstring): cstring {.gcsafe.}]] - - stack: seq[WasmModule] - - moduleVfs*: VFS - vfs*: VFS - -var createEditorWasmImports: proc(): WasmImports {.raises: [].} - -proc getVfsPath*(self: WasmModule): string = - result = "plugs://" - result.add self.path.splitFile.name - result.add "/" - -method getCurrentContext*(self: ScriptContextWasm): string = - result = "plugs://" - if self.stack.len > 0: - result = self.stack[^1].getVfsPath() - -macro invoke*(self: ScriptContextWasm; pName: untyped; args: varargs[typed]; returnType: typedesc): untyped = - result = quote do: - default(`returnType`) - -proc newWasmModuleAsync(file: string, editorImports: WasmImports, vfs: VFS): Future[Option[WasmModule]] {.async.} = - try: - log lvlInfo, fmt"Try to load wasm module '{file}' from app directory" - let module = await newWasmModule(file, @[editorImports], vfs) - log lvlInfo, fmt"Loaded wasm module '{file}' from app directory" - return module - except: - log lvlError, &"Failde to load wasm module '{file}': {getCurrentExceptionMsg()}\n{getCurrentException().getStackTrace()}" - return WasmModule.none - -proc loadModules(self: ScriptContextWasm, path: string): Future[void] {.async.} = - let listing = await self.vfs.getDirectoryListing(path) - - {.gcsafe.}: - var editorImports = createEditorWasmImports() - - var wasmModuleFutures = collect: - for file2 in listing.files: - if not file2.endsWith(".wasm"): - continue - if file2.endsWith(".m.wasm"): - continue - if file2.endsWith(".me.wasm"): - continue - if file2.endsWith(".c.wasm"): - continue - if not file2.endsWith(".wasm"): - continue - - let file = path // file2 - let module = newWasmModuleAsync(file, editorImports, self.vfs) - (file, module) - - for (file, future) in wasmModuleFutures: - try: - let module = await future - - if module.getSome(module): - self.moduleVfs.mount(file.splitFile.name, newInMemoryVFS()) - self.stack.add module - defer: discard self.stack.pop - - log(lvlInfo, fmt"Loaded wasm module '{file}'") - - # todo: shouldn't need to specify gcsafe here, findFunction should handle that - if findFunction(module, "postInitializeWasm", bool, proc(module: WasmModule, fun: PFunction): bool {.gcsafe.}).getSome(f): - self.postInitializeCallbacks.add (module, f.pfun, f.fun) - - if findFunction(module, "handleCallbackWasm", bool, proc(module: WasmModule, fun: PFunction, id: int32, arg: cstring): bool {.gcsafe.}).getSome(f): - self.handleCallbackCallbacks.add (module, f.pfun, f.fun) - - if findFunction(module, "handleAnyCallbackWasm", cstring, proc(module: WasmModule, fun: PFunction, id: int32, arg: cstring): cstring {.gcsafe.}).getSome(f): - self.handleAnyCallbackCallbacks.add (module, f.pfun, f.fun) - - if findFunction(module, "handleScriptActionWasm", cstring, proc(module: WasmModule, fun: PFunction, name: cstring, arg: cstring): cstring {.gcsafe.}).getSome(f): - self.handleScriptActionCallbacks.add (module, f.pfun, f.fun) - - self.modules.add module - - if findFunction(module, "plugin_main", void, proc(module: WasmModule, fun: PFunction): void {.gcsafe.}).getSome(f): - log lvlInfo, "Run plugin_main" - f.fun(module, f.pfun) - log lvlInfo, "Finished plugin_main" - - else: - log(lvlError, fmt"Failed to create wasm module for file {file}") - - except: - log lvlError, &"Failde to load wasm module '{file}': {getCurrentExceptionMsg()}\n{getCurrentException().getStackTrace()}" - -{.push raises: [].} - -method init*(self: ScriptContextWasm, path: string, vfs: VFS): Future[void] {.async.} = - self.vfs = vfs - await self.loadModules("app://config/wasm") - -method deinit*(self: ScriptContextWasm) = discard - -method reload*(self: ScriptContextWasm): Future[void] {.async.} = - self.postInitializeCallbacks.setLen 0 - self.handleCallbackCallbacks.setLen 0 - self.handleAnyCallbackCallbacks.setLen 0 - self.handleScriptActionCallbacks.setLen 0 - - self.modules.setLen 0 - - await self.loadModules("app://config/wasm") - -method tryLoadPlugin*(self: ScriptContextWasm, plugin: Plugin): Future[bool] {.async: (raises: [IOError]).} = - return false - -method postInitialize*(self: ScriptContextWasm): bool = - result = false - try: - for (m, p, f) in self.postInitializeCallbacks: - self.stack.add m - defer: discard self.stack.pop - result = f(m, p) or result - except: - log lvlError, &"Failed to run post initialize: {getCurrentExceptionMsg()}\n{getCurrentException().getStackTrace()}" - -method handleCallback*(self: ScriptContextWasm, id: int, arg: JsonNode): bool = - result = false - try: - let argStr = $arg - for (m, p, f) in self.handleCallbackCallbacks: - self.stack.add m - defer: discard self.stack.pop - if f(m, p, id.int32, argStr.cstring): - return true - except: - log lvlError, &"Failed to run callback: {getCurrentExceptionMsg()}\n{getCurrentException().getStackTrace()}" - -method handleAnyCallback*(self: ScriptContextWasm, id: int, arg: JsonNode): JsonNode = - var path = "" - try: - result = nil - let argStr = $arg - for (m, p, f) in self.handleAnyCallbackCallbacks: - path = m.path - self.stack.add m - defer: discard self.stack.pop - let str = $f(m, p, id.int32, argStr.cstring) - if str.len == 0: - continue - - try: - return str.parseJson - except: - log lvlError, &"Failed to parse json from callback {id}({arg}): '{str}' is not valid json.\n{getCurrentExceptionMsg()}" - continue - except: - log lvlError, &"Failed to run handleAnyCallback '{path}': {getCurrentExceptionMsg()}\n{getCurrentException().getStackTrace()}" - -method handleScriptAction*(self: ScriptContextWasm, name: string, args: JsonNode): JsonNode = - try: - result = nil - let argStr = $args - for (m, p, f) in self.handleScriptActionCallbacks: - self.stack.add m - defer: discard self.stack.pop - let res = $f(m, p, name.cstring, argStr.cstring) - if res.len == 0 or res.startsWith("error: "): - continue - - try: - return res.parseJson - except: - log lvlError, &"Failed to parse json from script action {name}({args}): '{res}' is not valid json.\n{getCurrentExceptionMsg()}" - continue - except: - log lvlError, &"Failed to run handleScriptAction: {getCurrentExceptionMsg()}\n{getCurrentException().getStackTrace()}" - -# Sets the implementation of createEditorWasmImports. This needs to happen late during compilation after any expose pragmas have been executed, -# because this goes through all exposed functions at compile time to create the wasm import data. -# That's why it's in a template -template createEditorWasmImportConstructor*() = - proc createEditorWasmImportsImpl(): WasmImports = - macro addEditorFunctions(imports: WasmImports): untyped = - var list = nnkStmtList.newTree() - for m, l in wasmImportedFunctions: - for f in l: - let name = f[0].strVal.newLit - let function = f[0] - - let imp = genAst(imports, name, function): - imports.addFunction(name, function) - list.add imp - - return list - - var imports = WasmImports(namespace: "env") - addEditorFunctions(imports) - return imports - - createEditorWasmImports = createEditorWasmImportsImpl diff --git a/src/scripting/wasm.nim b/src/scripting/wasm.nim deleted file mode 100644 index 579d68df1..000000000 --- a/src/scripting/wasm.nim +++ /dev/null @@ -1,364 +0,0 @@ -import std/[macros, macrocache, json, options, tables, genasts] -import misc/[custom_logger, custom_async, util, array_buffer, id] -import vfs - -logCategory "wasi" - -import wasm3, wasm3/[wasm3c, wasmconversions] - -export WasmPtr, PFunction - -type WasmModule* = ref object - env: WasmEnv - path*: string - userData: Table[string, ref RootObj] - -type WasmImports* = object - namespace*: string - functions: seq[WasmHostProc] - module: WasmModule - -proc `$`*(p: WasmPtr): string {.borrow.} -proc `+`*(p: WasmPtr, offset: SomeNumber): WasmPtr = - return WasmPtr(p.int + offset.int) - -proc addUserData*[T](self: WasmModule, userData: T) = - mixin wasmUserDataKey - let key = T.wasmUserDataKey - self.userData[key] = userData - -proc getUserData*(self: WasmModule, T: typedesc): T = - mixin wasmUserDataKey - let key = T.wasmUserDataKey - self.userData.withValue(key, val): - return val[].T - raiseAssert("No userdata for " & $T) - -proc alloc*(module: WasmModule, size: uint32): WasmPtr = - return module.env.alloc(size) - -proc stackAlloc*(module: WasmModule, size: uint32): WasmPtr = - return module.env.stackAlloc(size) - -proc stackSave*(module: WasmModule): WasmPtr = - return module.env.stackSave() - -proc stackRestore*(module: WasmModule, p: WasmPtr) = - module.env.stackRestore(p) - -proc dealloc*(module: WasmModule, p: WasmPtr) = - module.env.dealloc(p) - -proc copyMem*(module: WasmModule, dest: WasmPtr, source: pointer, len: int, offset = 0u32) = - module.env.copyMem(dest, source, len, offset) - -proc setInt32*(module: WasmModule, dest: WasmPtr, value: int32) = - module.env.setMem(value, dest.uint32) - -proc getInt32*(module: WasmModule, dest: WasmPtr): int32 = - return module.env.getFromMem(int32, dest.uint32) - -proc getString*(module: WasmModule, pos: WasmPtr): cstring = - return module.env.getString(pos) - -proc replace(node: NimNode, target: string, newNodes: openArray[NimNode]): bool = - for i, c in node: - if c.kind == nnkAccQuoted and c[0].strVal == target: - node.del(i) - for k, newNode in newNodes: - node.insert(i + k, newNode) - return true - if c.replace(target, newNodes): - return true - return false - -# Stuff for wrapping functions - -macro createHostWrapper(module: WasmModule, function: typed, outFunction: untyped): untyped = - # echo "createHostWrapper ", function.repr - - let functionBody = if function.kind == nnkSym: - function.getImpl - else: - function - - var params: seq[NimNode] = @[] - var args: seq[NimNode] = @[] - - let returnType = if functionBody[3][0].kind == nnkEmpty: bindSym"void" else: functionBody[3][0] - let argTypes = functionBody[3] - - let returnCString = returnType.repr == "cstring" - let returnString = returnType.repr == "string" - - if returnCString: - params.add bindSym"WasmPtr" - elif returnString: - params.add bindSym"uint64" - else: - params.add returnType - - for i, p in argTypes[1..^1]: - let paramType = p[1] - # echo paramType.treeRepr - - var arg = genSym(nskParam, "p" & $i) - - let isCString = paramType.repr == "cstring" - let isWasmModule = paramType.repr == "WasmModule" # todo: nicer way to detect WasmModule? - - if isCString: - params.add nnkIdentDefs.newTree(arg, bindSym"WasmPtr", newEmptyNode()) - - arg = genAst(arg, module): - block: - let res = module.getString(arg) - res - - elif isWasmModule: - arg = genAst(module): - module - - else: - params.add nnkIdentDefs.newTree(arg, paramType, newEmptyNode()) - - args.add(arg) - - var body = if returnType.repr == "void": - genAst(function): - let x = function - x(`parameters`) - - elif returnCString: - genAst(function, module): - let x = function - let str = x(`parameters`) - let len = str.len - let p: WasmPtr = module.alloc(len.uint32 + 1) - module.copyMem(p, cast[pointer](str), len + 1) - return p - - elif returnString: - genAst(function, module): - let x = function - let str = x(`parameters`) - let len = str.len - let p: WasmPtr = module.alloc(len.uint32 + 1) - module.copyMem(p, cast[pointer](str[0].addr), len + 1) - return p.uint64 or (len.uint64 shl 32) - - else: - genAst(function): - let x = function - let res = x(`parameters`) - return res - - discard body.replace("parameters", args) - - # defer: - # echo result.repr - - result = newProc(outFunction, params=params, body=body) - result.addPragma(nnkExprColonExpr.newTree(ident"raises", nnkBracket.newTree(bindSym"CatchableError"))) - -proc getWasmType(typ: NimNode): string = - # echo typ.treeRepr - case typ.repr - of "void": return "v" - of "int32", "uint32", "bool": return "i" - of "int64", "uint64": return "I" - of "float32": return "f" - of "float64", "float": return "F" - of "cstring", "pointer", "WasmPtr": return "*" - of "string": return "I" - else: - error(fmt"getWasmType: Invalid type {typ.repr}", typ) - -macro getWasmSignature(function: typed): string = - # echo "getWasmSignature" - # echo function.treeRepr - - let types = function.getType - # echo types.treeRepr - let returnType = if types[1].kind == nnkBracketExpr: - types[1][1] - else: - types[1] - - let returnTypeWasm = returnType.getWasmType - if returnTypeWasm == "": - error("Invalid return type " & returnType.repr, function) - - var signature = returnTypeWasm & "(" - - for i in 2.. ", signature - return newLit(signature) - -template addFunction*(self: var WasmImports, name: string, function: static proc) = - block: - template buildFunction(runtime, outFunction: untyped) = - let module = cast[WasmModule](m3_GetUserData(runtime)) - {.push hint[XCannotRaiseY]:off.} - createHostWrapper(module, function, outFunction) - {.pop.} - self.functions.add toWasmHostProcTemplate(buildFunction, self.namespace, name, getWasmSignature(function)) - -type - WasiFD* = distinct uint32 - -proc newWasmModule*(wasmData: ArrayBuffer, importsOld: seq[WasmImports]): Future[Option[WasmModule]] {.async.} = - try: - var allFunctions: seq[WasmHostProc] = @[] - for imp in importsOld: - allFunctions.add imp.functions - - let res = WasmModule() - - try: - res.env = loadWasmEnv(wasmData.buffer, hostProcs=allFunctions, loadAlloc=true, allocName="my_alloc", deallocName="my_dealloc", userdata=cast[pointer](res)) - except: - log lvlError, &"Failed to create wasm env: {getCurrentExceptionMsg()}\n{getCurrentException().getStackTrace()}" - return WasmModule.none - - var imports = @importsOld - for imp in imports.mitems: - imp.module = res - return res.some - - except CatchableError: - log lvlError, &"Failed to load wasm binary from array buffer: {getCurrentExceptionMsg()}\n{getCurrentException().getStackTrace()}" - return WasmModule.none - -proc newWasmModule*(path: string, importsOld: seq[WasmImports], vfs: VFS): Future[Option[WasmModule]] {.async.} = - try: - var allFunctions: seq[WasmHostProc] = @[] - for imp in importsOld: - allFunctions.add imp.functions - - let res = WasmModule(path: path) - - var content: string - try: - content = await vfs.read(path, {Binary}) - - if content.len == 0: - log lvlError, &"Failed to load wasm module file {path}" - return WasmModule.none - except CatchableError: - log lvlError, &"Failed to load wasm module file {path}: {getCurrentExceptionMsg()}\n{getCurrentException().getStackTrace()}" - return WasmModule.none - - try: - res.env = loadWasmEnv(content, hostProcs=allFunctions, loadAlloc=true, allocName="my_alloc", deallocName="my_dealloc", userdata=cast[pointer](res)) - except: - log lvlError, &"Failed to create wasm env for {path}: {getCurrentExceptionMsg()}\n{getCurrentException().getStackTrace()}" - return WasmModule.none - - var imports = @importsOld - for imp in imports.mitems: - imp.module = res - return res.some - - except CatchableError: - log lvlError, &"Failed to load wasm binary from file {path}: {getCurrentExceptionMsg()}\n{getCurrentException().getStackTrace()}" - return WasmModule.none - -macro createWasmWrapper(returnType: typedesc, typ: typedesc, body: untyped): untyped = - # echo "createWasmWrapper" - - var params: seq[NimNode] = @[] - var args: seq[NimNode] = @[] - - let returnCString = returnType.getType[1].repr == "cstring" - - var actualReturnType = if returnCString: - var actualReturnType = genAst(): - typedesc[WasmPtr] - actualReturnType - else: - returnType - - params.add returnType.getType[1] - - let moduleSym = genSym(nskParam, "module") - let pfunSym = genSym(nskParam, "pfun") - params.add nnkIdentDefs.newTree(moduleSym, typ.getType[1][2], newEmptyNode()) - params.add nnkIdentDefs.newTree(pfunSym, typ.getType[1][3], newEmptyNode()) - - for i, p in typ.getType[1][4..^1]: - let argSym = genSym(nskParam, "p" & $i) - let repr = p.repr - let isCString = p.repr == "cstring" - let isString = p.repr == "string" - - params.add nnkIdentDefs.newTree(argSym, p, newEmptyNode()) - - var arg = argSym - - if isCString: - arg = genAst(argSym, moduleSym): - block: - let p: WasmPtr = moduleSym.alloc(argSym.len.uint32 + 1) - moduleSym.copyMem(p, cast[pointer](argSym), argSym.len + 1) - p - elif isString: - arg = genAst(argSym, moduleSym): - block: - let p: WasmPtr = moduleSym.alloc(argSym.len.uint32 + 1) - moduleSym.copyMem(p, cast[ptr char](argSym.cstring), argSym.len + 1) - p.uint64 or (argSym.len.uint64 shl 32) - - args.add(arg) - - discard body.replace("returnType", [actualReturnType]) - discard body.replace("parameters", args) - discard body.replace("f", [pfunSym]) - - if returnType.getType[1].repr != "void": - if returnCString: - body[0] = genAst(value = body[0], moduleSym): - let p = value - let res = moduleSym.getString(p) - return res - else: - body[0] = nnkReturnStmt.newTree(body[0]) - - # defer: - # echo result.repr - - result = newProc(params=params, body=body) - result.addPragma(ident"gcsafe") - result.addPragma(nnkExprColonExpr.newTree(ident"raises", nnkBracket.newTree(bindSym"CatchableError"))) - -proc findFunction*(module: WasmModule, name: string, R: typedesc, T: typedesc): Option[tuple[pfun: PFunction, fun: T]] = - try: - let f = module.env.findFunction(name) - if f.isNil: - return - - {.push hint[XCannotRaiseY]:off.} - let wrapper = createWasmWrapper(R, T): - try: - `f`.call(`returnType`, `parameters`) - except WasmError as e: - raise newException(CatchableError, "Failed to call function " & e.msg, e) - {.pop.} - - result = typeof(result.get).default.some - result.get.pfun = f - result.get.fun = wrapper - except CatchableError as e: - log lvlError, &"Failed to find function {name}: {e.msg}" - return diff --git a/src/terminal_service.nim b/src/terminal_service.nim index 4a08a38fc..406b0067c 100644 --- a/src/terminal_service.nim +++ b/src/terminal_service.nim @@ -1,15 +1,14 @@ -import std/[os, streams, strutils, sequtils, strformat, typedthreads, tables, json, colors, hashes, base64, algorithm, sets, macros, bitops, deques] +import std/[os, streams, strutils, sequtils, strformat, typedthreads, tables, json, colors, hashes, base64, algorithm, sets, macros, deques] import vmath import chroma, pixie, pixie/fileformats/png import nimsumtree/[rope, arc] -import misc/[custom_logger, util, custom_unicode, custom_async, event, timer, disposable_ref, myjsonutils, render_command, embed_source, async_process] +import misc/[custom_logger, util, custom_unicode, custom_async, event, timer, disposable_ref, myjsonutils, render_command, async_process] import dispatch_tables, config_provider, events, view, layout, service, platform_service, selector_popup, vfs_service, vfs, theme import scripting/expose import platform/[tui, platform] import finder/[finder, previewer] import vterm, input, input_api, register, command_service, channel import scripting_api as api except DocumentEditor, TextDocumentEditor, AstDocumentEditor, ModelDocumentEditor, Popup, SelectorPopup -import compilation_config when defined(enableLibssh): static: @@ -994,7 +993,7 @@ proc handleProcessOutput(state: var TerminalThreadState, buffer: var string) {.r state.screen.flushDamage() state.dirty = true - except IOError as e: + except IOError: discard else: when defined(windows): @@ -1560,8 +1559,8 @@ iterator parseKittyData(s: ptr TerminalThreadState) {.closure, gcsafe, raises: [ # kittyDebugf"Read file '{path}'" try: data = readFile(path) - except IOError as e: - kittyDebugf"Failed to read file '{path}': {e.msg}" + except IOError: + kittyDebugf"Failed to read file '{path}': {getCurrentExceptionMsg()}" sendErrResponse("EBADF"): discard return @@ -1571,8 +1570,8 @@ iterator parseKittyData(s: ptr TerminalThreadState) {.closure, gcsafe, raises: [ try: data = readFile(path) removeFile(path) - except IOError as e: - kittyDebugf"Failed to read file '{path}': {e.msg}" + except IOError: + kittyDebugf"Failed to read file '{path}': {getCurrentExceptionMsg()}" sendErrResponse("EBADF"): discard return @@ -1924,7 +1923,7 @@ proc terminalThread(s: TerminalThreadState) {.thread, nimcall.} = ) var parserCallbacks = VTermStateFallbacks( - control: (proc(control: char; user: pointer): cint {.cdecl.} = + control: (proc(control: uint8; user: pointer): cint {.cdecl.} = # echo &"control '{control}'" return 1 ), @@ -1999,7 +1998,7 @@ proc terminalThread(s: TerminalThreadState) {.thread, nimcall.} = sos: (proc(frag: VTermStringFragment; user: pointer): cint {.cdecl.} = return 1 ), - reset: (proc (hard: int; user: pointer): cint {.cdecl.} = + reset: (proc (hard: cint; user: pointer): cint {.cdecl.} = let state = cast[ptr TerminalThreadState](user) # echo &"===================== reset: {hard}" if state.alternateScreen: @@ -2354,7 +2353,7 @@ when defined(enableLibssh): except CatchableError as e: log lvlError, &"Failed to create ssh connection: {e.msg}" -proc createTerminal*(self: TerminalService, width: int, height: int, command: string, args: seq[string] = @[], autoRunCommand: string = "", createPty: bool = true, kittyPathPrefix: string = "", ssh: Option[SshOptions]): Terminal {.raises: [OSError, IOError, ResourceExhaustedError, TransportError, CancelledError].} = +proc createTerminal*(self: TerminalService, width: int, height: int, command: string, args: seq[string] = @[], autoRunCommand: string = "", createPty: bool = true, kittyPathPrefix: string = "", ssh: Option[SshOptions]): Terminal {.raises: [IOError, OSError, ResourceExhaustedError].} = if ssh.isSome: var stdin = newInMemoryChannel() var stdout = newInMemoryChannel() diff --git a/src/text/custom_treesitter.nim b/src/text/custom_treesitter.nim index 462cd8be2..90ef510f6 100644 --- a/src/text/custom_treesitter.nim +++ b/src/text/custom_treesitter.nim @@ -205,10 +205,14 @@ proc getTextRangeTreesitter(payload: pointer; byteIndex: uint32; position: ts.TS proc parseCallback*(self: TSParser, oldTree: TSTree, text: GetTextCallback): TSTree = let input = TSInput( payload: text.addr, - read: cast[typeof(TSInput().read)](getTextRangeTreesitter), + # read: cast[typeof(TSInput().read)](getTextRangeTreesitter), encoding: TSInputEncoding.TSInputEncodingUTF8 ) + # Ugly hack, but on windows it complains about incompatible function pointer type because nim maps cstring to "char*" + # instead of "const char*" + {.emit: [input, ".read = (void*)(", getTextRangeTreesitter, ");"].} + let oldTreeImpl = if oldTree.isNotNil: oldTree.impl else: diff --git a/src/text/language/debugger.nim b/src/text/language/debugger.nim index 0c0c9723c..7c296353d 100644 --- a/src/text/language/debugger.nim +++ b/src/text/language/debugger.nim @@ -1064,7 +1064,7 @@ proc applyBreakpointSignsToEditor(self: Debugger, editor: TextDocumentEditor) = proc toggleBreakpointAt*(self: Debugger, editorId: EditorId, line: int) {.expose("debugger").} = ## Line is 0-based - if self.editors.getEditorForId(editorId).getSome(editor) and editor of TextDocumentEditor: + if self.editors.getEditorForId(editorId.EditorIdNew).getSome(editor) and editor of TextDocumentEditor: let path = editor.TextDocumentEditor.document.filename if not self.breakpoints.contains(path): self.breakpoints[path] = @[] @@ -1085,7 +1085,7 @@ proc toggleBreakpointAt*(self: Debugger, editorId: EditorId, line: int) {.expose proc toggleBreakpoint*(self: Debugger) {.expose("debugger").} = if self.layout.tryGetCurrentEditorView().getSome(view) and view.editor of TextDocumentEditor: - self.toggleBreakpointAt(view.editor.id, view.editor.TextDocumentEditor.selection.last.line) + self.toggleBreakpointAt(view.editor.id.EditorId, view.editor.TextDocumentEditor.selection.last.line) proc removeBreakpoint*(self: Debugger, path: string, line: int) {.expose("debugger").} = ## Line is 1-based diff --git a/src/text/language/language_server_lsp.nim b/src/text/language/language_server_lsp.nim index 2d8380ad2..c95f22897 100644 --- a/src/text/language/language_server_lsp.nim +++ b/src/text/language/language_server_lsp.nim @@ -601,7 +601,7 @@ method getSymbols*(self: LanguageServerLSP, filename: string): Future[seq[Symbol location: (line: r.range.start.line, column: r.range.start.character), name: r.name, symbolType: r.kind.toInternalSymbolKind, - filename: self.localVfs.normalize(filename), + filename: filename, ) for child in r.children: @@ -609,7 +609,7 @@ method getSymbols*(self: LanguageServerLSP, filename: string): Future[seq[Symbol location: (line: child.range.start.line, column: child.range.start.character), name: child.name, symbolType: child.kind.toInternalSymbolKind, - filename: self.localVfs.normalize(filename), + filename: filename, ) diff --git a/src/text/text_document.nim b/src/text/text_document.nim index 2899655ef..b4ac81840 100644 --- a/src/text/text_document.nim +++ b/src/text/text_document.nim @@ -1719,3 +1719,57 @@ proc trimTrailingWhitespace*(self: TextDocument) = discard self.edit(selections, selections, [""]) func isInitialized*(self: TextDocument): bool = self.isInitialized + +type IdentifierCase* = enum Camel, Pascal, Kebab, Snake, ScreamingSnake + +proc splitCase*(s: string): tuple[cas: IdentifierCase, parts: seq[string]] = + if s == "": + return (IdentifierCase.Camel, @[]) + + if s.find('_') != -1: + result.cas = IdentifierCase.Snake + result.parts = s.split('_').mapIt(custom_unicode.toLower(it)) + for r in s.runes: + if r != '_'.Rune and not r.isLower: + result.cas = IdentifierCase.ScreamingSnake + break + + elif s.find('-') != -1: + result.cas = IdentifierCase.Kebab + result.parts = s.split('-').mapIt(custom_unicode.toLower(it)) + else: + if s[0].isUpperAscii: + result.cas = IdentifierCase.Pascal + else: + result.cas = IdentifierCase.Camel + + result.parts.add "" + for r in s.runes: + if not r.isLower and result.parts.last.len > 0: + result.parts.add "" + result.parts.last.add(custom_unicode.toLower(r)) + +proc joinCase*(parts: seq[string], cas: IdentifierCase): string = + if parts.len == 0: + return "" + case cas + of IdentifierCase.Camel: + parts[0] & parts[1..^1].mapIt(it.capitalize).join("") + of IdentifierCase.Pascal: + parts.mapIt(it.capitalize).join("") + of IdentifierCase.Kebab: + parts.join("-") + of IdentifierCase.Snake: + parts.join("_") + of IdentifierCase.ScreamingSnake: + parts.mapIt(custom_unicode.toUpper(it)).join("_") + +proc cycleCase*(s: string): string = + if s.len == 0: + return s + let (cas, parts) = s.splitCase() + let nextCase = if cas == IdentifierCase.high: + IdentifierCase.low + else: + cas.succ + return parts.joinCase(nextCase) diff --git a/src/text/text_editor.nim b/src/text/text_editor.nim index e5a5aed65..2c78a1ccc 100644 --- a/src/text/text_editor.nim +++ b/src/text/text_editor.nim @@ -13,11 +13,12 @@ import document, document_editor, events, vmath, bumpy, input, custom_treesitter import completion, completion_provider_document, completion_provider_lsp, completion_provider_snippet, selector_popup_builder, dispatch_tables, register import config_provider, service, layout, platform_service, vfs, vfs_service, command_service, toast -import diff, plugin_service +import diff, plugin_service, move_database import workspaces/workspace import finder/[previewer, finder] import vcs/vcs import overlay_map, tab_map, wrap_map, diff_map, display_map +import lisp from language/lsp_types import CompletionList, CompletionItem, InsertTextFormat, TextEdit, Position, asTextEdit, asInsertReplaceEdit, toJsonHook, CodeAction, CodeActionResponse, CodeActionKind, @@ -231,6 +232,7 @@ type TextDocumentEditor* = ref object of DocumentEditor plugins: PluginService registers: Registers workspace: Workspace + moveDatabase: MoveDatabase vfsService: VFSService vfs*: VFS commands*: CommandService @@ -381,6 +383,8 @@ type TextDocumentEditor* = ref object of DocumentEditor debugSettings*: DebugSettings settings*: TextEditorSettings + moveFallbacks: MoveFunction + type TextDocumentEditorService* = ref object of Service TextDocumentFactory* = ref object of DocumentFactory @@ -441,7 +445,7 @@ proc handleInput(self: TextDocumentEditor, input: string, record: bool): EventRe proc showCompletionWindow(self: TextDocumentEditor) proc updateCompletionsFromEngine(self: TextDocumentEditor) proc hideCompletions*(self: TextDocumentEditor) -proc getSelectionForMove*(self: TextDocumentEditor, cursor: Cursor, move: string, count: int = 0): Selection +proc getSelectionForMove*(self: TextDocumentEditor, cursor: Cursor, move: string, count: int = 0, includeEol: bool = true): Selection proc extendSelectionWithMove*(self: TextDocumentEditor, selection: Selection, move: string, count: int = 0): Selection proc updateTargetColumn*(self: TextDocumentEditor, cursor: SelectionCursor = Last) proc updateInlayHints*(self: TextDocumentEditor) @@ -453,7 +457,7 @@ proc centerCursor*(self: TextDocumentEditor, cursor: SelectionCursor = Selection proc centerCursor*(self: TextDocumentEditor, cursor: Cursor, relativePosition: float = 0.5) proc getContextWithMode*(self: TextDocumentEditor, context: string): string proc scrollToCursor*(self: TextDocumentEditor, cursor: SelectionCursor = SelectionCursor.Config, margin: Option[float] = float.none, scrollBehaviour: Option[ScrollBehaviour] = ScrollBehaviour.none, relativePosition: float = 0.5) -proc getFileName(self: TextDocumentEditor): string +proc getFileName*(self: TextDocumentEditor): string proc closeDiff*(self: TextDocumentEditor) proc setNextSnapBehaviour*(self: TextDocumentEditor, snapBehaviour: ScrollSnapBehaviour) proc numDisplayLines*(self: TextDocumentEditor): int @@ -1181,7 +1185,7 @@ method handleScroll*(self: TextDocumentEditor, scroll: Vec2, mousePosWindow: Vec proc getTextDocumentEditor(wrapper: api.TextDocumentEditor): Option[TextDocumentEditor] = {.gcsafe.}: if gServices.getService(DocumentEditorService).getSome(editors): - if editors.getEditorForId(wrapper.id).getSome(editor): + if editors.getEditorForId(wrapper.id.EditorIdNew).getSome(editor): if editor of TextDocumentEditor: return editor.TextDocumentEditor.some return TextDocumentEditor.none @@ -1203,18 +1207,18 @@ proc enableAutoReload(self: TextDocumentEditor, enabled: bool) {.expose: "editor proc setLanguage(self: TextDocumentEditor, language: string) {.expose: "editor.text".} = self.document.languageId = language -proc getFileName(self: TextDocumentEditor): string {.expose: "editor.text".} = +proc getFileName*(self: TextDocumentEditor): string = if self.document.isNil: return "" return self.document.filename -proc lineCount(self: TextDocumentEditor): int {.expose: "editor.text".} = +proc lineCount(self: TextDocumentEditor): int = return self.document.numLines -proc lineLength*(self: TextDocumentEditor, line: int): int {.expose: "editor.text".} = +proc lineLength*(self: TextDocumentEditor, line: int): int = return self.document.lineLength(line) -proc numDisplayLines*(self: TextDocumentEditor): int {.expose: "editor.text".} = +proc numDisplayLines*(self: TextDocumentEditor): int = return self.displayMap.toDisplayPoint(self.document.rope.summary.lines).row.int + 1 proc displayEndPoint*(self: TextDocumentEditor): DisplayPoint = @@ -1226,13 +1230,13 @@ proc endDisplayPoint*(self: TextDocumentEditor): DisplayPoint = proc endPoint*(self: TextDocumentEditor): Point = return self.displayMap.buffer.visibleText.endPoint -proc numWrapLines*(self: TextDocumentEditor): int {.expose: "editor.text".} = +proc numWrapLines*(self: TextDocumentEditor): int = return self.displayMap.wrapMap.endWrapPoint.row.int + 1 proc wrapEndPoint*(self: TextDocumentEditor): WrapPoint = return self.displayMap.wrapMap.endWrapPoint -proc screenLineCount(self: TextDocumentEditor): int {.expose: "editor.text".} = +proc screenLineCount*(self: TextDocumentEditor): int = ## Returns the number of lines that can be shown on the screen ## This value depends on the size of the view this editor is in and the font size # todo @@ -1364,11 +1368,11 @@ proc evaluateExpressionAsync(self: TextDocumentEditor, selections: Selections, i else: self.selections = selections -proc evaluateExpressions(self: TextDocumentEditor, selections: Selections, inclusiveEnd: bool = false, prefix: string = "", suffix: string = "", addSelectionIndex: bool = false) {.expose: "editor.text".} = +proc evaluateExpressions*(self: TextDocumentEditor, selections: Selections, inclusiveEnd: bool = false, prefix: string = "", suffix: string = "", addSelectionIndex: bool = false) {.expose: "editor.text".} = asyncSpawn self.evaluateExpressionAsync(selections, inclusiveEnd, prefix, suffix, addSelectionIndex) -proc doMoveCursorLine(self: TextDocumentEditor, cursor: Cursor, offset: int, - wrap: bool = false, includeAfter: bool = false): Cursor {.expose: "editor.text".} = +# todo: remove +proc doMoveCursorLine(self: TextDocumentEditor, cursor: Cursor, offset: int, wrap: bool = false, includeAfter: bool = false): Cursor = var cursor = cursor let line = cursor.line + offset if line < 0: @@ -1381,13 +1385,11 @@ proc doMoveCursorLine(self: TextDocumentEditor, cursor: Cursor, offset: int, cursor.column = self.displayMap.toPoint(wrapPoint(wrapPoint.row.int, self.targetColumn)).column.int return self.clampCursor(cursor, includeAfter) -proc getDefaultScrollBehaviour(self: TextDocumentEditor): ScrollBehaviour {.expose: "editor.text".} = - self.defaultScrollBehaviour - proc setDefaultScrollBehaviour(self: TextDocumentEditor, scrollBehaviour: ScrollBehaviour) {.expose: "editor.text".} = self.defaultScrollBehaviour = scrollBehaviour -proc doMoveCursorVisualLine(self: TextDocumentEditor, cursor: Cursor, offset: int, wrap: bool = false, includeAfter: bool = false, targetColumn: Option[int] = int.none): Cursor {.expose: "editor.text".} = +# todo: remove +proc doMoveCursorVisualLine(self: TextDocumentEditor, cursor: Cursor, offset: int, wrap: bool = false, includeAfter: bool = false, targetColumn: Option[int] = int.none): Cursor = let targetColumn = targetColumn.get(self.targetColumn) let wrapPointOld = self.displayMap.toWrapPoint(cursor.toPoint) let wrapPoint = wrapPoint(max(wrapPointOld.row.int + offset, 0), targetColumn).clamp(wrapPoint()...self.wrapEndPoint) @@ -1415,34 +1417,26 @@ proc doMoveCursorVisualLine(self: TextDocumentEditor, cursor: Cursor, offset: in return cursor return self.clampCursor(newCursor, includeAfter) -proc doMoveCursorHome(self: TextDocumentEditor, cursor: Cursor, offset: int, wrap: bool, - includeAfter: bool): Cursor {.expose: "editor.text".} = +# todo: remove +proc doMoveCursorHome(self: TextDocumentEditor, cursor: Cursor, offset: int, wrap: bool, includeAfter: bool): Cursor = return (cursor.line, 0) -proc doMoveCursorEnd(self: TextDocumentEditor, cursor: Cursor, offset: int, wrap: bool, - includeAfter: bool): Cursor {.expose: "editor.text".} = +# todo: remove +proc doMoveCursorEnd(self: TextDocumentEditor, cursor: Cursor, offset: int, wrap: bool, includeAfter: bool): Cursor = return (cursor.line, self.document.rope.lastValidIndex cursor.line) -proc doMoveCursorPrevFindResult(self: TextDocumentEditor, cursor: Cursor, offset: int, - wrap: bool, includeAfter: bool): Cursor {.expose: "editor.text".} = - return self.getPrevFindResult(cursor, offset, includeAfter=includeAfter).first - -proc doMoveCursorNextFindResult(self: TextDocumentEditor, cursor: Cursor, offset: int, - wrap: bool, includeAfter: bool): Cursor {.expose: "editor.text".} = - return self.getNextFindResult(cursor, offset, includeAfter=includeAfter).first - -proc doMoveCursorLineCenter(self: TextDocumentEditor, cursor: Cursor, offset: int, wrap: bool, - includeAfter: bool): Cursor {.expose: "editor.text".} = +# todo: remove +proc doMoveCursorLineCenter(self: TextDocumentEditor, cursor: Cursor, offset: int, wrap: bool, includeAfter: bool): Cursor = return (cursor.line, self.document.lineLength(cursor.line) div 2) -proc doMoveCursorCenter(self: TextDocumentEditor, cursor: Cursor, offset: int, wrap: bool, - includeAfter: bool): Cursor {.expose: "editor.text".} = +# todo: remove +proc doMoveCursorCenter(self: TextDocumentEditor, cursor: Cursor, offset: int, wrap: bool, includeAfter: bool): Cursor = let r = self.visibleDisplayRange() let line = clamp((r.a.row.int + r.b.row.int) div 2, 0, self.numDisplayLines - 1) return self.displayMap.toPoint(displayPoint(line, self.targetColumn)).toCursor -proc doMoveCursorColumn(self: TextDocumentEditor, cursor: Cursor, offset: int, - wrap: bool = true, includeAfter: bool = true): Cursor {.expose: "editor.text".} = +# todo: remove +proc doMoveCursorColumn(self: TextDocumentEditor, cursor: Cursor, offset: int, wrap: bool = true, includeAfter: bool = true): Cursor = var cursor = cursor if cursor.line notin 0..= 0: - let line = editor.document.getLine(res.line) - res.column = min(res.column, line.len - 1) - while line.len > 0 and res.column >= 0: - let c = line.charAt(res.column) - # debugf"findSurroundStart: {res} -> {depth}, '{c}'" - if c == c1 and (depth < 1 or c0 != c1): - inc depth - if depth == 0: - return res.some - elif c == c0: - dec depth - if depth == 0: - return res.some - dec res.column - - if res.line == 0: - return Cursor.none - - res = (res.line - 1, editor.lineLength(res.line - 1) - 1) - - return Cursor.none - -proc findSurroundEnd*(editor: TextDocumentEditor, cursor: Cursor, count: int, c0: char, c1: char, - depth: int = 1): Option[Cursor] {.expose: "editor.text".} = - let lineCount = editor.lineCount - var depth = depth - var res = cursor - - # todo: use RopeCursor - while res.line < lineCount: - let line = editor.document.getLine(res.line) - res.column = min(res.column, line.len - 1) - while line.len > 0 and res.column < line.len: - let c = line.charAt(res.column) - # echo &"findSurroundEnd: {res} -> {depth}, '{c}'" - if c == c0 and (depth < 1 or c0 != c1): - inc depth - if depth == 0: - return res.some - elif c == c1: - dec depth - if depth == 0: - return res.some - inc res.column - - if res.line == lineCount - 1: - return Cursor.none - - res = (res.line + 1, 0) - - return Cursor.none - proc toggleFlag*(self: TextDocumentEditor, key: string) {.expose("editor.text").} = try: let value = self.config.get(key, false) @@ -1643,73 +1578,50 @@ proc setMode*(self: TextDocumentEditor, mode: string, exclusive: bool = true) {. proc setDefaultMode*(self: TextDocumentEditor) {.expose("editor.text").} = self.setMode(self.settings.defaultMode.get()) -proc mode*(self: TextDocumentEditor): string {.expose("editor.text").} = +proc mode*(self: TextDocumentEditor): string = ## Returns the current mode of the text editor, or "" if there is no mode let modes = self.settings.modes.get() if modes.len > 0: return modes.last return "" -proc getContextWithMode(self: TextDocumentEditor, context: string): string {.expose("editor.text").} = +proc modes*(self: TextDocumentEditor): seq[string] = + ## Returns the current modes of the text editor + return self.settings.modes.get() + +proc getContextWithMode(self: TextDocumentEditor, context: string): string = ## Appends the current mode to context return context & "." & $self.mode -proc updateTargetColumn*(self: TextDocumentEditor, cursor: SelectionCursor = Last) {. - expose("editor.text").} = +proc updateTargetColumn*(self: TextDocumentEditor, cursor: SelectionCursor = Last) = let cursor = self.getCursor(cursor) let wrapPoint = self.displayMap.toWrapPoint(cursor.toPoint) self.targetColumn = wrapPoint.column.int -proc invertSelection(self: TextDocumentEditor) {.expose("editor.text").} = - ## Inverts the current selection. Discards all but the last cursor. - self.selection = (self.selection.last, self.selection.first) - -proc getRevision*(self: TextDocumentEditor): int {.expose("editor.text").} = +proc getRevision*(self: TextDocumentEditor): int = return self.document.revision -proc getUsage*(self: TextDocumentEditor): string {.expose("editor.text").} = +proc getUsage*(self: TextDocumentEditor): string = return self.usage -proc getChar*(self: TextDocumentEditor, cursor: Cursor): char {.expose("editor.text").} = +proc getChar*(self: TextDocumentEditor, cursor: Cursor): char = return self.document.rope.slice(Point).charAt(cursor.toPoint) -proc getText*(self: TextDocumentEditor, selection: Selection, inclusiveEnd: bool = false): - string {.expose("editor.text").} = +proc getText*(self: TextDocumentEditor, selection: Selection, inclusiveEnd: bool = false): string = return self.document.contentString(selection, inclusiveEnd) -proc getLine*(self: TextDocumentEditor, line: int): string {.expose("editor.text").} = +proc getLine*(self: TextDocumentEditor, line: int): string = return $self.document.getLine(line) -proc insert*(self: TextDocumentEditor, selections: seq[Selection], text: string, notify: bool = true, - record: bool = true): seq[Selection] {.expose("editor.text").} = +proc insert*(self: TextDocumentEditor, selections: seq[Selection], text: string, notify: bool = true, record: bool = true): seq[Selection] = return self.document.edit(selections, self.selections, [text], notify, record) -proc insertMulti*(self: TextDocumentEditor, selections: seq[Selection], texts: seq[string], notify: bool = true, - record: bool = true): seq[Selection] {.expose("editor.text").} = - return self.document.edit(selections, self.selections, texts, notify, record) - -proc delete*(self: TextDocumentEditor, selections: seq[Selection], notify: bool = true, - record: bool = true, inclusiveEnd: bool = false): seq[Selection] {.expose("editor.text").} = +proc delete*(self: TextDocumentEditor, selections: seq[Selection], notify: bool = true, record: bool = true, inclusiveEnd: bool = false): seq[Selection] = return self.document.edit(selections, self.selections, [""], notify, record, inclusiveEnd=inclusiveEnd) proc edit*(self: TextDocumentEditor, selections: seq[Selection], texts: seq[string], - notify: bool = true, record: bool = true, inclusiveEnd: bool = false): seq[Selection] {. - expose("editor.text").} = - return self.document.edit(selections, self.selections, texts, notify, record, - inclusiveEnd=inclusiveEnd) - -proc deleteLines(self: TextDocumentEditor, slice: Slice[int], oldSelections: Selections) {. - expose("editor.text").} = - var selection: Selection = ( - (slice.a.clamp(0, self.lineCount - 1), 0), - (slice.b.clamp(0, self.lineCount - 1), 0) - ).normalized - selection.last.column = self.document.rope.lastValidIndex(selection.last.line) - if selection.last.line < self.document.numLines - 1: - selection.last = (selection.last.line + 1, 0) - elif selection.first.line > 0: - selection.first = (selection.first.line - 1, self.document.rope.lastValidIndex(selection.first.line - 1)) - discard self.document.edit([selection], oldSelections, [""]) + notify: bool = true, record: bool = true, inclusiveEnd: bool = false): seq[Selection] = + return self.document.edit(selections, self.selections, texts, notify, record, inclusiveEnd=inclusiveEnd) proc selectPrev(self: TextDocumentEditor) {.expose("editor.text").} = if self.selectionHistory.len > 0: @@ -1735,42 +1647,7 @@ proc selectNext(self: TextDocumentEditor) {.expose("editor.text").} = self.scrollToCursor(self.selection.last) self.setNextSnapBehaviour(ScrollSnapBehaviour.MinDistanceOffscreen) -proc selectInside*(self: TextDocumentEditor, cursor: Cursor) {.expose("editor.text").} = - self.selection = self.getSelectionForMove(cursor, "word") - # todo - # let regex = re("[a-zA-Z0-9_]") - # var first = cursor.column - # # echo self.document.getLine(cursor.line), ", ", first, ", ", - # self.document.getLine(cursor.line).matchLen(regex, start = first - 1) - # while first > 0 and self.document.getLine(cursor.line).matchLen(regex, start = first - 1) == 1: - # first -= 1 - # var last = cursor.column - # while last < self.document.lineLength(cursor.line) and - # self.document.getLine(cursor.line).matchLen(regex, start = last) == 1: - # last += 1 - # self.selection = ((cursor.line, first), (cursor.line, last)) - -proc selectInsideCurrent(self: TextDocumentEditor) {.expose("editor.text").} = - self.selection = self.extendSelectionWithMove(self.selection, "word") - -proc selectLine*(self: TextDocumentEditor, line: int) {.expose("editor.text").} = - self.selection = ((line, 0), (line, self.document.rope.lastValidIndex(line))) - -proc selectLineCurrent(self: TextDocumentEditor) {.expose("editor.text").} = - let first = ( - (self.selection.first.line, 0), - (self.selection.first.line, self.document.rope.lastValidIndex(self.selection.first.line)) - ) - let last = ( - (self.selection.last.line, 0), - (self.selection.last.line, self.document.rope.lastValidIndex(self.selection.last.line)) - ) - let wasBackwards = self.selection.isBackwards - self.selection = first or last - if wasBackwards: - self.selection = self.selection.reverse - -proc getParentNodeSelection(self: TextDocumentEditor, selection: Selection, includeAfter: bool = true): Selection {.expose("editor.text").} = +proc getParentNodeSelection(self: TextDocumentEditor, selection: Selection, includeAfter: bool = true): Selection = if self.document.tsTree.isNil: return selection @@ -1787,7 +1664,7 @@ proc getParentNodeSelection(self: TextDocumentEditor, selection: Selection, incl result = node.getRange.toSelection result = self.includeSelectionEnd(result, includeAfter) -proc getNextNamedSiblingNodeSelection(self: TextDocumentEditor, selection: Selection, includeAfter: bool = true): Option[Selection] {.expose("editor.text").} = +proc getNextNamedSiblingNodeSelection(self: TextDocumentEditor, selection: Selection, includeAfter: bool = true): Option[Selection] = if self.document.tsTree.isNil: return Selection.none @@ -1804,7 +1681,7 @@ proc getNextNamedSiblingNodeSelection(self: TextDocumentEditor, selection: Selec return Selection.none -proc getNextSiblingNodeSelection(self: TextDocumentEditor, selection: Selection, includeAfter: bool = true): Option[Selection] {.expose("editor.text").} = +proc getNextSiblingNodeSelection(self: TextDocumentEditor, selection: Selection, includeAfter: bool = true): Option[Selection] = if self.document.tsTree.isNil: return Selection.none @@ -1821,14 +1698,9 @@ proc getNextSiblingNodeSelection(self: TextDocumentEditor, selection: Selection, return Selection.none -proc getParentNodeSelections(self: TextDocumentEditor, selections: Selections, includeAfter: bool = true): Selections {.expose("editor.text").} = +proc getParentNodeSelections(self: TextDocumentEditor, selections: Selections, includeAfter: bool = true): Selections = return selections.mapIt(self.getParentNodeSelection(it, includeAfter)) -proc selectParentTs(self: TextDocumentEditor, selection: Selection, includeAfter: bool = true) {.expose("editor.text").} = - if self.document.tsTree.isNil: - return - self.selection = self.getParentNodeSelection(selection, includeAfter) - proc printTreesitterMemoryUsage*(self: TextDocumentEditor) {.expose("editor.text").} = let allocated = custom_treesitter.tsAllocated let freed = custom_treesitter.tsFreed @@ -1855,11 +1727,12 @@ proc printTreesitterTreeUnderCursor*(self: TextDocumentEditor) {.expose("editor. toasts.showToast("Treesitter tree", $node, "info") log lvlInfo, $node +# todo proc selectParentCurrentTs*(self: TextDocumentEditor, includeAfter: bool = true) {.expose("editor.text").} = self.`selections=`(self.getParentNodeSelections(self.selections, includeAfter), addToHistory = true.some) proc getNextNodeWithSameType*(self: TextDocumentEditor, selection: Selection, offset: int = 0, - includeAfter: bool = true, wrap: bool = true, stepIn: bool = true, stepOut: bool = true): Option[Selection] {.expose("editor.text").} = + includeAfter: bool = true, wrap: bool = true, stepIn: bool = true, stepOut: bool = true): Option[Selection] = if self.document.tsTree.isNil: return Selection.none @@ -1916,7 +1789,7 @@ proc getNextNodeWithSameType*(self: TextDocumentEditor, selection: Selection, of return Selection.none -proc shouldShowCompletionsAt*(self: TextDocumentEditor, cursor: Cursor): bool {.expose("editor.text").} = +proc shouldShowCompletionsAt*(self: TextDocumentEditor, cursor: Cursor): bool = ## Returns true if the completion window should automatically open at the given position # todo: use RopeCursor if cursor.column <= 0 or cursor.column > self.document.rope.lineLen(cursor.line): @@ -1936,7 +1809,7 @@ proc shouldShowCompletionsAt*(self: TextDocumentEditor, cursor: Cursor): bool {. return false -proc autoShowCompletions*(self: TextDocumentEditor) {.expose("editor.text").} = +proc autoShowCompletions*(self: TextDocumentEditor) = if self.disableCompletions: return if self.shouldShowCompletionsAt(self.selection.last): @@ -1993,8 +1866,7 @@ proc insertText*(self: TextDocumentEditor, text: string, autoIndent: bool = true texts.setLen(0) for s in selections.mitems: - let openLocation = self.findSurroundStart((s.first.line, s.first.column - 1), - 0, open, close, 1).getOr: + let openLocation = self.document.rope.findSurroundStart((s.first.line, s.first.column - 1), open, close, 1).getOr: texts.add text continue @@ -2167,11 +2039,10 @@ proc copyAsync*(self: TextDocumentEditor, register: string, inclusiveEnd: bool): self.registers.setRegisterAsync(register, Register(kind: Rope, rope: text.move)).await -proc copy*(self: TextDocumentEditor, register: string = "", inclusiveEnd: bool = false) {. - expose("editor.text").} = +proc copy*(self: TextDocumentEditor, register: string = "", inclusiveEnd: bool = false) {.expose("editor.text").} = asyncSpawn self.copyAsync(register, inclusiveEnd) -proc pasteAsync*(self: TextDocumentEditor, registerName: string, inclusiveEnd: bool = false): +proc pasteAsync*(self: TextDocumentEditor, selections: seq[Selection], registerName: string, inclusiveEnd: bool = false): Future[void] {.async.} = log lvlInfo, fmt"paste register from '{registerName}', inclusiveEnd: {inclusiveEnd}" @@ -2184,26 +2055,26 @@ proc pasteAsync*(self: TextDocumentEditor, registerName: string, inclusiveEnd: b let numLines = register.numLines() - let newSelections = if numLines == self.selections.len and numLines > 1: + let newSelections = if numLines == selections.len and numLines > 1: case register.kind of RegisterKind.Text: let lines = register.text.splitLines() - self.document.edit(self.selections, self.selections, lines, notify=true, record=true, inclusiveEnd=inclusiveEnd).mapIt(it.last.toSelection) + self.document.edit(selections, selections, lines, notify=true, record=true, inclusiveEnd=inclusiveEnd).mapIt(it.last.toSelection) of RegisterKind.Rope: let lines = register.rope.splitLines() - self.document.edit(self.selections, self.selections, lines, notify=true, record=true, inclusiveEnd=inclusiveEnd).mapIt(it.last.toSelection) + self.document.edit(selections, selections, lines, notify=true, record=true, inclusiveEnd=inclusiveEnd).mapIt(it.last.toSelection) else: case register.kind of RegisterKind.Text: - self.document.edit(self.selections, self.selections, [register.text.move], notify=true, record=true, inclusiveEnd=inclusiveEnd).mapIt(it.last.toSelection) + self.document.edit(selections, selections, [register.text.move], notify=true, record=true, inclusiveEnd=inclusiveEnd).mapIt(it.last.toSelection) of RegisterKind.Rope: - self.document.edit(self.selections, self.selections, [register.rope.move], notify=true, record=true, inclusiveEnd=inclusiveEnd).mapIt(it.last.toSelection) + self.document.edit(selections, selections, [register.rope.move], notify=true, record=true, inclusiveEnd=inclusiveEnd).mapIt(it.last.toSelection) # add list of selections for what was just pasted to history - if newSelections.len == self.selections.len: + if newSelections.len == selections.len: var tempSelections = newSelections for i in 0..tempSelections.high: - tempSelections[i].first = self.selections[i].first + tempSelections[i].first = selections[i].first self.selections = tempSelections self.selections = newSelections @@ -2211,9 +2082,8 @@ proc pasteAsync*(self: TextDocumentEditor, registerName: string, inclusiveEnd: b self.setNextSnapBehaviour(ScrollSnapBehaviour.Always) self.markDirty() -proc paste*(self: TextDocumentEditor, registerName: string = "", inclusiveEnd: bool = false) {. - expose("editor.text").} = - asyncSpawn self.pasteAsync(registerName, inclusiveEnd) +proc paste*(self: TextDocumentEditor, registerName: string = "", inclusiveEnd: bool = false) {.expose("editor.text").} = + asyncSpawn self.pasteAsync(self.selections, registerName, inclusiveEnd) proc scrollText*(self: TextDocumentEditor, amount: float32) {.expose("editor.text").} = if self.disableScrolling: @@ -2237,22 +2107,19 @@ proc scrollLines(self: TextDocumentEditor, amount: int) {.expose("editor.text"). self.markDirty() -proc duplicateLastSelection*(self: TextDocumentEditor) {.expose("editor.text").} = - let newSelection = self.doMoveCursorColumn(self.selections[self.selections.high].last, 1).toSelection - self.selections = self.selections & @[newSelection] - +# todo proc addCursorBelow*(self: TextDocumentEditor) {.expose("editor.text").} = let newCursor = self.doMoveCursorLine(self.selections[self.selections.high].last, 1).toSelection if not self.selections.contains(newCursor): self.selections = self.selections & @[newCursor] +# todo proc addCursorAbove*(self: TextDocumentEditor) {.expose("editor.text").} = let newCursor = self.doMoveCursorLine(self.selections[self.selections.high].last, -1).toSelection if not self.selections.contains(newCursor): self.selections = self.selections & @[newCursor] -proc getPrevFindResult*(self: TextDocumentEditor, cursor: Cursor, offset: int = 0, - includeAfter: bool = true, wrap: bool = true): Selection {.expose("editor.text").} = +proc getPrevFindResult*(self: TextDocumentEditor, cursor: Cursor, offset: int = 0, includeAfter: bool = true, wrap: bool = true): Selection = self.updateSearchResults() if self.searchResults.len == 0: @@ -2279,8 +2146,7 @@ proc getPrevFindResult*(self: TextDocumentEditor, cursor: Cursor, offset: int = if not includeAfter: result.last = self.doMoveCursorColumn(result.last, -1, wrap = false) -proc getNextFindResult*(self: TextDocumentEditor, cursor: Cursor, offset: int = 0, - includeAfter: bool = true, wrap: bool = true): Selection {.expose("editor.text").} = +proc getNextFindResult*(self: TextDocumentEditor, cursor: Cursor, offset: int = 0, includeAfter: bool = true, wrap: bool = true): Selection = self.updateSearchResults() if self.searchResults.len == 0: @@ -2307,19 +2173,18 @@ proc getNextFindResult*(self: TextDocumentEditor, cursor: Cursor, offset: int = if not includeAfter: result.last = self.doMoveCursorColumn(result.last, -1, wrap = false) -proc createAnchors*(self: TextDocumentEditor, selections: Selections): seq[(Anchor, Anchor)] {.expose("editor.text").} = +proc createAnchors*(self: TextDocumentEditor, selections: Selections): seq[(Anchor, Anchor)] = if self.document.requiresLoad: return @[] let snapshot {.cursor.} = self.document.buffer.snapshot return selections.mapIt (snapshot.anchorAfter(it.first.toPoint), snapshot.anchorBefore(it.last.toPoint)) -proc resolveAnchors*(self: TextDocumentEditor, anchors: seq[(Anchor, Anchor)]): Selections {.expose("editor.text").} = +proc resolveAnchors*(self: TextDocumentEditor, anchors: seq[(Anchor, Anchor)]): Selections = if self.document.requiresLoad: return @[] return anchors.mapIt (it[0].summaryOpt(Point, self.snapshot).get(Point()), it[1].summaryOpt(Point, self.snapshot).get(Point())).toSelection -proc getPrevDiagnostic*(self: TextDocumentEditor, cursor: Cursor, severity: int = 0, - offset: int = 0, includeAfter: bool = true, wrap: bool = true): Selection {.expose("editor.text").} = +proc getPrevDiagnostic*(self: TextDocumentEditor, cursor: Cursor, severity: int = 0, offset: int = 0, includeAfter: bool = true, wrap: bool = true): Selection = self.document.resolveDiagnosticAnchors() @@ -2358,8 +2223,7 @@ proc getPrevDiagnostic*(self: TextDocumentEditor, cursor: Cursor, severity: int return wrapped return cursor.toSelection -proc getNextDiagnostic*(self: TextDocumentEditor, cursor: Cursor, severity: int = 0, - offset: int = 0, includeAfter: bool = true, wrap: bool = true): Selection {.expose("editor.text").} = +proc getNextDiagnostic*(self: TextDocumentEditor, cursor: Cursor, severity: int = 0, offset: int = 0, includeAfter: bool = true, wrap: bool = true): Selection = self.document.resolveDiagnosticAnchors() @@ -2410,7 +2274,7 @@ proc closeDiff*(self: TextDocumentEditor) {.expose("editor.text").} = self.diffDocument = nil self.markDirty() -proc getPrevChange*(self: TextDocumentEditor, cursor: Cursor): Selection {.expose("editor.text").} = +proc getPrevChange*(self: TextDocumentEditor, cursor: Cursor): Selection = if self.diffChanges.isNone: return cursor.toSelection @@ -2420,13 +2284,13 @@ proc getPrevChange*(self: TextDocumentEditor, cursor: Cursor): Selection {.expos return cursor.toSelection -proc getNextChange*(self: TextDocumentEditor, cursor: Cursor): Selection {.expose("editor.text").} = +proc getNextChange*(self: TextDocumentEditor, cursor: Cursor): Selection = if self.diffChanges.isNone: return cursor.toSelection for mapping in self.diffChanges.get: if mapping.target.first > cursor.line: - return (mapping.target.first, 0).toSelection + return ((mapping.target.first, 0), (mapping.target.last, 0)) return cursor.toSelection @@ -2746,16 +2610,19 @@ proc checkoutFileAsync*(self: TextDocumentEditor) {.async.} = proc checkoutFile*(self: TextDocumentEditor) {.expose("editor.text").} = asyncSpawn self.checkoutFileAsync() +# todo proc addNextFindResultToSelection*(self: TextDocumentEditor, includeAfter: bool = true, wrap: bool = true) {.expose("editor.text").} = self.selections = self.selections & @[self.getNextFindResult(self.selection.last, includeAfter=includeAfter)] +# todo proc addPrevFindResultToSelection*(self: TextDocumentEditor, includeAfter: bool = true, wrap: bool = true) {.expose("editor.text").} = self.selections = self.selections & @[self.getPrevFindResult(self.selection.first, includeAfter=includeAfter)] +# todo proc setAllFindResultToSelection*(self: TextDocumentEditor) {.expose("editor.text").} = self.updateSearchResults() @@ -2765,23 +2632,7 @@ proc setAllFindResultToSelection*(self: TextDocumentEditor) {.expose("editor.tex if selections.len > 0: self.selections = selections -proc clearSelections*(self: TextDocumentEditor) {.expose("editor.text").} = - if self.selections.len > 1: - self.selection = self.selection - else: - self.selection = self.selection.last.toSelection - -proc moveCursorColumn*(self: TextDocumentEditor, distance: int, - cursor: SelectionCursor = SelectionCursor.Config, all: bool = true, wrap: bool = true, - includeAfter: bool = true) {.expose("editor.text").} = - self.moveCursor(cursor, doMoveCursorColumn, distance, all, wrap, includeAfter) - self.updateTargetColumn(cursor) - -proc moveCursorLine*(self: TextDocumentEditor, distance: int, - cursor: SelectionCursor = SelectionCursor.Config, all: bool = true, wrap: bool = true, - includeAfter: bool = true) {.expose("editor.text").} = - self.moveCursor(cursor, doMoveCursorLine, distance, all, wrap, includeAfter) - +# todo proc moveCursorVisualLine*(self: TextDocumentEditor, distance: int, cursor: SelectionCursor = SelectionCursor.Config, all: bool = true, wrap: bool = true, includeAfter: bool = true) {.expose("editor.text").} = @@ -2801,14 +2652,7 @@ proc moveCursorVisualLine*(self: TextDocumentEditor, distance: int, self.doMoveCursorVisualLine(cursor, offset, wrap, includeAfter, targetColumn.some) self.moveCursor(cursor, doMoveCursor, distance, all, wrap, includeAfter) -proc moveCursorPage*(self: TextDocumentEditor, distance: float, - cursor: SelectionCursor = SelectionCursor.Config, all: bool = true, wrap: bool = true, - includeAfter: bool = true) {.expose("editor.text").} = - - let visibleLines = self.screenLineCount() - let linesToMove = int(visibleLines.float * distance) - self.moveCursorLine(linesToMove, cursor, all, wrap, includeAfter) - +# todo proc moveCursorVisualPage*(self: TextDocumentEditor, distance: float, cursor: SelectionCursor = SelectionCursor.Config, all: bool = true, wrap: bool = true, includeAfter: bool = true) {.expose("editor.text").} = @@ -2817,75 +2661,28 @@ proc moveCursorVisualPage*(self: TextDocumentEditor, distance: float, let linesToMove = int(visibleLines.float * distance) self.moveCursorVisualLine(linesToMove, cursor, all, wrap, includeAfter) -proc moveCursorHome*(self: TextDocumentEditor, cursor: SelectionCursor = SelectionCursor.Config, - all: bool = true) {.expose("editor.text").} = - self.moveCursor(cursor, doMoveCursorHome, 0, all) - self.updateTargetColumn(cursor) - -proc moveCursorEnd*(self: TextDocumentEditor, cursor: SelectionCursor = SelectionCursor.Config, - all: bool = true, includeAfter: bool = true) {.expose("editor.text").} = - self.moveCursor(cursor, doMoveCursorEnd, 0, all, includeAfter=includeAfter) - self.updateTargetColumn(cursor) - -proc moveCursorTo*(self: TextDocumentEditor, str: string, - cursor: SelectionCursor = SelectionCursor.Config, all: bool = true) {.expose("editor.text").} = - proc doMoveCursorTo(self: TextDocumentEditor, cursor: Cursor, offset: int, - wrap: bool = true, includeAfter: bool = true): Cursor = - # todo: use RopeCursor - let line = self.document.getLine cursor.line - result = cursor - let index = line.suffix(cursor.column + 1).find(str) - if index >= 0: - result = (cursor.line, index + cursor.column + 1) - self.moveCursor(cursor, doMoveCursorTo, 0, all) - self.updateTargetColumn(cursor) - -proc moveCursorBefore*(self: TextDocumentEditor, str: string, - cursor: SelectionCursor = SelectionCursor.Config, all: bool = true) {.expose("editor.text").} = - proc doMoveCursorBefore(self: TextDocumentEditor, cursor: Cursor, offset: int, - wrap: bool = true, includeAfter: bool = true): Cursor = - # todo: use RopeCursor - let line = self.document.getLine cursor.line - result = cursor - let index = line.suffix(cursor.column).find(str) - if index > 0: - result = (cursor.line, index - 1 + cursor.column) - - self.moveCursor(cursor, doMoveCursorBefore, 0, all) - self.updateTargetColumn(cursor) - -proc moveCursorNextFindResult*(self: TextDocumentEditor, - cursor: SelectionCursor = SelectionCursor.Config, all: bool = true, wrap: bool = true) {. - expose("editor.text").} = - self.moveCursor(cursor, doMoveCursorNextFindResult, 0, all, wrap) - self.updateTargetColumn(cursor) - -proc moveCursorPrevFindResult*(self: TextDocumentEditor, - cursor: SelectionCursor = SelectionCursor.Config, all: bool = true, wrap: bool = true) {. - expose("editor.text").} = - self.moveCursor(cursor, doMoveCursorPrevFindResult, 0, all, wrap) - self.updateTargetColumn(cursor) - +# todo proc moveCursorLineCenter*(self: TextDocumentEditor, cursor: SelectionCursor = SelectionCursor.Config, all: bool = true) {.expose("editor.text").} = self.moveCursor(cursor, doMoveCursorLineCenter, 0, all) self.updateTargetColumn(cursor) +# todo proc moveCursorCenter*(self: TextDocumentEditor, cursor: SelectionCursor = SelectionCursor.Config, all: bool = true) {.expose("editor.text").} = self.moveCursor(cursor, doMoveCursorCenter, 0, all) proc scrollToCursor*(self: TextDocumentEditor, cursor: SelectionCursor = SelectionCursor.Config, - margin: Option[float] = float.none, scrollBehaviour: Option[ScrollBehaviour] = ScrollBehaviour.none, relativePosition: float = 0.5) {.expose("editor.text").} = + margin: Option[float] = float.none, scrollBehaviour: Option[ScrollBehaviour] = ScrollBehaviour.none, relativePosition: float = 0.5) = self.scrollToCursor(self.getCursor(cursor), margin, scrollBehaviour, relativePosition) -proc setNextScrollBehaviour*(self: TextDocumentEditor, scrollBehaviour: ScrollBehaviour) {.expose("editor.text").} = +proc setNextScrollBehaviour*(self: TextDocumentEditor, scrollBehaviour: ScrollBehaviour) = self.nextScrollBehaviour = scrollBehaviour.some proc setDefaultSnapBehaviour*(self: TextDocumentEditor, snapBehaviour: ScrollSnapBehaviour) {.expose("editor.text").} = self.defaultSnapBehaviour = snapBehaviour -proc setNextSnapBehaviour*(self: TextDocumentEditor, snapBehaviour: ScrollSnapBehaviour) {.expose("editor.text").} = +proc setNextSnapBehaviour*(self: TextDocumentEditor, snapBehaviour: ScrollSnapBehaviour) = self.nextSnapBehaviour = snapBehaviour.some if snapBehaviour == Always: self.interpolatedScrollOffset = self.scrollOffset @@ -2896,12 +2693,16 @@ proc setCursorScrollOffset*(self: TextDocumentEditor, offset: float, self.scrollOffset.y = offset - displayPoint.row.float * self.platform.totalLineHeight self.markDirty() -proc getContentBounds*(self: TextDocumentEditor): Vec2 {.expose("editor.text").} = +proc setCursorScrollOffset*(self: TextDocumentEditor, cursor: Cursor, offset: float) = + let displayPoint = self.displayMap.toDisplayPoint(cursor.toPoint) + self.scrollOffset.y = offset * self.platform.totalLineHeight - displayPoint.row.float * self.platform.totalLineHeight + self.markDirty() + +proc getContentBounds*(self: TextDocumentEditor): Vec2 = # todo return self.lastContentBounds.wh -proc centerCursor*(self: TextDocumentEditor, cursor: SelectionCursor = SelectionCursor.Config) {. - expose("editor.text").} = +proc centerCursor*(self: TextDocumentEditor, cursor: SelectionCursor = SelectionCursor.Config) {.expose("editor.text").} = self.centerCursor(self.getCursor(cursor)) proc reloadTreesitter*(self: TextDocumentEditor) {.expose("editor.text").} = @@ -2915,304 +2716,214 @@ proc reloadTreesitter*(self: TextDocumentEditor) {.expose("editor.text").} = if doc.languageId == self.document.languageId: doc.reloadTreesitterLanguage() -proc deleteLeft*(self: TextDocumentEditor) {.expose("editor.text").} = - var selections = self.selections - for i, selection in selections: - if selection.isEmpty: - selections[i] = (self.doMoveCursorColumn(selection.first, -1), selection.first) - - # echo &"delete left {self.selections} -> {selections}" - self.selections = self.document.edit(selections, self.selections, [""], - inclusiveEnd=self.useInclusiveSelections) - - self.autoShowCompletions() - -proc deleteRight*(self: TextDocumentEditor, includeAfter: bool = true) {.expose("editor.text").} = - var selections = self.selections - for i, selection in selections: - if selection.isEmpty: - selections[i] = (selection.first, self.doMoveCursorColumn(selection.first, 1)) - - self.selections = self.document.edit(selections, self.selections, [""], - inclusiveEnd=self.useInclusiveSelections).mapIt(self.clampSelection(it, includeAfter)) - - self.autoShowCompletions() - -proc getCommandCount*(self: TextDocumentEditor): int {.expose("editor.text").} = +proc getCommandCount*(self: TextDocumentEditor): int = return self.commandCount -proc setCommandCount*(self: TextDocumentEditor, count: int) {.expose("editor.text").} = +proc setCommandCount*(self: TextDocumentEditor, count: int) = self.commandCount = count -proc setCommandCountRestore*(self: TextDocumentEditor, count: int) {.expose("editor.text").} = +proc setCommandCountRestore*(self: TextDocumentEditor, count: int) = self.commandCountRestore = count -proc updateCommandCount*(self: TextDocumentEditor, digit: int) {.expose("editor.text").} = +proc updateCommandCount*(self: TextDocumentEditor, digit: int) = self.commandCount = self.commandCount * 10 + digit -proc runAction*(self: TextDocumentEditor, action: string, args: JsonNode): Option[JsonNode] {. - expose("editor.text").} = +proc runAction*(self: TextDocumentEditor, action: string, args: JsonNode): Option[JsonNode] {.expose("editor.text").} = # echo "runAction ", action, ", ", $args return self.handleActionInternal(action, args) -proc findWordBoundary*(self: TextDocumentEditor, cursor: Cursor): Selection {.expose("editor.text").} = +proc findWordBoundary*(self: TextDocumentEditor, cursor: Cursor): Selection = self.document.findWordBoundary(cursor) -proc getSelectionInPair*(self: TextDocumentEditor, cursor: Cursor, delimiter: char): Selection {. - expose("editor.text").} = - result = cursor.toSelection - # todo - -proc getSelectionInPairNested*(self: TextDocumentEditor, cursor: Cursor, open: char, - close: char): Selection {.expose("editor.text").} = - result = cursor.toSelection - # todo - -proc extendSelectionWithMove*(self: TextDocumentEditor, selection: Selection, move: string, - count: int = 0): Selection {.expose("editor.text").} = +proc extendSelectionWithMove*(self: TextDocumentEditor, selection: Selection, move: string, count: int = 0): Selection = result = self.getSelectionForMove(selection.first, move, count) or self.getSelectionForMove(selection.last, move, count) if selection.isBackwards: result = result.reverse -proc getEnclosing(text: RopeSlice, column: int, predicate: proc(c: char): bool {.gcsafe, raises: [].}): (int, int) = - var cf = text.cursor(column) - var cb = cf.clone() - while cf.offset < text.len - 1: - cf.seekNextRune() - if not predicate(cf.currentChar()): - cf.seekPrevRune() - break - while cb.offset > 0: - cb.seekPrevRune() - if not predicate(cb.currentChar()): - cb.seekNextRune() - break - return (cb.offset, cf.offset) - -proc vimMotionWord*(self: TextDocumentEditor, cursor: Cursor, count: int = 0): Selection {.expose("editor.text").} = - const AlphaNumeric = {'A'..'Z', 'a'..'z', '0'..'9', '_'} - - var line = self.document.getLine(cursor.line) - if line.len == 0: - return (cursor.line, 0).toSelection - - let c = line.charAt(cursor.column.clamp(0, line.len - 1)) - if c in Whitespace: - let (startColumn, endColumn) = line.getEnclosing(cursor.column, (c) => c in Whitespace) - return ((cursor.line, startColumn), (cursor.line, endColumn)) - - elif c in AlphaNumeric: - let (startColumn, endColumn) = line.getEnclosing(cursor.column, (c) => c in AlphaNumeric) - return ((cursor.line, startColumn), (cursor.line, endColumn)) - - else: - let (startColumn, endColumn) = line.getEnclosing(cursor.column, (c) => c notin Whitespace and c notin AlphaNumeric) - return ((cursor.line, startColumn), (cursor.line, endColumn)) - -proc vimMotionWordBig*(self: TextDocumentEditor, cursor: Cursor, count: int = 0): Selection {.expose("editor.text").} = - var line = self.document.getLine(cursor.line) - if line.len == 0: - return (cursor.line, 0).toSelection - - let c = line.charAt(cursor.column.clamp(0, line.len - 1)) - if c in Whitespace: - let (startColumn, endColumn) = line.getEnclosing(cursor.column, (c) => c in Whitespace) - return ((cursor.line, startColumn), (cursor.line, endColumn)) - - else: - let (startColumn, endColumn) = line.getEnclosing(cursor.column, (c) => c notin Whitespace) - return ((cursor.line, startColumn), (cursor.line, endColumn)) +proc applyMoveFallback(self: TextDocumentEditor, move: string, selections: openArray[Selection], count: int): seq[Selection] = + debugf"applyMoveFallback {move}" + let includeEol = true + let wrap = false + + let cursorSelector = self.config.get(self.getContextWithMode("editor.text.cursor.movement"), SelectionCursor.Both) + + var moveOriginal = move + var move = move + var args: JsonNode = nil + var argsString = "" + var hasArgs = false + var parsedArgs = false + let argsStart = move.find(" ") + if argsStart > 0: + hasArgs = true + argsString = move[(argsStart + 1)..^1] + move = move[0.. 0: - result.first = (cursor.line - 1, self.document.lineLength(cursor.line - 1)) - if cursor.column == line.len and cursor.line < self.document.numLines - 1: - result.last = (cursor.line + 1, 0) - - for _ in 1.. 0: - result.first = (result.first.line - 1, self.document.lineLength(result.first.line - 1)) - if result.last.column == line.len and result.last.line < self.document.numLines - 1: - result.last = (result.last.line + 1, 0) - - of "word-back": - return self.getSelectionForMove((cursor.line, max(0, cursor.column - 1)), "word", count).reverse - - of "word-line-back": - return self.getSelectionForMove((cursor.line, max(0, cursor.column - 1)), "word-line", count).reverse - - of "number": - var r = cursor.toPoint...cursor.toPoint - var c = self.document.rope.cursorT(cursor.toPoint) - while c.currentChar in {'0'..'9'}: - c.seekNextRune() - r.b = c.position - - if r.a.column > 0: - c = self.document.rope.cursorT(cursor.toPoint) - while c.position.column > 0: - c.seekPrevRune() - if c.currentChar == '-': - r.a = c.position - break - - if c.currentChar notin {'0'..'9'}: - c.seekNextRune() - break - r.a = c.position - - return r.toSelection - - of "line-back": - let first = if cursor.line > 0 and cursor.column == 0: - (cursor.line - 1, self.document.lineLength(cursor.line - 1)) - else: - (cursor.line, 0) - result = (first, (cursor.line, self.document.lineLength(cursor.line))) - - of "line": - result = ((cursor.line, 0), (cursor.line, self.document.lineLength(cursor.line))) - - of "visual-line": - let wrapPoint = self.displayMap.toWrapPoint(cursor.toPoint) - let displayLineStart = wrapPoint(wrapPoint.row) - let displayLineEnd = wrapPoint(wrapPoint.row + 1) - result[0] = self.displayMap.toPoint(displayLineStart, Right).toCursor - result[1] = self.displayMap.toPoint(displayLineEnd, Right).toCursor - if result[1].column == 0: - result[1].line -= 1 - result[1].column = self.document.lineLength(result[1].line) - - of "line-next": - result = ((cursor.line, 0), (cursor.line, self.document.lineLength(cursor.line))) - if result.last.line + 1 < self.document.numLines: - result.last = (result.last.line + 1, 0) - for _ in 1.. 0: - result.first = (result.first.line - 1, self.document.lineLength(result.first.line - 1)) - for _ in 1.. 0: - result.first = (result.first.line - 1, self.document.lineLength(result.first.line - 1)) + var foundTabStop = false + while self.currentSnippetData.get.currentTabStop < self.currentSnippetData.get.highestTabStop: + self.currentSnippetData.get.currentTabStop.inc + self.currentSnippetData.get.tabStops.withValue(self.currentSnippetData.get.currentTabStop, val): + result = val[] + foundTabStop = true + break - of "line-no-indent": - let indent = self.document.rope.indentBytes(cursor.line) - result = ((cursor.line, indent), (cursor.line, self.document.lineLength(cursor.line))) + if not foundTabStop: + self.currentSnippetData.get.currentTabStop = 0 + result = self.currentSnippetData.get.tabStops[0] - of "file": - result.first = (0, 0) - let line = self.document.numLines - 1 - result.last = (line, self.document.lineLength(line)) + of "prev-tab-stop": + result = @selections + if self.currentSnippetData.isNone: + return - of "prev-find-result": - result = self.getPrevFindResult(cursor, count) + if self.currentSnippetData.get.currentTabStop == 0: + self.currentSnippetData.get.currentTabStop = self.currentSnippetData.get.highestTabStop + self.currentSnippetData.get.tabStops.withValue(self.currentSnippetData.get.currentTabStop, val): + result = val[] + return - of "next-find-result": - result = self.getNextFindResult(cursor, count) + while self.currentSnippetData.get.currentTabStop > 1: + self.currentSnippetData.get.currentTabStop.dec + self.currentSnippetData.get.tabStops.withValue(self.currentSnippetData.get.currentTabStop, val): + result = val[] + break - of "\"": - result = self.getSelectionInPair(cursor, '"') + else: + # return self.moveDatabase.applyMove(self.displayMap, moveOriginal, selections, count, self.targetColumn, includeEol, self.moveFallbacks) + log lvlError, &"Unknown move '{move}'" + return @selections + +proc getSelectionsForMove*(self: TextDocumentEditor, selections: openArray[Selection], move: string, + count: int = 0, includeEol: bool = true, wrap: bool = true, options: JsonNode = nil): seq[Selection] = + var env = Env() + env["screen-lines"] = newNumber(self.screenLineCount()) + env["target-column"] = newNumber(self.targetColumn) + env["count"] = newNumber(count) + env["include-eol"] = newBool(includeEol) + env["wrap"] = newBool(wrap) + + proc readOptions(env: var Env, options: JsonNode) = + if options.kind == JObject: + for (key, val) in options.fields.pairs: + try: + env[key] = val.jsonTo(LispVal) + except CatchableError as e: + log lvlError, "Failed to convert option " & key & " = " & $val & " to lisp value: " & e.msg + else: + log lvlError, "Invalid move options, expected object: " & $options - of "'": - result = self.getSelectionInPair(cursor, '\'') + if options != nil: + if options.kind == JArray: + for o in options.elems: + env.readOptions(o) + else: + env.readOptions(options) - of "(", ")": - result = self.getSelectionInPairNested(cursor, '(', ')') + return self.moveDatabase.applyMove(self.displayMap, move, selections, self.moveFallbacks, env) - of "{", "}": - result = self.getSelectionInPairNested(cursor, '{', '}') +proc getSelectionForMove*(self: TextDocumentEditor, cursor: Cursor, move: string, + count: int = 0, includeEol: bool = true): Selection = + let selections = self.getSelectionsForMove([cursor.toSelection], move, count, includeEol) + if selections.len > 0: + return selections[0] + else: + return cursor.toSelection + # defer: + # debugf"getSelectionForMove '{move}', {cursor} -> {result}" + # case move - of "[", "]": - result = self.getSelectionInPairNested(cursor, '[', ']') + # of "line-back": + # let first = if cursor.line > 0 and cursor.column == 0: + # (cursor.line - 1, self.document.lineLength(cursor.line - 1)) + # else: + # (cursor.line, 0) + # result = (first, (cursor.line, self.document.lineLength(cursor.line))) - else: - if move.startsWith("move-to "): - # todo: use RopeCursor - let str = move[8..^1] - let line = self.document.getLine cursor.line - result = cursor.toSelection - let index = line.suffix(cursor.column).find(str) - if index >= 0: - result.last = (cursor.line, index + 1 + cursor.column) - for _ in 1..= 0: - result.last = (result.last.line, index + 1 + result.last.column) - - elif move.startsWith("move-before "): - # todo: use RopeCursor - let str = move[12..^1] - let line = self.document.getLine cursor.line - result = cursor.toSelection - let index = line.suffix(cursor.column + 1).find(str) - if index >= 0: - result.last = (cursor.line, index + cursor.column + 1) - for _ in 1..= 0: - result.last = (result.last.line, index + result.last.column + 1) - else: - result = cursor.toSelection + # else: + # result = cursor.toSelection - let cursorJson = self.plugins.invokeAnyCallback("editor.text.custom-move", %*{ - "editor": self.id, - "move": move, - "cursor": cursor.toJson, - "count": count, - }) + # let cursorJson = self.plugins.invokeAnyCallback("editor.text.custom-move", %*{ + # "editor": self.id.EditorId, + # "move": move, + # "cursor": cursor.toJson, + # "count": count, + # }) - if cursorJson.isNil: - log(lvlError, fmt"editor.text.custom-move returned nil") - return result + # if cursorJson.isNil: + # log(lvlError, fmt"editor.text.custom-move returned nil") + # return result - result = cursorJson.jsonTo(Selection).catch: - log(lvlError, fmt"Failed to parse selection from custom move '{move}': {cursorJson}") - return cursor.toSelection + # result = cursorJson.jsonTo(Selection).catch: + # log(lvlError, fmt"Failed to parse selection from custom move '{move}': {cursorJson}") + # return cursor.toSelection - return result + # return result proc mapAllOrLast[T](self: openArray[T], all: bool, p: proc(v: T): T {.gcsafe, raises: [].}): seq[T] = if all: @@ -3235,52 +2946,18 @@ proc cursor(self: TextDocumentEditor, selection: Selection, which: SelectionCurs of Last, LastToFirst: return selection.last -proc applyMove*(self: TextDocumentEditor, args {.varargs.}: JsonNode) {.expose("editor.text").} = - self.config.set("text.move-count", self.getCommandCount) - self.setMode self.config.get("text.move-next-mode", "") - self.setCommandCount self.config.get("text.move-command-count", 0) - let command = self.config.get("text.move-action", "") - discard self.runAction(command, args) - self.config.set("text.move-action", "") - -proc deleteMove*(self: TextDocumentEditor, move: string, inside: bool = false, - which: SelectionCursor = SelectionCursor.Config, all: bool = true) {.expose("editor.text").} = +proc deleteMove*(self: TextDocumentEditor, move: string, updateTargetColumn: bool = true, options {.varargs.}: JsonNode = newJObject()) {.expose("editor.text").} = ## Deletes text based on the current selections. ## ## `move` specifies which move should be applied to each selection. let count = self.config.get("text.move-count", 0) - # echo fmt"delete-move {move}, {which}, {count}, {inside}" - - let selections = if inside: - self.selections.mapAllOrLast(all, (s) {.gcsafe, raises: [].} => self.getSelectionForMove(s.last, move, count)) - else: - self.selections.mapAllOrLast(all, (s) {.gcsafe, raises: [].} => ( - self.getCursor(s, which), - self.getCursor(self.getSelectionForMove(s.last, move, count), which) - )) - - self.selections = self.document.edit(selections, self.selections, [""], - inclusiveEnd=self.useInclusiveSelections) - self.scrollToCursor(Last) - self.setNextSnapBehaviour(ScrollSnapBehaviour.Always) - self.updateTargetColumn(Last) - -proc selectMove*(self: TextDocumentEditor, move: string, inside: bool = false, - which: SelectionCursor = SelectionCursor.Config, all: bool = true) {.expose("editor.text").} = - let count = self.config.get("text.move-count", 0) - - self.selections = if inside: - self.selections.mapAllOrLast(all, (s) {.gcsafe, raises: [].} => self.getSelectionForMove(s.last, move, count)) - else: - self.selections.mapAllOrLast(all, (s) {.gcsafe, raises: [].} => ( - self.getCursor(s, which), - self.getCursor(self.getSelectionForMove(s.last, move, count), which) - )) - + let selections = self.getSelectionsForMove(self.selections, move, 1, true, true, options) + self.selections = self.document.edit(selections, self.selections, [""]) self.scrollToCursor(Last) self.setNextSnapBehaviour(ScrollSnapBehaviour.Always) - self.updateTargetColumn(Last) + if updateTargetColumn: + self.updateTargetColumn(Last) proc extendSelectMove*(self: TextDocumentEditor, move: string, inside: bool = false, which: SelectionCursor = SelectionCursor.Config, all: bool = true) {.expose("editor.text").} = @@ -3297,69 +2974,17 @@ proc extendSelectMove*(self: TextDocumentEditor, move: string, inside: bool = fa self.scrollToCursor(Last) self.updateTargetColumn(Last) -proc copyMove*(self: TextDocumentEditor, move: string, inside: bool = false, - which: SelectionCursor = SelectionCursor.Config, all: bool = true) {.expose("editor.text").} = - self.selectMove(move, inside, which, all) - self.copy() - self.selections = self.selections.mapIt(it.first.toSelection) - -proc changeMove*(self: TextDocumentEditor, move: string, inside: bool = false, - which: SelectionCursor = SelectionCursor.Config, all: bool = true) {.expose("editor.text").} = - let count = self.config.get("text.move-count", 0) - - let selections = if inside: - self.selections.mapAllOrLast(all, (s) {.gcsafe, raises: [].} => self.getSelectionForMove(s.last, move, count)) - else: - self.selections.mapAllOrLast(all, (s) {.gcsafe, raises: [].} => ( - self.getCursor(s, which), - self.getCursor(self.getSelectionForMove(s.last, move, count), which) - )) - - self.selections = self.document.edit(selections, self.selections, [""], - inclusiveEnd=self.useInclusiveSelections) +proc move*(self: TextDocumentEditor, move: string, updateTargetColumn: bool = true, options {.varargs.}: JsonNode = newJObject()) {.expose("editor.text").} = + self.selections = self.getSelectionsForMove(self.selections, move, 1, true, true, options) self.scrollToCursor(Last) - self.setNextSnapBehaviour(ScrollSnapBehaviour.Always) - self.updateTargetColumn(Last) - -proc moveLast*(self: TextDocumentEditor, move: string, which: SelectionCursor = SelectionCursor.Config, - all: bool = true, count: int = 0) {.expose("editor.text").} = - case which - of Config: - let cursorSelector = self.config.get( - self.getContextWithMode("editor.text.cursor.movement"), - SelectionCursor.Both - ) - self.selections = self.selections.mapAllOrLast(all, (s) {.gcsafe, raises: [].} => - self.getSelectionForMove(self.cursor(s, which), move, count).last.toSelection(s, cursorSelector) - ) - else: - self.selections = self.selections.mapAllOrLast(all, (s) {.gcsafe, raises: [].} => - self.getSelectionForMove(self.cursor(s, which), move, count).last.toSelection(s, which)) - self.scrollToCursor(which) - self.updateTargetColumn(which) - -proc moveFirst*(self: TextDocumentEditor, move: string, which: SelectionCursor = SelectionCursor.Config, - all: bool = true, count: int = 0) {.expose("editor.text").} = - case which - of Config: - let cursorSelector = self.config.get( - self.getContextWithMode("editor.text.cursor.movement"), - SelectionCursor.Both - ) - self.selections = self.selections.mapAllOrLast(all, (s) {.gcsafe, raises: [].} => - self.getSelectionForMove(self.cursor(s, which), move, count).first.toSelection(s, cursorSelector) - ) - else: - self.selections = self.selections.mapAllOrLast(all, (s) {.gcsafe, raises: [].} => - self.getSelectionForMove(self.cursor(s, which), move, count).first.toSelection(s, which)) - self.scrollToCursor(which) - self.updateTargetColumn(which) + if updateTargetColumn: + self.updateTargetColumn(Last) -proc getSearchQuery*(self: TextDocumentEditor): string {.expose("editor.text").} = +proc getSearchQuery*(self: TextDocumentEditor): string = return self.searchQuery -proc setSearchQuery*(self: TextDocumentEditor, query: string, escapeRegex: bool = false, - prefix: string = "", suffix: string = ""): bool {.expose("editor.text").} = +proc setSearchQuery*(self: TextDocumentEditor, query: string, escapeRegex: bool = false, prefix: string = "", suffix: string = ""): bool {.expose("editor.text").} = + debugf"setSearchQuery '{query}'" let query = if escapeRegex: query.escapeRegex @@ -3394,7 +3019,7 @@ proc openSearchBar*(self: TextDocumentEditor, query: string = "", scrollToPrevie let document = commandLineEditor.document commandLineEditor.disableCompletions = true - commandLineEditor.moveLast("file") + commandLineEditor.move("(file) (end)") commandLineEditor.updateTargetColumn() var onEditHandle = Id.new @@ -3418,13 +3043,15 @@ proc openSearchBar*(self: TextDocumentEditor, query: string = "", scrollToPrevie if scrollToPreview: self.scrollToCursor(s.last) -proc setSearchQueryFromMove*(self: TextDocumentEditor, move: string, - count: int = 0, prefix: string = "", suffix: string = ""): Selection {.expose("editor.text").} = +proc setSearchQueryFromMove*(self: TextDocumentEditor, move: string, count: int = 0, prefix: string = "", suffix: string = ""): Selection = let selection = self.getSelectionForMove(self.selection.last, move, count) let searchText = self.document.contentString(selection) discard self.setSearchQuery(searchText, escapeRegex=true, prefix, suffix) return selection +proc toggleDebugMoves*(self: TextDocumentEditor) {.expose("editor.text").} = + self.moveDatabase.toggleDebugMoves() + proc toggleLineComment*(self: TextDocumentEditor) {.expose("editor.text").} = self.selections = self.document.toggleLineComment(self.selections) @@ -3435,7 +3062,7 @@ proc openFileAt(self: TextDocumentEditor, filename: string, location: Option[Sel self.updateTargetColumn(Last) self.centerCursor() self.setNextSnapBehaviour(ScrollSnapBehaviour.MinDistanceOffscreen) - self.layout.showEditor(self.id) + self.layout.showEditor(self.id.EditorId) else: let editor = self.layout.openFile(filename) @@ -3848,8 +3475,7 @@ proc renameAsync(self: TextDocumentEditor) {.async.} = log lvlError, &"Failed to rename to '{name}': {it.error}" commandLineEditor.disableCompletions = true - commandLineEditor.moveLast("file") - commandLineEditor.updateTargetColumn() + commandLineEditor.move("(file) (end)") proc rename*(self: TextDocumentEditor) {.expose("editor.text").} = asyncSpawn self.renameAsync() @@ -3888,44 +3514,12 @@ proc selectNextCompletionVisual*(self: TextDocumentEditor) {.expose("editor.text else: self.selectNextCompletion() -proc hasTabStops*(self: TextDocumentEditor): bool {.expose("editor.text").} = +proc hasTabStops*(self: TextDocumentEditor): bool = return self.currentSnippetData.isSome proc clearTabStops*(self: TextDocumentEditor) {.expose("editor.text").} = self.currentSnippetData = SnippetData.none -proc selectNextTabStop*(self: TextDocumentEditor) {.expose("editor.text").} = - if self.currentSnippetData.isNone: - return - - var foundTabStop = false - while self.currentSnippetData.get.currentTabStop < self.currentSnippetData.get.highestTabStop: - self.currentSnippetData.get.currentTabStop.inc - self.currentSnippetData.get.tabStops.withValue(self.currentSnippetData.get.currentTabStop, val): - self.selections = val[] - foundTabStop = true - break - - if not foundTabStop: - self.currentSnippetData.get.currentTabStop = 0 - self.selections = self.currentSnippetData.get.tabStops[0] - -proc selectPrevTabStop*(self: TextDocumentEditor) {.expose("editor.text").} = - if self.currentSnippetData.isNone: - return - - if self.currentSnippetData.get.currentTabStop == 0: - self.currentSnippetData.get.currentTabStop = self.currentSnippetData.get.highestTabStop - self.currentSnippetData.get.tabStops.withValue(self.currentSnippetData.get.currentTabStop, val): - self.selections = val[] - return - - while self.currentSnippetData.get.currentTabStop > 1: - self.currentSnippetData.get.currentTabStop.dec - self.currentSnippetData.get.tabStops.withValue(self.currentSnippetData.get.currentTabStop, val): - self.selections = val[] - break - proc applyCompletion*(self: TextDocumentEditor, completion: Completion) = let completion = completion log(lvlInfo, fmt"Applying completion {completion.item.label}") @@ -4036,7 +3630,7 @@ proc applyCompletion*(self: TextDocumentEditor, completion: Completion) = self.selections = newSelections[numAdditionalEdits..^1].mapIt(it.last.toSelection) self.currentSnippetData = snippetData - self.selectNextTabStop() + self.move("(next-tab-stop)") if completion.item.showCompletionsAgain.get(false): self.autoShowCompletions() @@ -4048,7 +3642,7 @@ proc applyCompletion*(self: TextDocumentEditor, completion: JsonNode) {.expose(" except: log lvlError, &"[applyCompletion] Failed to parse completion {completion}" -proc isShowingCompletions*(self: TextDocumentEditor): bool {.expose("editor.text").} = +proc isShowingCompletions*(self: TextDocumentEditor): bool = return self.showCompletions and self.completions.len > 0 proc applySelectedCompletion*(self: TextDocumentEditor) {.expose("editor.text").} = @@ -4093,7 +3687,7 @@ proc showHoverForAsync(self: TextDocumentEditor, cursor: Cursor): Future[void] { self.markDirty() -proc showHoverFor*(self: TextDocumentEditor, cursor: Cursor) {.expose("editor.text").} = +proc showHoverFor*(self: TextDocumentEditor, cursor: Cursor) = ## Shows lsp hover information for the given cursor. ## Does nothing if no language server is available or the language server doesn't return any info. asyncSpawn self.showHoverForAsync(cursor) @@ -4108,11 +3702,11 @@ proc hideHover*(self: TextDocumentEditor) {.expose("editor.text").} = self.showHover = false self.markDirty() -proc cancelDelayedHideHover*(self: TextDocumentEditor) {.expose("editor.text").} = +proc cancelDelayedHideHover*(self: TextDocumentEditor) = if self.hideHoverTask.isNotNil: self.hideHoverTask.pause() -proc hideHoverDelayed*(self: TextDocumentEditor) {.expose("editor.text").} = +proc hideHoverDelayed*(self: TextDocumentEditor) = ## Hides the hover information after a delay. if self.showHoverTask.isNotNil: self.showHoverTask.pause() @@ -4422,7 +4016,7 @@ proc setFileReadOnlyAsync*(self: TextDocumentEditor, readOnly: bool) {.async.} = proc setFileReadOnly*(self: TextDocumentEditor, readOnly: bool) {.expose("editor.text").} = asyncSpawn self.setFileReadOnlyAsync(readOnly) -proc isRunningSavedCommands*(self: TextDocumentEditor): bool {.expose("editor.text").} = +proc isRunningSavedCommands*(self: TextDocumentEditor): bool = self.bIsRunningSavedCommands proc runSavedCommands*(self: TextDocumentEditor) {.expose("editor.text").} = @@ -4445,8 +4039,7 @@ proc runSavedCommands*(self: TextDocumentEditor) {.expose("editor.text").} = self.savedCommandHistory = commandHistory -proc clearCurrentCommandHistory*(self: TextDocumentEditor, retainLast: bool = false) {. - expose("editor.text").} = +proc clearCurrentCommandHistory*(self: TextDocumentEditor, retainLast: bool = false) = if retainLast and self.currentCommandHistory.commands.len > 0: let last = self.currentCommandHistory.commands[self.currentCommandHistory.commands.high] self.currentCommandHistory.commands.setLen 0 @@ -4454,7 +4047,7 @@ proc clearCurrentCommandHistory*(self: TextDocumentEditor, retainLast: bool = fa else: self.currentCommandHistory.commands.setLen 0 -proc saveCurrentCommandHistory*(self: TextDocumentEditor) {.expose("editor.text").} = +proc saveCurrentCommandHistory*(self: TextDocumentEditor) = self.savedCommandHistory = self.currentCommandHistory self.currentCommandHistory.commands.setLen 0 @@ -4517,22 +4110,22 @@ proc assignKeys*(self: TextDocumentEditor, cursors: openArray[Cursor]): seq[stri if result.len == cursors.len: return -proc getSelection*(self: TextDocumentEditor): Selection {.expose("editor.text").} = +proc getSelection*(self: TextDocumentEditor): Selection = self.selection -proc getSelections*(self: TextDocumentEditor): Selections {.expose("editor.text").} = +proc getSelections*(self: TextDocumentEditor): Selections = self.selections -proc setSelection*(self: TextDocumentEditor, selection: Selection) {.expose("editor.text").} = - self.selection = selection +proc setSelection*(self: TextDocumentEditor, selection: Selection, addToHistory: Option[bool] = bool.none) = + self.`selections=`(@[selection], addToHistory) -proc setSelections*(self: TextDocumentEditor, selections: Selections) {.expose("editor.text").} = +proc setSelections*(self: TextDocumentEditor, selections: Selections, addToHistory: Option[bool] = bool.none) = if selections.len == 0: log lvlError, &"Failed to set selections for '{self.getFileName()}': no selections provided" return - self.selections = selections + self.`selections=`(selections, addToHistory) -proc setTargetSelection*(self: TextDocumentEditor, selection: Selection) {.expose("editor.text").} = +proc setTargetSelection*(self: TextDocumentEditor, selection: Selection) = self.targetSelection = selection proc enterChooseCursorMode*(self: TextDocumentEditor, action: string) {.expose("editor.text").} = @@ -4611,41 +4204,41 @@ proc enterChooseCursorMode*(self: TextDocumentEditor, action: string) {.expose(" self.markDirty() -proc recordCurrentCommand*(self: TextDocumentEditor, registers: seq[string] = @[]) {.expose("editor.text").} = +proc recordCurrentCommand*(self: TextDocumentEditor, registers: seq[string] = @[]) = self.recordCurrentCommandRegisters = if registers.len > 0: registers else: self.registers.recordingCommands -proc runControlClickCommand*(self: TextDocumentEditor) {.expose("editor.text").} = +proc runControlClickCommand*(self: TextDocumentEditor) = let commandName = self.settings.controlClickCommand.get() let args = self.settings.controlClickCommandArgs.get() if commandName.len == 0: return discard self.runAction(commandName, args) -proc runSingleClickCommand*(self: TextDocumentEditor) {.expose("editor.text").} = +proc runSingleClickCommand*(self: TextDocumentEditor) = let commandName = self.settings.singleClickCommand.get() let args = self.settings.singleClickCommandArgs.get() if commandName.len == 0: return discard self.runAction(commandName, args) -proc runDoubleClickCommand*(self: TextDocumentEditor) {.expose("editor.text").} = +proc runDoubleClickCommand*(self: TextDocumentEditor) = let commandName = self.settings.doubleClickCommand.get() let args = self.settings.doubleClickCommandArgs.get() if commandName.len == 0: return discard self.runAction(commandName, args) -proc runTripleClickCommand*(self: TextDocumentEditor) {.expose("editor.text").} = +proc runTripleClickCommand*(self: TextDocumentEditor) = let commandName = self.settings.tripleClickCommand.get() let args = self.settings.tripleClickCommandArgs.get() if commandName.len == 0: return discard self.runAction(commandName, args) -proc runDragCommand*(self: TextDocumentEditor) {.expose("editor.text").} = +proc runDragCommand*(self: TextDocumentEditor) = if self.lastPressedMouseButton == MouseButton.Left: self.runSingleClickCommand() elif self.lastPressedMouseButton == MouseButton.DoubleClick: @@ -4653,67 +4246,14 @@ proc runDragCommand*(self: TextDocumentEditor) {.expose("editor.text").} = elif self.lastPressedMouseButton == MouseButton.TripleClick: self.runTripleClickCommand() -proc getCurrentEventHandlers*(self: TextDocumentEditor): seq[string] {.expose("editor.text").} = +proc getCurrentEventHandlers*(self: TextDocumentEditor): seq[string] = return self.settings.modes.get() proc setCustomHeader*(self: TextDocumentEditor, text: string) {.expose("editor.text").} = self.customHeader = text self.markDirty() -type IdentifierCase = enum Camel, Pascal, Kebab, Snake, ScreamingSnake - -proc splitCase(s: string): tuple[cas: IdentifierCase, parts: seq[string]] = - if s == "": - return (IdentifierCase.Camel, @[]) - - if s.find('_') != -1: - result.cas = IdentifierCase.Snake - result.parts = s.split('_').mapIt(custom_unicode.toLower(it)) - for r in s.runes: - if r != '_'.Rune and not r.isLower: - result.cas = IdentifierCase.ScreamingSnake - break - - elif s.find('-') != -1: - result.cas = IdentifierCase.Kebab - result.parts = s.split('-').mapIt(custom_unicode.toLower(it)) - else: - if s[0].isUpperAscii: - result.cas = IdentifierCase.Pascal - else: - result.cas = IdentifierCase.Camel - - result.parts.add "" - for r in s.runes: - if not r.isLower and result.parts.last.len > 0: - result.parts.add "" - result.parts.last.add(custom_unicode.toLower(r)) - -proc joinCase(parts: seq[string], cas: IdentifierCase): string = - assert parts.len > 0 - case cas - of IdentifierCase.Camel: - parts[0] & parts[1..^1].mapIt(it.capitalize).join("") - of IdentifierCase.Pascal: - parts.mapIt(it.capitalize).join("") - of IdentifierCase.Kebab: - parts.join("-") - of IdentifierCase.Snake: - parts.join("_") - of IdentifierCase.ScreamingSnake: - parts.mapIt(custom_unicode.toUpper(it)).join("_") - -proc cycleCase(s: string): string = - if s.len == 0: - return s - let (cas, parts) = s.splitCase() - let nextCase = if cas == IdentifierCase.high: - IdentifierCase.low - else: - cas.succ - return parts.joinCase(nextCase) - -proc cycleCase*(self: TextDocumentEditor, selection: Selection, inclusiveEnd: bool = false): string {.expose("editor.text").} = +proc cycleCase*(self: TextDocumentEditor, selection: Selection, inclusiveEnd: bool = false): string = return self.document.contentString(selection, inclusiveEnd).cycleCase() proc cycleSelectedCase*(self: TextDocumentEditor) {.expose("editor.text").} = @@ -4731,7 +4271,17 @@ proc handleActionInternal(self: TextDocumentEditor, action: string, args: JsonNo # debugf"[textedit] handleAction {action}, '{args}'" var args = args.copy - args.elems.insert api.TextDocumentEditor(id: self.id).toJson, 0 + args.elems.insert api.TextDocumentEditor(id: self.id.EditorId).toJson, 0 + + if self.commands.activeCommands.contains(action): + try: + let res = self.commands.activeCommands[action].execute(args.elems.mapIt($it).join(" ")) + if res == "": + return newJNull().some + return res.parseJson().some + except CatchableError as e: + log lvlError, &"Failed to execute command '{action} {args}': {e.msg}" + return newJNull().some block: let res = self.plugins.invokeAnyCallback(action, args) @@ -4885,19 +4435,19 @@ proc updateMatchingWordHighlightAsync(self: TextDocumentEditor) {.async.} = return let (selection, inclusive, addWordBoundary) = if oldSelection.isEmpty: - var s = self.vimMotionWord(oldSelection.last).normalized + var s = self.document.rope.vimMotionWord(oldSelection.last, false).normalized const AlphaNumeric = {'A'..'Z', 'a'..'z', '0'..'9', '_'} if self.document.rope.charAt(s.first.toPoint) notin AlphaNumeric: let prev = (oldSelection.last.line, oldSelection.last.column - 1) if s.first.column > 0 and self.document.rope.charAt(prev.toPoint) in AlphaNumeric: - s = self.vimMotionWord(prev).normalized + s = self.document.rope.vimMotionWord(prev, false).normalized else: self.clearCustomHighlights(wordHighlightId) return if self.document.rope.charAt(s.first.toPoint) notin AlphaNumeric: self.clearCustomHighlights(wordHighlightId) return - (s, true, true) + (s, false, true) else: (oldSelection.normalized, self.useInclusiveSelections, false) @@ -5092,7 +4642,6 @@ proc handleDisplayMapUpdated(self: TextDocumentEditor, displayMap: DisplayMap) = if displayMap == self.displayMap: if displayMap.endDisplayPoint.row != self.lastEndDisplayPoint.row: self.lastEndDisplayPoint = displayMap.endDisplayPoint - self.updateTargetColumn() # let oldScrollOffset = self.scrollOffset.y # debugf"handleDisplayMapUpdated '{self.getFileName()}': target {self.targetPoint}, {displayMap.endDisplayPoint.row} -> {self.lastEndDisplayPoint.row}, {self.lastContentBounds}" @@ -5135,6 +4684,7 @@ proc newTextEditor*(document: TextDocument, services: Services): TextDocumentEdi self.plugins = self.services.getService(PluginService).get self.registers = self.services.getService(Registers).get self.workspace = self.services.getService(Workspace).get + self.moveDatabase = self.services.getService(MoveDatabase).get self.vfs = self.services.getService(VFSService).get.vfs self.commands = self.services.getService(CommandService).get self.displayMap = DisplayMap.new() @@ -5154,6 +4704,8 @@ proc newTextEditor*(document: TextDocument, services: Services): TextDocumentEdi self.debugSettings = DebugSettings.new(self.config) self.settings = TextEditorSettings.new(self.config) + self.moveFallbacks = proc(move: string, selections: openArray[Selection], count: int): seq[Selection] = self.applyMoveFallback(move, selections, count) + self.setDocument(document) self.startBlinkCursorTask() diff --git a/src/vcs/vcs_api.nim b/src/vcs/vcs_api.nim index fec00f6d2..da2c2e8b4 100644 --- a/src/vcs/vcs_api.nim +++ b/src/vcs/vcs_api.nim @@ -8,7 +8,7 @@ import finder/[finder, previewer, file_previewer] import platform/[platform] import service, dispatch_tables, platform_service import selector_popup, vcs, layout, vfs, config_provider -from scripting_api import SelectionCursor, ScrollSnapBehaviour +from scripting_api import SelectionCursor, ScrollSnapBehaviour, toSelection logCategory "vcs_api" @@ -230,7 +230,7 @@ proc chooseGitActiveFiles*(self: VCSService, all: bool = false) {.expose("vcs"). popup.addCustomCommand "prev-change", proc(popup: SelectorPopup, args: JsonNode): bool = if popup.textEditor.isNil: return false - popup.previewEditor.selection = popup.previewEditor.getPrevChange(popup.previewEditor.selection.last) + popup.previewEditor.selection = popup.previewEditor.getPrevChange(popup.previewEditor.selection.first).last.toSelection popup.previewEditor.scrollToCursor(SelectionCursor.Last) popup.previewEditor.centerCursor() popup.previewEditor.setNextSnapBehaviour(ScrollSnapBehaviour.MinDistanceOffscreen) @@ -239,7 +239,7 @@ proc chooseGitActiveFiles*(self: VCSService, all: bool = false) {.expose("vcs"). popup.addCustomCommand "next-change", proc(popup: SelectorPopup, args: JsonNode): bool = if popup.textEditor.isNil: return false - popup.previewEditor.selection = popup.previewEditor.getNextChange(popup.previewEditor.selection.last) + popup.previewEditor.selection = popup.previewEditor.getNextChange(popup.previewEditor.selection.first).last.toSelection popup.previewEditor.scrollToCursor(SelectionCursor.Last) popup.previewEditor.centerCursor() popup.previewEditor.setNextSnapBehaviour(ScrollSnapBehaviour.MinDistanceOffscreen) diff --git a/src/vterm.nim b/src/vterm.nim index 28ae13939..0cbd11614 100644 --- a/src/vterm.nim +++ b/src/vterm.nim @@ -165,7 +165,7 @@ type VTermParserCallbacks* {.bycopy, importc.} = object text*: proc (bytes: cstring; len: csize_t; user: pointer): cint {.cdecl.} - control*: proc (control: char; user: pointer): cint {.cdecl.} + control*: proc (control: uint8; user: pointer): cint {.cdecl.} escape*: proc (bytes: cstring; len: csize_t; user: pointer): cint {.cdecl.} csi*: proc (leader: cstring; args: ptr clong; argcount: cint; intermed: cstring; command: char; user: pointer): cint {.cdecl.} osc*: proc (command: cint; frag: VTermStringFragment; user: pointer): cint {.cdecl.} @@ -190,14 +190,14 @@ type sb_clear*: proc (user: pointer): cint {.cdecl.} VTermStateFallbacks* {.bycopy, importc.} = object - control*: proc (control: char; user: pointer): cint {.cdecl.} + control*: proc (control: uint8; user: pointer): cint {.cdecl.} csi*: proc (leader: cstring; args: ptr UncheckedArray[clong]; argcount: cint; intermed: cstring; command: char; user: pointer): cint {.cdecl.} osc*: proc (command: cint; frag: VTermStringFragment; user: pointer): cint {.cdecl.} dcs*: proc (command: cstring; commandlen: csize_t; frag: VTermStringFragment; user: pointer): cint {.cdecl.} apc*: proc (frag: VTermStringFragment; user: pointer): cint {.cdecl.} pm*: proc (frag: VTermStringFragment; user: pointer): cint {.cdecl.} sos*: proc (frag: VTermStringFragment; user: pointer): cint {.cdecl.} - reset*: proc (hard: int; user: pointer): cint {.cdecl.} + reset*: proc (hard: cint; user: pointer): cint {.cdecl.} VTermScreenCallbacks* {.bycopy, importc.} = object damage*: proc (rect: VTermRect; user: pointer): cint {.cdecl.} @@ -273,7 +273,7 @@ type VTERM_KEY_KP_EQUAL, VTERM_KEY_MAX - VTermAttrMask* = enum + VTermAttrMask* {.importc.} = enum VTERM_ATTR_BOLD_MASK = 1 shl 0, VTERM_ATTR_UNDERLINE_MASK = 1 shl 1, VTERM_ATTR_ITALIC_MASK = 1 shl 2, VTERM_ATTR_BLINK_MASK = 1 shl 3, VTERM_ATTR_REVERSE_MASK = 1 shl 4, VTERM_ATTR_STRIKE_MASK = 1 shl 5, @@ -283,7 +283,7 @@ type VTERM_ATTR_DIM_MASK = 1 shl 12, VTERM_ALL_ATTRS_MASK = (1 shl 13) - 1 - VTermSelectionMask* = enum + VTermSelectionMask* {.importc.} = enum VTERM_SELECTION_CLIPBOARD = (1 shl 0), VTERM_SELECTION_PRIMARY = (1 shl 1), VTERM_SELECTION_SECONDARY = (1 shl 2), diff --git a/tools/package_release.nims b/tools/package_release.nims index 2f27f25f9..34f3b33c0 100644 --- a/tools/package_release.nims +++ b/tools/package_release.nims @@ -41,7 +41,6 @@ proc copySharedFilesTo(dir: string) = cpDir2 "fonts", dir cpDir2 "languages", dir cpDir2 "themes", dir - cpDir2 "scripting", dir cpDir2 "docs", dir cpDir2 "res", dir mkDir dir / "src" diff --git a/wit/v0/api.wit b/wit/v0/api.wit index dea8756f0..8a6844062 100644 --- a/wit/v0/api.wit +++ b/wit/v0/api.wit @@ -24,6 +24,27 @@ interface types { size: vec2f, } + flags active-editor-flags { + include-command-line, + include-popups, + } + + record lamport { + replica-id: u16, + value: u32, + } + + enum bias { + left, + right, + } + + record anchor { + timestamp: lamport, + offset: u32, + bias: bias, + } + /// Shared reference to a rope. The rope data is stored in the editor, not in the plugin, so ropes /// can be used to efficiently access any document content or share a string with another plugin. /// Ropes are reference counted internally, and this resource also affects that reference count. @@ -39,15 +60,24 @@ interface types { lines: func() -> s64; /// Returns the text of the rope as a string. This is expensive for large ropes. text: func() -> string; - /// Returns a slice of the rope from 'a' to 'b'. 'a' and 'b' are byte indices, 'b' is exclusive. + /// Returns a slice of the rope from 'a' to 'b'. 'a' and 'b' are byte indices, 'b' is inclusive if `inclusive` is true. /// This operation is cheap because it doesn't create a copy of the text. - slice: func(a: s64, b: s64) -> rope; + slice: func(a: s64, b: s64, inclusive: bool) -> rope; + /// Returns a slice of the rope from the given selection. 's.last' is inclusive if `inclusive` is true. + /// This operation is cheap because it doesn't create a copy of the text. + slice-selection: func(s: selection, inclusive: bool) -> rope; + /// Find the byte index of the sub string 'sub', starting the search at 'start'. The returned index is relative to the start of the rope, not 'start'. + find: func(sub: string, start: s64) -> option; /// Returns a slice of the rope from 'a' to 'b'. The column of 'b' is exclusive. Columns are in bytes. /// This operation is cheap because it doesn't create a copy of the text. slice-points: func(a: cursor, b: cursor) -> rope; + /// Return the length in bytes of the given line (0 based). + line-length: func(line: s64) -> s64; // /// Returns a slice of the rope from line 'a' to 'b'. 'b' is inclusive. // /// This operation is cheap because it doesn't create a copy of the text. // slice-lines: func(a: s64, b: s64) -> rope; + rune-at: func(a: cursor) -> char; + byte-at: func(a: cursor) -> u8; } /// Non-owning handle to an editor. @@ -185,19 +215,34 @@ interface vfs { } interface editor { - use types.{editor, document}; + use types.{editor, document, active-editor-flags}; /// Returns a handle for the currently active text editor. - active-editor: func() -> option; + active-editor: func(options: active-editor-flags) -> option; /// Returns the document the given editor is currently editing. get-document: func(editor: editor) -> option; } interface text-editor { - use types.{editor, document, text-editor, text-document, cursor, selection, rope}; + use types.{editor, document, text-editor, text-document, cursor, selection, rope, active-editor-flags, anchor}; use commands.{command-error}; + enum scroll-behaviour { + center-always, + center-offscreen, + center-margin, + scroll-to-margin, + top-of-screen, + } + + enum scroll-snap-behaviour { + never, + always, + min-distance-offscreen, + min-distance-center, + } + /// Returns a handle for the currently active text editor. - active-text-editor: func() -> option; + active-text-editor: func(options: active-editor-flags) -> option; /// Returns the text document the given editor is currently editing. get-document: func(editor: text-editor) -> option; /// Try to cast the given editor handle to a text editor handle. @@ -208,14 +253,112 @@ interface text-editor { /// Run the given command on the given text editor. This requires 'command' permissions. command: func(editor: text-editor, name: string, arguments: string) -> result; + /// todo + record-current-command: func(editor: text-editor, registers: list); + /// todo + clear-current-command-history: func(editor: text-editor, retain-last: bool); + /// todo + save-current-command-history: func(editor: text-editor); + + /// todo + hide-completions: func(editor: text-editor); + + /// todo + scroll-to-cursor: func(editor: text-editor, behaviour: option, relative-position: f32); + /// todo + set-next-snap-behaviour: func(editor: text-editor, behaviour: scroll-snap-behaviour); + + /// todo + update-target-column: func(editor: text-editor); + + /// todo + get-usage: func(editor: text-editor) -> string; + /// todo + get-revision: func(editor: text-editor) -> s32; + /// todo + set-mode: func(editor: text-editor, mode: string, exclusive: bool); + /// todo + mode: func(editor: text-editor) -> string; + /// todo + modes: func(editor: text-editor) -> list; + /// todo + clear-tab-stops: func(editor: text-editor); + /// todo + undo: func(editor: text-editor, checkpoint: string); + /// todo + redo: func(editor: text-editor, checkpoint: string); + /// todo + add-next-checkpoint: func(editor: text-editor, checkpoint: string); + /// todo + copy: func(editor: text-editor, register: string, inclusive-end: bool); + /// todo + paste: func(editor: text-editor, selections: list, register: string, inclusive-end: bool); + /// todo + auto-show-completions: func(editor: text-editor); + /// todo + toggle-line-comment: func(editor: text-editor); + /// todo + insert-text: func(editor: text-editor, text: string, auto-indent: bool); + /// todo + open-search-bar: func(editor: text-editor, query: string, scroll-to-preview: bool, select-result: bool); + + /// Set the search query by applying the given move to the current selection. + /// 'prefix' and 'suffix' are appended to the string after escaping. + set-search-query-from-move: func(editor: text-editor, move: string, count: s32, prefix: string, suffix: string) -> selection; + /// Set the search query to 'query'. If 'escape-regex' is true the the 'query' string is escaped so special characters + /// are searched for literally. 'prefix' and 'suffix' are appended to the string after escaping. + set-search-query: func(editor: text-editor, query: string, escape-regex: bool, prefix: string, suffix: string) -> bool; + /// Returns the current search query. + get-search-query: func(editor: text-editor) -> string; + + /// todo + apply-move: func(editor: text-editor, selection: selection, move: string, count: s32, wrap: bool, include-eol: bool) -> list; + multi-move: func(editor: text-editor, selections: list, move: string, count: s32, wrap: bool, include-eol: bool) -> list; + /// Sets the given selection as the only selection for the given editor. set-selection: func(editor: text-editor, s: selection); + /// Sets the selections for the given editor. + set-selections: func(editor: text-editor, s: list); /// Returns the last selection of the given editor. get-selection: func(editor: text-editor) -> selection; + /// Returns the selections of the given editor. + get-selections: func(editor: text-editor) -> list; + /// Return the length of the given line (0 based) + line-length: func(editor: text-editor, line: s32) -> s32; /// Add a callback which will be called whenever any editor changes mode. add-mode-changed-handler: func(fun: u32) -> s32; - edit: func(editor: text-editor, selections: list, contents: list) -> list; + /// Returns the value of the setting with the given path, encoded as JSON. + get-setting-raw: func(editor: text-editor, name: string) -> string; + + /// Set the value of the setting with the given path. The value must be encoded as JSON. + set-setting-raw: func(editor: text-editor, name: string, value: string); + + /// todo + evaluate-expressions: func(editor: text-editor, selections: list, inclusive: bool, prefix: string, suffix: string, add-selection-index: bool); + + /// todo + indent: func(editor: text-editor, delta: s32); + + /// todo + get-command-count: func(editor: text-editor) -> s32; + + /// todo + set-cursor-scroll-offset: func(editor: text-editor, cursor: cursor, scroll-offset: f32); + + /// Returns the number of lines that fit on the current screen size for this editor. + get-visible-line-count: func(editor: text-editor) -> s32; + + /// todo + create-anchors: func(editor: text-editor, selections: list) -> list>; + + /// todo + resolve-anchors: func(editor: text-editor, anchors: list>) -> list; + + /// todo + edit: func(editor: text-editor, selections: list, contents: list, inclusive: bool) -> list; + + define-move: func(move: string, fun: u32, data: u32); /// Returns the rope containing the current content of the text editors document. /// This rope is not automatically kept up to date when the document changes, but @@ -224,6 +367,23 @@ interface text-editor { content: func(editor: text-editor) -> rope; } +interface registers { + /// todo + is-replaying-commands: func() -> bool; + /// todo + is-recording-commands: func(register: string) -> bool; + /// todo + set-register-text: func(text: string, register: string); + /// todo + get-register-text: func(register: string) -> string; + /// todo + start-recording-commands: func(register: string); + /// todo + stop-recording-commands: func(register: string); + /// todo + replay-commands: func(register: string); +} + interface text-document { use types.{text-document, cursor, selection, rope}; @@ -248,6 +408,9 @@ interface layout { close: func(v: view, keep-hidden: bool, restore-hidden: bool); /// Set focus to the view in the given slot. focus: func(slot: string); + /// Close the active view. If 'close-open-popup' is set and a popup is open then the popup will be closed. + /// If 'restore-hidden' is true then the view will be replaced by a hidden view, otherwise the slot will be removed from the layout.. + close-active-view: func(close-open-popup: bool, restore-hidden: bool); } interface render { @@ -355,6 +518,9 @@ interface commands { /// Run the given command. This requires 'command' permissions. run-command: func(name: string, arguments: string) -> result; + + /// Close the command line. + exit-command-line: func(); } interface settings { @@ -368,12 +534,14 @@ interface settings { interface guest { use render.{view}; use channel.{channel-listen-response}; + use types.{rope, selection}; init-plugin: func(); handle-command: func(fun: u32, data: u32, arguments: string) -> string; handle-mode-changed: func(fun: u32, old: string, new: string); handle-view-render-callback: func(id: s32, fun: u32, data: u32); handle-channel-update: func(fun: u32, data: u32, closed: bool) -> channel-listen-response; notify-task-complete: func(task: u64, canceled: bool); + handle-move: func(fun: u32, data: u32, text: u32, selections: list, count: s32, eol: bool) -> list; } /// APIs which can safely be used on a background thread @@ -400,6 +568,7 @@ world plugin { import vfs; import channel; import process; + import registers; export guest; }