diff --git a/.editorconfig b/.editorconfig deleted file mode 100644 index 5ac29c5..0000000 --- a/.editorconfig +++ /dev/null @@ -1,8 +0,0 @@ -[*] -end_of_file = lf -insert_final_newline = true - -[*.lua] -indent_size = 2 -indent_style = space - diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..a231b3a --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +lua/**/*.lua linguist-generated +lua/example/nfnl/**/*.lua linguist-vendored diff --git a/.gitignore b/.gitignore index 464d172..6912fef 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1 @@ deps/ -.eca/ diff --git a/.ignore b/.ignore new file mode 100644 index 0000000..3fe5d97 --- /dev/null +++ b/.ignore @@ -0,0 +1 @@ +lua/**/*.lua diff --git a/.luacheckrc b/.luacheckrc deleted file mode 100644 index 4f83aba..0000000 --- a/.luacheckrc +++ /dev/null @@ -1,3 +0,0 @@ -read_globals = { - "vim", -} diff --git a/.nfnl.fnl b/.nfnl.fnl new file mode 100644 index 0000000..8695d70 --- /dev/null +++ b/.nfnl.fnl @@ -0,0 +1,9 @@ +(local core (require :eca.nfnl.core)) +(local config (require :eca.nfnl.config)) +(local defaults (config.default)) + +{:compiler-options (core.merge + defaults.compiler-options + {:compilerEnv _G}) + :source-file-patterns [".nvim.fnl" "plugin/*.fnl" "fnl/**/*.fnl"] + :orphan-detection {:ignore-patterns ["lua/eca/nfnl/"]}} diff --git a/Makefile b/Makefile index c78e03a..9023667 100644 --- a/Makefile +++ b/Makefile @@ -1,27 +1,20 @@ # Makefile for ECA Neovim plugin testing -.PHONY: test test-file deps clean +.PHONY: test deps clean # Download dependencies for testing -deps: deps/mini.nvim deps/nui.nvim +deps: deps/plenary.nvim -deps/mini.nvim: +deps/plenary.nvim: mkdir -p deps - git clone --filter=blob:none https://github.com/echasnovski/mini.nvim deps/mini.nvim - -deps/nui.nvim: - mkdir -p deps - git clone --filter=blob:none https://github.com/MunifTanjim/nui.nvim deps/nui.nvim + git clone --filter=blob:none https://github.com/nvim-lua/plenary.nvim.git deps/plenary.nvim # Run all tests test: deps - nvim --headless --noplugin -u ./scripts/minimal_init.lua -c "lua MiniTest.run()" - -# Run a specific test file -# Usage: make test-file FILE=tests/test_example.lua -test-file: deps - nvim --headless --noplugin -u ./scripts/minimal_init.lua -c "lua MiniTest.run_file('$(FILE)')" + nvim --headless -u NONE --noplugin \ + -c "set rtp^=deps/plenary.nvim" \ + -c "lua require('plenary.test_harness').test_directory_command(\"lua/spec\")" # Clean up dependencies clean: - rm -rf deps/ \ No newline at end of file + rm -rf deps/ diff --git a/after/plugin/eca-nvim.lua b/after/plugin/eca-nvim.lua deleted file mode 100644 index 747534e..0000000 --- a/after/plugin/eca-nvim.lua +++ /dev/null @@ -1,29 +0,0 @@ ----@diagnostic disable-next-line: param-type-mismatch -local has_cmp, cmp = pcall(require, "cmp") -if has_cmp then - cmp.register_source("eca_commands", require("eca.completion.cmp.commands").new()) - cmp.register_source("eca_contexts", require("eca.completion.cmp.context").new()) - cmp.setup.filetype("eca-input", { - sources = { - { name = "eca_contexts" }, - { name = "eca_commands" }, - }, - }) -end - -local has_blink, blink = pcall(require, "blink.cmp") -if has_blink then - blink.add_source_provider("eca_commands", { - name = "eca_commands", - module = "eca.completion.blink.commands", - enabled = true, - }) - blink.add_filetype_source("eca-input", "eca_commands") - - blink.add_source_provider("eca_contexts", { - name = "eca_contexts", - module = "eca.completion.blink.context", - enabled = true, - }) - blink.add_filetype_source("eca-input", "eca_contexts") -end diff --git a/demo.png b/demo.png deleted file mode 100644 index 6d161ca..0000000 Binary files a/demo.png and /dev/null differ diff --git a/docs/configuration.md b/docs/configuration.md deleted file mode 100644 index fe65c5b..0000000 --- a/docs/configuration.md +++ /dev/null @@ -1,353 +0,0 @@ -# Configuration - -ECA is highly configurable. This page lists all available options and provides common presets. - -## Full configuration reference - -```lua -require("eca").setup({ - -- === SERVER === - - -- Path to the ECA binary - -- - Empty string: automatically download & manage the binary - -- - Custom path: use your own binary - server_path = "", - - -- Extra arguments passed to the ECA server (eca start ...) - server_args = "", - - -- === LOGGING === - log = { - -- Where to display logs inside Neovim - -- "split" - use a split window - -- "float" - use a floating window - -- "none" - disable the log window - display = "split", - - -- Minimum log level to record - -- vim.log.levels.TRACE | DEBUG | INFO | WARN | ERROR - level = vim.log.levels.INFO, - - -- Optional file path for persistent logs (empty = disabled) - file = "", - - -- Maximum log file size before ECA warns you (in MB) - max_file_size_mb = 10, - }, - - -- === BEHAVIOR === - behavior = { - -- Set default keymaps automatically - auto_set_keymaps = true, - - -- Focus the ECA sidebar when opening it - auto_focus_sidebar = true, - - -- Automatically start the server on plugin setup - auto_start_server = false, - - -- Automatically download the server if not found - auto_download = true, - - -- Show status updates (startup, downloads, errors) as notifications - show_status_updates = true, - }, - - -- === CONTEXT === - context = { - -- Automatically attach repo context (repoMap) when starting new chats - auto_repo_map = true, - }, - - -- === KEY MAPPINGS === - mappings = { - chat = "ec", -- Open chat - focus = "ef", -- Focus sidebar - toggle = "et",-- Toggle sidebar - - -- Chat input submit keys (per-mode). Always bound regardless of - -- `behavior.auto_set_keymaps`, since the input window is unusable without - -- a way to send. Override one or both — partial overrides preserve the - -- other mode's default. - -- - -- Example "chat-app feel" override (insert-mode Enter sends, no easy - -- newline while composing): - -- submit = { insert = "" } - submit = { - normal = "", - insert = "", - }, - }, - - -- === WINDOWS & UI === - windows = { - -- Automatic line wrapping in ECA buffers - wrap = true, - - -- Width as percentage of Neovim columns (1–100) - width = 40, - - -- Sidebar header configuration - sidebar_header = { - enabled = true, - align = "center", -- "left", "center", "right" - rounded = true, - }, - - -- Input area configuration - input = { - prefix = "> ", -- Input line prefix - height = 8, -- Input window height (lines) - - -- Maximum length for web context names in the input area - web_context_max_len = 20, - }, - - -- Edit window configuration - edit = { - border = "rounded", -- "none", "single", "double", "rounded" - start_insert = true, -- Start in insert mode - }, - - -- Usage line configuration (token / cost display) - usage = { - -- Supported placeholders: - -- {session_tokens} - raw session token count (e.g. "30376") - -- {limit_tokens} - raw token limit (e.g. "400000") - -- {session_tokens_short} - shortened session tokens (e.g. "30k") - -- {limit_tokens_short} - shortened token limit (e.g. "400k") - -- {session_cost} - session cost (e.g. "0.09") - -- Default: "30k / 400k ($0.09)" -> - -- "{session_tokens_short} / {limit_tokens_short} (${session_cost})" - format = "{session_tokens_short} / {limit_tokens_short} (${session_cost})", - }, - - -- Chat window & behavior - chat = { - -- Prefixes for each speaker - headers = { - user = "> ", - assistant = "", - }, - - -- Welcome message configuration - welcome = { - -- If non-empty, overrides the server-provided welcome message - message = "", - - -- Tips appended under the welcome (set {} to disable). - -- Available placeholders: {submit_key_normal}, {submit_key_insert} - tips = { - "Type your message and press {submit_key_insert} to send", - }, - }, - - -- Typewriter effect for streaming responses - typing = { - enabled = true, -- Enable/disable typewriter effect - chars_per_tick = 1, -- Characters to display per tick (1 = realistic typing) - tick_delay = 10, -- Delay in ms between ticks (lower = faster typing) - }, - - -- Tool call display settings - tool_call = { - icons = { - success = "✅", -- Shown when a tool call succeeds - error = "❌", -- Shown when a tool call fails - running = "⏳", -- Shown while a tool call is running - expanded = "▼", -- Arrow when the tool call details are expanded - collapsed = "▶", -- Arrow when the tool call details are collapsed - }, - diff = { - collapsed_label = "+ view diff", -- Label when the diff is collapsed - expanded_label = "- view diff", -- Label when the diff is expanded - expanded = false, -- When true, tool diffs start expanded - }, - preserve_cursor = true, -- When true, cursor stays in place when expanding/collapsing - }, - - -- Reasoning ("Thinking") block behavior - reasoning = { - expanded = false, -- When true, "Thinking" blocks start expanded - running_label = "Thinking...", -- Label while reasoning is running - finished_label = "Thought", -- Base label when reasoning is finished - }, - }, - }, -}) -``` - ---- - -## Presets - -These examples show how to override just a subset of the configuration. - -### Minimalist -```lua -require("eca").setup({ - behavior = { - show_status_updates = false, - }, - windows = { - width = 30, - chat = { - headers = { - user = "> ", - assistant = "", - }, - }, - }, -}) -``` - -### Visual / UX focused -```lua -require("eca").setup({ - behavior = { auto_focus_sidebar = true }, - windows = { - width = 50, - wrap = true, - sidebar_header = { enabled = true, rounded = true }, - input = { prefix = "💬 ", height = 10 }, - chat = { - headers = { - user = "## 👤 You\n\n", - assistant = "## 🤖 ECA\n\n", - }, - reasoning = { - expanded = true, - }, - }, - }, -}) -``` - -### Development -```lua -require("eca").setup({ - server_args = "--log-level debug", - log = { - level = vim.log.levels.DEBUG, - display = "split", - }, -}) -``` - -### Typing Speed Presets - -```lua --- Fast typing (2x speed) -require("eca").setup({ - windows = { - chat = { - typing = { - enabled = true, - chars_per_tick = 2, -- 2 characters at a time - tick_delay = 5, -- 5ms between ticks - }, - }, - }, -}) - --- Slow/realistic typing -require("eca").setup({ - windows = { - chat = { - typing = { - enabled = true, - chars_per_tick = 1, -- 1 character at a time - tick_delay = 30, -- 30ms between ticks (~33 chars/sec) - }, - }, - }, -}) - --- Instant display (no typing effect) -require("eca").setup({ - windows = { - chat = { - typing = { - enabled = false, -- Disable typing effect - }, - }, - }, -}) -``` - -### Tool Call Behavior - -```lua --- Keep cursor in place when expanding/collapsing tool calls -require("eca").setup({ - windows = { - chat = { - tool_call = { - preserve_cursor = true, -- Don't move cursor on expand/collapse - diff = { - expanded = true, -- Start with diffs expanded - }, - }, - }, - }, -}) -``` - ---- - -## Migration Guide - -### Upgrading from older versions - -If you have existing configuration, note these changes: - -**Config structure changes:** -- `debug` option removed → Use `log.level = vim.log.levels.DEBUG` -- `usage_string_format` moved → Now `windows.usage.format` -- `chat.*` options moved → Now nested under `windows.chat.*` - -**Legacy config is still supported** through automatic merging, but the new structure is recommended: - -```lua --- Old (still works) -require("eca").setup({ - debug = true, - usage_string_format = "{messageCost} / {sessionCost}", - chat = { - headers = { user = "> " }, - }, -}) - --- New (recommended) -require("eca").setup({ - log = { - level = vim.log.levels.DEBUG, - }, - windows = { - usage = { - format = "{session_cost}", - }, - chat = { - headers = { user = "> " }, - }, - }, -}) -``` - -**New placeholders for usage format:** -- `{session_tokens}` → Raw session token count -- `{limit_tokens}` → Raw token limit -- `{session_tokens_short}` → Shortened format (e.g., "30k") -- `{limit_tokens_short}` → Shortened format (e.g., "400k") -- `{session_cost}` → Session cost - ---- - -## Notes -- Set `server_path` if you prefer using a local ECA binary. -- Use the `log` block to control verbosity and where logs are written. -- `context.auto_repo_map` controls whether repo context is attached automatically. - -- Adjust `windows.width` to fit your layout. -- Keymaps can be set manually by turning off `behavior.auto_set_keymaps` and defining your own mappings. -- The `windows.usage.format` string controls how token and cost usage are displayed. diff --git a/docs/development.md b/docs/development.md deleted file mode 100644 index afd70b5..0000000 --- a/docs/development.md +++ /dev/null @@ -1,70 +0,0 @@ -# Development and Contribution - -## Support -- Issues: https://github.com/editor-code-assistant/eca-nvim/issues -- Discussions: https://github.com/editor-code-assistant/eca-nvim/discussions -- Wiki: https://github.com/editor-code-assistant/eca-nvim/wiki - -## Local development - -1. Clone the repository - ```bash - git clone https://github.com/editor-code-assistant/eca-nvim.git - ``` - -2. Configure local path (optional) - ```lua - require("eca").setup({ - debug = true, - -- server_path = "/path/to/eca-binary", - }) - ``` - -3. Test changes - ```vim - :luafile % - :EcaServerRestart - ``` - -## Contributing - -1. Fork the repository -2. Create a branch: `git checkout -b feature/new-functionality` -3. Commit your changes: `git commit -m 'Add new functionality'` -4. Push to your branch: `git push origin feature/new-functionality` -5. Open a Pull Request - -## Testing - -Run tests before submitting a PR: - -```bash -# Run all tests with mini.test -nvim --headless -u scripts/minimal_init.lua -c "lua require('mini.test').setup(); MiniTest.run_file('tests/test_eca.lua')" - -# Run specific test files -nvim --headless -u scripts/minimal_init.lua -c "lua require('mini.test').setup(); MiniTest.run_file('tests/test_stream_queue.lua')" -nvim --headless -u scripts/minimal_init.lua -c "lua require('mini.test').setup(); MiniTest.run_file('tests/test_sidebar_usage_and_tools.lua')" - -# Manual test -nvim -c "lua require('eca').setup({log = {level = vim.log.levels.DEBUG}})" -``` - -### Test Coverage - -The plugin includes comprehensive tests for: -- Core configuration and utilities (`test_eca.lua`, `test_utils.lua`) -- Stream queue and typewriter effect (`test_stream_queue.lua`) -- Sidebar tool calls and reasoning blocks (`test_sidebar_usage_and_tools.lua`) -- Picker commands (`test_picker.lua`, `test_server_picker_commands.lua`) -- Highlight groups (`test_highlights.lua`) - -### Highlight Groups - -ECA defines custom highlight groups for UI elements: -- `EcaToolCall` - Tool call headers -- `EcaHyperlink` - Clickable diff labels -- `EcaLabel` - Muted text (context labels, reasoning headers) -- `EcaSuccess`, `EcaWarning`, `EcaInfo` - Status indicators - -These can be customized in your colorscheme or via `:highlight` commands. diff --git a/docs/installation.md b/docs/installation.md deleted file mode 100644 index b653006..0000000 --- a/docs/installation.md +++ /dev/null @@ -1,164 +0,0 @@ -# Installation - -This guide covers system requirements and how to install the ECA Neovim plugin with popular plugin managers. - -## System Requirements - -### Required -- Neovim >= 0.8.0 (Recommended: >= 0.9.0) -- curl (for automatic server download) -- unzip (for server extraction) -- Internet connection (for initial download and ECA functionality) - -### Optional -- plenary.nvim — Utility functions used by some distributions -- snacks.nvim — Required for `:EcaServerMessages` and `:EcaServerTools` commands (picker functionality) - -### Tested Systems -- macOS (Intel and Apple Silicon) -- Linux (Ubuntu, Arch, Fedora, etc.) -- Windows (WSL2 recommended) -- FreeBSD - ---- - -## Install with popular plugin managers - -### lazy.nvim (recommended) - -```lua -{ - "editor-code-assistant/eca-nvim", - dependencies = { - "MunifTanjim/nui.nvim", -- Required: UI framework - "nvim-lua/plenary.nvim", -- Optional: Enhanced async operations - "folke/snacks.nvim", -- Optional: Picker for server messages/tools - }, - opts = {} -} -``` - -Advanced setup example: - -```lua -{ - "editor-code-assistant/eca-nvim", - dependencies = { - "MunifTanjim/nui.nvim", -- Required: UI framework - "nvim-lua/plenary.nvim", -- Optional: Enhanced async operations - "folke/snacks.nvim", -- Optional: Picker for server messages/tools - }, - keys = { - { "ec", "EcaChat", desc = "Open ECA chat" }, - { "ef", "EcaFocus", desc = "Focus ECA sidebar" }, - { "et", "EcaToggle", desc = "Toggle ECA sidebar" }, - }, - opts = { - debug = false, - server_path = "", - behavior = { - auto_set_keymaps = true, - auto_focus_sidebar = true, - }, - } -} -``` - -### packer.nvim - -```lua -use { - "editor-code-assistant/eca-nvim", - requires = { - "MunifTanjim/nui.nvim", -- Required: UI framework - "nvim-lua/plenary.nvim", -- Optional: Enhanced async operations - "folke/snacks.nvim", -- Optional: Picker for server messages/tools - }, - config = function() - require("eca").setup({ - -- Your configurations here - }) - end -} -``` - -### vim-plug - -```vim -" In your init.vim or init.lua -Plug 'editor-code-assistant/eca-nvim' - -" Required dependencies -Plug 'MunifTanjim/nui.nvim' - -" Optional dependencies -Plug 'nvim-lua/plenary.nvim' " Enhanced async operations -Plug 'folke/snacks.nvim' " Picker for server messages/tools - -" After the plugins, add: -lua << EOF -require("eca").setup({ - -- Your configurations here -}) -EOF -``` - -### dein.vim - -```vim -call dein#add('editor-code-assistant/eca-nvim') - -" Required dependencies -call dein#add('MunifTanjim/nui.nvim') - -" Optional dependencies -call dein#add('nvim-lua/plenary.nvim') " Enhanced async operations -call dein#add('folke/snacks.nvim') " Picker for server messages/tools - -" Configuration -lua << EOF -require("eca").setup({ - -- Your configurations here -}) -EOF -``` - -### rocks.nvim - -```toml -# rocks.toml -[plugins] -"eca-nvim" = { git = "editor-code-assistant/eca-nvim" } - -# Required dependencies -"nui.nvim" = { git = "MunifTanjim/nui.nvim" } - -# Optional dependencies -"plenary.nvim" = { git = "nvim-lua/plenary.nvim" } # Enhanced async operations -"snacks.nvim" = { git = "folke/snacks.nvim" } # Picker for server messages/tools -``` - -### mini.deps - -```lua -local add = MiniDeps.add - -add({ - source = "editor-code-assistant/eca-nvim", - depends = { - "MunifTanjim/nui.nvim", -- Required: UI framework - "nvim-lua/plenary.nvim", -- Optional: Enhanced async operations - "folke/snacks.nvim", -- Optional: Picker for server messages/tools - } -}) - -require("eca").setup({ - -- Your configurations here -}) -``` - ---- - -## Next steps -- See the Usage guide for getting started with chat and context: [docs/usage.md](./usage.md) -- Explore configuration options: [docs/configuration.md](./configuration.md) diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md deleted file mode 100644 index b9ce6b9..0000000 --- a/docs/troubleshooting.md +++ /dev/null @@ -1,85 +0,0 @@ -# Troubleshooting - -Common issues and how to fix them. - -## Server won't start - -Symptoms: Chat doesn't respond, "server not running" error - -Solutions: -- Check if `curl` and `unzip` are installed -- Try setting `server_path` manually with absolute path -- Check logs with `debug = true` in configuration -- Try `:EcaServerRestart` - -```lua --- Debug configuration -require("eca").setup({ - server_args = "--log-level debug", - log = { - level = vim.log.levels.DEBUG, - display = "split", - }, -}) -``` - -You can also use these debug commands to inspect the server state: -- `:EcaServerMessages` - View all server messages -- `:EcaServerTools` - View all registered tools - -## Connectivity issues - -Symptoms: Download fails, timeouts, network errors - -Solutions: -- Check your internet connection -- Ensure firewalls are not blocking requests -- Restart with `:EcaServerRestart` -- Configure a proxy if necessary -- Download the server manually and set `server_path` - -## Shortcuts not working - -Symptoms: `ec` doesn't open chat - -Solutions: -- Ensure `behavior.auto_set_keymaps = true` -- Confirm your `` key (default: `\`) -- Configure shortcuts manually: - -```lua -vim.keymap.set("n", "ec", ":EcaChat", { desc = "ECA Chat" }) -vim.keymap.set("n", "et", ":EcaToggle", { desc = "ECA Toggle" }) -``` - -## Windows-specific - -Symptoms: Path errors, server not found - -Solutions: -- Use WSL2 for better compatibility -- Install curl and unzip on Windows -- Use forward slashes `/` in paths -- Configure `server_path` with `.exe` extension - -## Performance issues - -Symptoms: Lag when typing, slow responses, slow streaming - -Solutions: -- Reduce window width: `windows.width = 25` -- Disable visual updates: `behavior.show_status_updates = false` -- Speed up or disable typewriter effect: - ```lua - windows = { - chat = { - typing = { - enabled = false, -- Instant display - -- OR - chars_per_tick = 10, -- Much faster typing - tick_delay = 1, - }, - }, - } - ``` -- Use the minimalist configuration preset diff --git a/docs/usage.md b/docs/usage.md deleted file mode 100644 index de1f58c..0000000 --- a/docs/usage.md +++ /dev/null @@ -1,449 +0,0 @@ -# Usage - -Everything you need to get productive with ECA inside Neovim. - -## What's New - -Recent updates include: - -- **Expandable tool calls**: Click `Enter` on tool call headers to show/hide arguments, outputs, and diffs -- **Reasoning blocks**: See ECA's "thinking" process with expandable reasoning content -- **Typewriter effect**: Responses stream with a configurable typing animation (can be disabled) -- **Enhanced MCP display**: See active vs. registered MCP server counts with status indicators -- **Debug commands**: `:EcaServerMessages` and `:EcaServerTools` for inspecting server state -- **Better usage display**: Shortened token counts (e.g., "30k / 400k") with customizable format -- **Improved highlights**: New `EcaToolCall`, `EcaHyperlink`, and `EcaLabel` highlight groups - -## Quick Start - -1. Install the plugin using any package manager -2. Restart Neovim or reload your configuration -3. Open a file you want to analyze -4. Run `:EcaChat` or press `ec` -5. On first run, the server downloads automatically -6. Type your question and press `` to send (configurable — see [Configuration](./configuration.md)) - ---- - -## Available Commands - -| Command | Description | Example | -|--------|-------------|---------| -| `:EcaChat` | Open ECA chat sidebar | `:EcaChat` | -| `:EcaToggle` | Toggle sidebar visibility | `:EcaToggle` | -| `:EcaFocus` | Focus ECA sidebar | `:EcaFocus` | -| `:EcaClose` | Close ECA sidebar | `:EcaClose` | -| `:EcaChatAddFile [file]` | Add a file as context for the current chat | `:EcaChatAddFile lua/eca/sidebar.lua` | -| `:EcaChatRemoveFile [file]` | Remove a file context from the current chat | `:EcaChatRemoveFile lua/eca/sidebar.lua` | -| `:EcaChatAddSelection` | Add current visual selection as a file-range context | `:EcaChatAddSelection` | -| `:EcaChatAddUrl` | Add a URL as "web" context | `:EcaChatAddUrl` | -| `:EcaChatListContexts` | List active contexts for the current chat | `:EcaChatListContexts` | -| `:EcaChatClearContexts` | Clear all contexts for the current chat | `:EcaChatClearContexts` | -| `:EcaServerStart` | Start ECA server manually | `:EcaServerStart` | -| `:EcaServerStop` | Stop ECA server | `:EcaServerStop` | -| `:EcaServerRestart` | Restart ECA server | `:EcaServerRestart` | -| `:EcaServerMessages` | Display server messages (for debugging) | `:EcaServerMessages` | -| `:EcaServerTools` | Display registered server tools | `:EcaServerTools` | -| `:EcaSend ` | Send message directly (without opening chat) | `:EcaSend Explain this function` | - -Deprecated aliases (still available but log a warning): `:EcaAddFile`, `:EcaAddSelection`, `:EcaRemoveContext`, `:EcaListContexts`, `:EcaClearContexts`. Prefer the `:EcaChat*` variants above. - ---- - -## Keyboard Shortcuts - -### Global (default) - -| Shortcut | Action | -|----------|--------| -| `ec` | Open/focus chat | -| `ef` | Focus on sidebar | -| `et` | Toggle sidebar | - -### Chat - -| Shortcut | Action | Context | -|----------|--------|---------| -| `` | Send message (default) | Normal mode in input | -| `` | Send message (default) | Insert mode in input | -| `Enter` | New line | Insert mode | -| `Enter` (in chat buffer) | Toggle tool call/reasoning block | Normal mode on tool call or reasoning header | -| `Esc` | Exit insert mode | Insert mode | - -Submit keys are configurable via `mappings.submit.normal` and `mappings.submit.insert` — see [Configuration](./configuration.md). - ---- - -## Using the Chat - -### Sending messages -- Type in the input line starting with `> ` -- Press `Enter` to insert a new line (insert mode) -- Press `` (insert mode) or `` (normal mode) to send — both configurable -- Responses stream in real time with a typewriter effect (configurable) - -### Interacting with responses - -#### Tool calls -When ECA uses tools (like file editing), tool calls appear in the chat with: -- **Header line**: Shows tool name and status icon (⏳ running, ✅ success, ❌ error) -- **Expandable details**: Press `Enter` on the header to show/hide arguments and outputs -- **Diff view**: If a tool modifies files, a "view diff" label appears below the header. Press `Enter` on this label to expand/collapse the diff - -#### Reasoning blocks -When ECA is "thinking" (extended reasoning), you'll see: -- **"Thinking..."** label while reasoning is active -- **"Thought X.XX s"** label when complete, showing elapsed time -- Press `Enter` on the header to expand/collapse the reasoning content - -These blocks can be configured to start expanded or collapsed (see Configuration) - -### Examples - -```markdown -Explain what this function does -``` - -```markdown -Optimize this code: -[code will be added as context] -``` - -```markdown -How can I improve the performance of this function? -Consider readability and maintainability. -``` - ---- - -## Adding Context - -### Current file - -```vim -:EcaChatAddFile -``` - -Adds the current buffer as a file context for the active chat. - -### Specific file - -```vim -:EcaChatAddFile src/main.lua -:EcaChatAddFile /full/path/to/file.js -``` - -Pass a path to add that file as context. Relative paths are resolved to absolute paths. - -### Code selection - -1. Select code in visual mode (`v`, `V`, or `Ctrl+v`) -2. Run `:EcaChatAddSelection` -3. The selected lines will be added as a file-range context (file + line range) - -### Web URLs - -```vim -:EcaChatAddUrl -``` - -Prompts for a URL and adds it as a `web` context. The URL label in the input is truncated for display, but the full URL is sent to the server. - -### Listing and clearing contexts - -```vim -:EcaChatListContexts " show all active contexts -:EcaChatClearContexts " remove all contexts from the current chat -:EcaChatRemoveFile " remove the current file from contexts -``` - -### Multiple files - -```vim -:EcaChatAddFile -:EcaChatAddFile src/utils.lua -:EcaChatAddFile src/config.lua -:EcaChatAddFile tests/test_utils.lua -``` - -### Context area in the input - -When the sidebar is open, the chat input buffer has **two parts**: - -1. **First line – context area**: shows one label per active context (e.g. `sidebar.lua `, `sidebar.lua:25-50 ` or a truncated URL). -2. **Below that – message input**: your prompt, prefixed by `> ` (configurable via `windows.input.prefix`). - -You normally do not need to edit the first line manually, but you can: - -- **Remove a single context**: move the cursor to the corresponding label on the first line and delete it; the context is removed from the current chat while your message text is preserved. -- **Clear all contexts**: delete the whole first line; ECA restores an empty context line and clears all contexts. - -#### Examples - -**No contexts yet** - -```text -@ -> Explain this code -``` - -**Single file context** - -```text -@sidebar.lua @ -> Explain this code -``` - -**Two contexts (file + line range)** - -```text -@sidebar.lua @sidebar.lua:25-50 @ -> Explain this selection -``` - -If you now delete just the `sidebar.lua:25-50 ` label on the first line, only that context is removed: - -```text -@sidebar.lua @ -> Explain this selection -``` - -If instead you delete the **entire first line**, all contexts are cleared. ECA recreates an empty context line internally and keeps your input text: - -```text -@ -> Explain this selection -``` - -When typing paths directly with `@` to trigger completion, the input might briefly look like: - -```text -@lua/eca/sidebar.lua -> Input text -``` - -After confirming a completion item, that `@...` reference is turned into a context entry and shown as a short label (for example `sidebar.lua `) in the context area. - ---- - -## Model Context Protocol (MCP) Servers - -ECA supports MCP servers for extended functionality. The config display line at the bottom of the sidebar shows: - -``` -model: behavior: mcps: 2/3 -``` - -Where: -- The first number (2) is the count of **active MCPs** (starting + running) -- The second number (3) is the **total registered MCPs** - -**Status indicators**: -- Gray text: One or more MCPs are still starting -- Red text: One or more MCPs failed to start -- Normal text: All MCPs are running successfully - -Use `:EcaServerTools` to see which tools are available from your MCP servers. - -### Context completion and `@` / `#` path shortcuts - -Inside the input (filetype `eca-input`): - -- Typing `@` or `#` followed by part of a path triggers context completion (via the provided `cmp`/`blink` sources). -- Selecting a completion item in the **context area line** automatically adds that item as a context for the current chat and shows it as a label on the first line. - -Semantics of the two prefixes: - -- **`@` prefix** – *inline content*: - - `@path/to/file.lua` means: "resolve this to the file contents and send those contents to the model". - - The server expands the `@` reference to the actual file content before forming the prompt. -- **`#` prefix** – *path reference*: - - `#path/to/file.lua` means: "send the full absolute path; the model will fetch and read the file itself". - - The server keeps it as a path reference in the prompt so the model can look up the file by path. - -In both cases, when you send a message any occurrences like: - -```text -@relative/path/to/file.lua -#another/path -``` - -are first expanded to absolute paths on the Neovim side (including `~` expansion). The difference is how the server then interprets `@` (inline file contents) versus `#` (path-only reference that the model resolves). - ---- - -## Common Use Cases - -### Code analysis -```markdown -> Analyze this file and tell me if there are performance issues -``` - -### Debugging -```markdown -> This code is returning an error. Can you help me identify the problem? -[add the file as context first] -``` - -### Documentation -```markdown -> Generate JSDoc documentation for these functions -``` - -### Refactoring -```markdown -> How can I refactor this code to use ES6+ features? -``` - -### Testing -```markdown -> Create unit tests for this function -``` - -### Optimization -```markdown -> Suggest improvements to optimize this algorithm -``` - ---- - -## Recommended Workflow - -1. Open the file you want to analyze -2. Add as context: `:EcaChatAddFile` -3. Open chat: `ec` -4. Ask your question: - ```markdown - > Explain what this function does and how I can improve it - ``` -5. Send with `` (insert) or `` (normal) -6. Read the response and implement suggestions -7. Continue the conversation for clarifications - ---- - -## Advanced Commands - -### Server management - -```vim -" Restart if there are issues -:EcaServerRestart - -" Stop temporarily -:EcaServerStop - -" Start again -:EcaServerStart - -" Debug: view server messages -:EcaServerMessages - -" Debug: view registered tools -:EcaServerTools -``` - -### Quick commands - -```vim -" Send message directly (without opening chat) -:EcaSend Explain this line of code - -" Focus on chat if already open -:EcaFocus - -" Toggle chat visibility -:EcaToggle -``` - ---- - -## Typewriter Effect - -ECA displays streaming responses with a configurable typewriter effect for a more natural reading experience. - -### Configuration - -```lua -require("eca").setup({ - windows = { - chat = { - typing = { - enabled = true, -- Enable/disable typewriter effect - chars_per_tick = 1, -- Characters per tick (higher = faster) - tick_delay = 10, -- Delay in ms between ticks (lower = faster) - }, - }, - }, -}) -``` - -### Presets - -**Fast typing (2x speed)**: -```lua -typing = { enabled = true, chars_per_tick = 2, tick_delay = 5 } -``` - -**Slow/realistic typing**: -```lua -typing = { enabled = true, chars_per_tick = 1, tick_delay = 30 } -``` - -**Instant display (no effect)**: -```lua -typing = { enabled = false } -``` - ---- - -## Tips and Tricks - -### Productivity -1. Use `:EcaChatAddFile` before asking about specific code -2. Combine contexts: add multiple related files -3. Be specific: detailed questions generate better responses -4. Use Markdown: ECA understands Markdown formatting - -### Workflows - -#### Code review -```markdown -> Analyze this code and suggest improvements: -- Performance -- Readability -- Best practices -- Possible bugs -``` - -#### Test creation -```markdown -> Create comprehensive unit tests for this function, including: -- Success cases -- Error cases -- Edge cases -- Mocks if necessary -``` - -#### Documentation -```markdown -> Generate complete documentation for this module: -- General description -- Parameters and types -- Usage examples -- Possible exceptions -``` - -### Custom shortcuts - -```lua --- More convenient shortcuts -vim.keymap.set("n", "", ":EcaChat") -vim.keymap.set("n", "", ":EcaToggle") -vim.keymap.set("v", "ea", ":EcaChatAddSelection") - --- Shortcut to add current file -vim.keymap.set("n", "ef", function() - vim.cmd("EcaChatAddFile " .. vim.fn.expand("%")) -end) -``` diff --git a/fnl/eca/init.fnl b/fnl/eca/init.fnl new file mode 100644 index 0000000..0752b83 --- /dev/null +++ b/fnl/eca/init.fnl @@ -0,0 +1,7 @@ +(local {: autoload} (require :eca.nfnl.module)) +(local notify (autoload :eca.nfnl.notify)) + +(fn setup [] + (notify.info "Hello, World!")) + +{: setup} diff --git a/fnl/eca/nfnl/macros.fnlm b/fnl/eca/nfnl/macros.fnlm new file mode 100644 index 0000000..6d1b0c4 --- /dev/null +++ b/fnl/eca/nfnl/macros.fnlm @@ -0,0 +1,52 @@ +(fn time [...] + `(let [start# (vim.loop.hrtime) + result# (do ,...) + end# (vim.loop.hrtime)] + (print (.. "Elapsed time: " (/ (- end# start#) 1000000) " msecs")) + result#)) + +(fn conditional-let [branch bindings ...] + (assert (= 2 (length bindings)) "expected a single binding pair") + + (let [[bind-expr value-expr] bindings] + (if + ;; Simple symbols + ;; [foo bar] + (sym? bind-expr) + `(let [,bind-expr ,value-expr] + (,branch ,bind-expr ,...)) + + ;; List / values destructure + ;; [(a b) c] + (list? bind-expr) + (do + ;; Even if the user isn't using the first slot, we will. + ;; [(_ val) (pcall #:foo)] + ;; => [(bindGENSYM12345 val) (pcall #:foo)] + (when (= `_ (. bind-expr 1)) + (tset bind-expr 1 (gensym "bind"))) + + `(let [,bind-expr ,value-expr] + (,branch ,(. bind-expr 1) ,...))) + + ;; Sequential and associative table destructure + ;; [[a b] c] + ;; [{: a : b} c] + (table? bind-expr) + `(let [value# ,value-expr + ,bind-expr (or value# {})] + (,branch value# ,...)) + + ;; We should never get here, but just in case. + (assert (.. "unknown bind-expr type: " (type bind-expr)))))) + +(fn if-let [bindings ...] + (assert (<= (length [...]) 2) (.. "if-let does not support more than two branches")) + (conditional-let `if bindings ...)) + +(fn when-let [bindings ...] + (conditional-let `when bindings ...)) + +{: time + : if-let + : when-let} diff --git a/fnl/eca/nfnl/macros/aniseed.fnlm b/fnl/eca/nfnl/macros/aniseed.fnlm new file mode 100644 index 0000000..ec68ae3 --- /dev/null +++ b/fnl/eca/nfnl/macros/aniseed.fnlm @@ -0,0 +1,51 @@ +;; Copied over from Aniseed. Contains all of the def* module macro systems. +;; https://github.com/Olical/aniseed + +;; This has been heavily slimmed down from the original implementation, the +;; `(module ...) macro can now ONLY define your module, it can not be used +;; to require dependencies. + +;; We had to slim things down because the Fennel compiler no longer supports +;; the weird tricks we were using. + +;; In nfnl they are not automatically required, you must use import-macros to +;; require them explicitly when migrating your Aniseed based projects. + +;; Avoids the compiler complaining that we're introducing locals without gensym. +(local mod-str :*module*) +(local mod-sym (sym mod-str)) + +;; Upserts the existence of the module for subsequent def forms. +;; +;; (module foo +;; {:some-optional-base :table-of-things +;; :to-base :the-module-off-of}) +(fn module [mod-name mod-base] + `(local + ,mod-sym + (let [pkg# (require :package)] + (tset pkg#.loaded ,(tostring mod-name) ,(or mod-base {})) + (. pkg#.loaded ,(tostring mod-name))))) + +(fn def- [name value] + `(local ,name ,value)) + +(fn def [name value] + `(local ,name (do (tset ,mod-sym ,(tostring name) ,value) (. ,mod-sym ,(tostring name))))) + +(fn defn- [name ...] + `(fn ,name ,...)) + +(fn defn [name ...] + `(def ,name (fn ,name ,...))) + +(fn defonce- [name value] + `(def- ,name (or ,name ,value))) + +(fn defonce [name value] + `(def ,name (or (. ,mod-sym ,(tostring name)) ,value))) + +{:module module + :def- def- :def def + :defn- defn- :defn defn + :defonce- defonce- :defonce defonce} diff --git a/fnl/spec/nfnl/example_spec.fnl b/fnl/spec/nfnl/example_spec.fnl new file mode 100644 index 0000000..a788aa7 --- /dev/null +++ b/fnl/spec/nfnl/example_spec.fnl @@ -0,0 +1,15 @@ +(local {: describe : it} (require :plenary.busted)) +(local assert (require :luassert.assert)) +(local core (require :eca.nfnl.core)) + +(describe + "first" + (fn [] + (it "gets the first value" + (fn [] + (assert.equals 1 (core.first [1 2 3 4 5])))) + + (it "returns nil for empty lists or nil" + (fn [] + (assert.is_nil (core.first nil)) + (assert.is_nil (core.first [])))))) diff --git a/lua/eca/api.lua b/lua/eca/api.lua deleted file mode 100644 index d061a67..0000000 --- a/lua/eca/api.lua +++ /dev/null @@ -1,431 +0,0 @@ -local Utils = require("eca.utils") -local Logger = require("eca.logger") - --- Load nui.nvim components for floating windows -local Popup = require("nui.popup") - ----@class eca.Api -local M = {} - ----@param opts? table -function M.chat(opts) - opts = opts or {} - local eca = require("eca") - - if not M.is_server_running() then - M.start_server() - end - - eca.open_sidebar(opts) -end - -function M.focus() - local eca = require("eca") - local sidebar = eca.get() - if sidebar then - sidebar:focus() - else - M.chat() - end -end - -function M.toggle() - local eca = require("eca") - return eca.toggle_sidebar() -end - -function M.close() - local eca = require("eca") - local sidebar = eca.get() - if sidebar then - sidebar:new_chat() -- This will reset and force welcome content on next open - else - eca.close_sidebar() - end -end - ----@param message string -function M.send_message(message) - local eca = require("eca") - local sidebar = eca.get() - if not sidebar or not sidebar:is_open() then - M.chat() - sidebar = eca.get() - end - - if sidebar then - sidebar:_send_message(message) - else - Logger.notify("Could not open ECA sidebar", vim.log.levels.ERROR) - end -end - ----@param file_path string -function M.add_file_context(file_path) - Logger.info("Adding file context: " .. file_path) - - local eca = require("eca") - - if not eca.server or not eca.server:is_running() then - Logger.notify("ECA server is not running", vim.log.levels.ERROR) - return - end - - -- Read file content - local content = Utils.read_file(file_path) - if not content then - Logger.notify("Could not read file: " .. file_path, vim.log.levels.ERROR) - return - end - - -- Create context object - local context = { - type = "file", - data = { - path = file_path, - } - } - - local chat = eca.get() - - if not chat or not chat.mediator then - Logger.notify("No active ECA Chat to add context", vim.log.levels.WARN) - return - end - - chat.mediator:add_context(context) - Logger.info("File context added: " .. vim.inspect(context)) -end - -function M.remove_file_context(path) - local eca = require("eca") - local chat = eca.get() - - if not chat or not chat.mediator then - Logger.notify("No active ECA Chat", vim.log.levels.WARN) - return - end - - -- Create context object - local context = { - type = "file", - data = { - path = path, - } - } - - Logger.info("Removing context: " .. vim.inspect(context)) - chat.mediator:remove_context(context) -end - -function M.remove_current_file_context() - local current_file = vim.api.nvim_buf_get_name(0) - if current_file and current_file ~= "" then - M.remove_file_context(current_file) - else - Logger.notify("No current file to remove as context", vim.log.levels.WARN) - end -end - ----@param directory_path string -function M.add_directory_context(directory_path) - Logger.info("Adding directory context: " .. directory_path) - local eca = require("eca") - - if not eca.server or not eca.server:is_running() then - Logger.notify("ECA server is not running", vim.log.levels.ERROR) - return - end - - -- Create context object for directory - local context = { - type = "directory", - data = { - path = directory_path, - }, - } - - local chat = eca.get() - - if not chat or not chat.mediator then - Logger.notify("No active ECA Chat to add context", vim.log.levels.WARN) - return - end - - chat.mediator:add_context(context) - Logger.info("Directory context added: " .. vim.inspect(context)) -end - ----@param url string -function M.add_web_context(url) - Logger.info("Adding web context: " .. url) - local eca = require("eca") - - if not eca.server or not eca.server:is_running() then - Logger.notify("ECA server is not running", vim.log.levels.ERROR) - return - end - - local chat = eca.get() - - if not chat or not chat.mediator then - Logger.notify("No active ECA Chat to add context", vim.log.levels.WARN) - return - end - - local context = { - type = "web", - data = { - path = url, - }, - } - - chat.mediator:add_context(context) - Logger.info("Web context added: " .. vim.inspect(context)) -end - -function M.add_current_file_context() - local current_file = vim.api.nvim_buf_get_name(0) - if current_file and current_file ~= "" then - M.add_file_context(current_file) - else - Logger.notify("No current file to add as context", vim.log.levels.WARN) - end -end - -function M.add_selection_context() - Logger.info("Adding selection context ...") - local eca = require("eca") - - -- Get visual selection marks (should be set by the command before calling this) - local start_pos = vim.fn.getpos("'<") - local end_pos = vim.fn.getpos("'>") - - if start_pos[2] == 0 or end_pos[2] == 0 then - Logger.notify("No selection to add as context. Please make a visual selection first.", vim.log.levels.WARN) - return - end - - -- Ensure we have the right line order - local start_line = math.min(start_pos[2], end_pos[2]) - local end_line = math.max(start_pos[2], end_pos[2]) - - local lines = vim.api.nvim_buf_get_lines(0, start_line - 1, end_line, false) - - if #lines <= 0 then - Logger.notify("No lines found in the selection", vim.log.levels.WARN) - return - end - - local current_file = vim.api.nvim_buf_get_name(0) - - -- Create context object - local context = { - type = "file", - data = { - path = current_file, - lines_range = { - line_start = start_line, - line_end = end_line, - }, - } - } - - local chat = eca.get() - - if not chat or not chat.mediator then - Logger.notify("No active ECA Chat to add context", vim.log.levels.WARN) - return - end - - chat.mediator:add_context(context) - Logger.info("Added selection context: " .. vim.inspect(context)) -end - -function M.list_contexts() - local eca = require("eca") - local chat = eca.get() - - if not chat or not chat.mediator then - Logger.notify("No active ECA sidebar", vim.log.levels.WARN) - return - end - - local contexts = chat.mediator:contexts() - if #contexts == 0 then - Logger.notify("No active contexts", vim.log.levels.INFO) - return - end - - Logger.info("Active contexts (" .. #contexts .. "):") - for i, context in ipairs(contexts) do - Logger.info(i .. ". " .. context.type .. ": " .. vim.inspect(context.data)) - end -end - -function M.clear_contexts() - local eca = require("eca") - local chat = eca.get() - - if not chat or not chat.mediator then - Logger.notify("No active ECA Chat", vim.log.levels.WARN) - return - end - - chat.mediator:clear_contexts() - Logger.info("Cleared all contexts") -end - ----@return boolean -function M.is_server_running() - local eca = require("eca") - return eca.server and eca.server:is_running() -end - -function M.start_server() - local eca = require("eca") - if eca.server then - eca.server:start() - else - Logger.notify("ECA server not initialized", vim.log.levels.ERROR) - end -end - -function M.stop_server() - local eca = require("eca") - if eca.server then - eca.server:stop() - end -end - -function M.restart_server() - M.stop_server() - vim.defer_fn(function() - M.start_server() - end, 1000) -end - -function M.server_status() - local eca = require("eca") - if eca.server then - return eca.server:status() - else - return "Not initialized" - end -end - --- Keep reference to logs popup globally to reuse it -local logs_popup = nil - -function M.show_logs() - -- File logging is always enabled now - local display = Logger.get_display() - if display == "popup" then - M._show_logs_in_popup() - else - M._show_logs_in_buffer() - end -end - ---- Show logs in a regular Neovim buffer (when file logging is enabled) -function M._show_logs_in_buffer() - local log_path = Logger.get_log_path() - - if vim.fn.filereadable(log_path) ~= 1 then - Logger.info("Log file does not exist yet: " .. log_path) - return - end - - vim.cmd("edit " .. vim.fn.fnameescape(log_path)) - local bufnr = vim.fn.bufnr("%") - - -- Set buffer options for log viewing - vim.api.nvim_set_option_value("modifiable", false, { buf = bufnr }) - vim.cmd("normal! G") - - Logger.debug("Opened ECA log file: " .. log_path) -end - ---- Show logs in a popup window -function M._show_logs_in_popup() - local log_path = Logger.get_log_path() - - -- Helper function to read latest log content - local function get_latest_log_content() - if vim.fn.filereadable(log_path) == 1 then - local content = vim.fn.readfile(log_path) - return #content > 0 and content or { "No log entries found" } - else - return { "Log file does not exist yet: " .. log_path } - end - end - - -- Helper function to setup popup close keymaps - local function setup_popup_keymaps(popup) - popup:map("n", "q", function() - popup:unmount() - end, { noremap = true, silent = true }) - - popup:map("n", "", function() - popup:unmount() - end, { noremap = true, silent = true }) - - -- Clean up reference when popup is closed - popup:on("BufWinLeave", function() - logs_popup = nil - end) - end - - -- Helper function to get responsive popup size - local function get_popup_size() - return { - width = math.floor(vim.o.columns * 0.8), - height = math.floor(vim.o.lines * 0.7), - } - end - - local function set_popup_content(popup, lines) - vim.api.nvim_set_option_value("modifiable", true, { buf = popup.bufnr }) - vim.api.nvim_buf_set_lines(popup.bufnr, 0, -1, false, lines) - vim.api.nvim_set_option_value("modifiable", false, { buf = popup.bufnr }) - vim.api.nvim_win_set_cursor(popup.winid, { #lines, 0 }) - end - - if logs_popup and logs_popup.winid and vim.api.nvim_win_is_valid(logs_popup.winid) then - set_popup_content(logs_popup, get_latest_log_content()) - return - end - - logs_popup = Popup({ - enter = true, - focusable = true, - border = { - style = "rounded", - text = { - top = " 📋 ECA Logs ", - top_align = "center", - }, - }, - position = "50%", - size = get_popup_size(), - buf_options = { - buftype = "nofile", - bufhidden = "hide", - swapfile = false, - modifiable = true, - filetype = "log", - }, - win_options = { - wrap = false, - number = true, - signcolumn = "no", - cursorline = true, - }, - }) - logs_popup:mount() - - set_popup_content(logs_popup, get_latest_log_content()) - setup_popup_keymaps(logs_popup) -end - -return M diff --git a/lua/eca/approve.lua b/lua/eca/approve.lua deleted file mode 100644 index fc94f7a..0000000 --- a/lua/eca/approve.lua +++ /dev/null @@ -1,103 +0,0 @@ -local M = {} - ----@param tool_call eca.ToolCallRun -function M.get_preview_lines(tool_call) - -- If no details or details without diff, show tool call info - if not tool_call.details or not tool_call.details.diff then - local arguments_text = tool_call.arguments or "" - local arguments = vim.split(vim.inspect(arguments_text), "\n") - local messages = {} - if tool_call.summary then - table.insert(messages, "Summary: " .. tool_call.summary) - end - table.insert(messages, "Tool Name: " .. (tool_call.name or "unknown")) - table.insert(messages, "Tool Type: " .. (tool_call.origin or "unknown")) - table.insert(messages, "Tool Arguments: ") - for _, v in pairs(arguments) do - table.insert(messages, v) - end - return messages - end - local lines = vim.split(tool_call.details.diff, "\n") - return { tool_call.details.path or "", unpack(lines) } -end - ----@param lines string[] ----@return {row: number, col: number, width: number, height: number} -local function get_position(lines) - local gheight = math.floor( - vim.api.nvim_list_uis() and vim.api.nvim_list_uis()[1] and vim.api.nvim_list_uis()[1].height or vim.o.lines - ) - local gwidth = math.floor( - vim.api.nvim_list_uis() and vim.api.nvim_list_uis()[1] and vim.api.nvim_list_uis()[1].width or vim.o.columns - ) - local height = #lines > 10 and 35 or #lines - local width = 0 - for _, line in ipairs(lines) do - if #line > width then - width = #line - end - end - return { - row = (gheight - height) * 0.5, - col = (gwidth - width) * 0.5, - width = math.floor(width * 1.5), - height = height, - } -end - ----@param tool_call eca.ToolCallRun ----@param on_accept function ----@param on_deny function -function M.display_preview_lines(tool_call, on_accept, on_deny) - local lines = M.get_preview_lines(tool_call) - local buf = vim.api.nvim_create_buf(false, false) - vim.api.nvim_buf_set_lines(buf, 0, -1, false, lines) - vim.api.nvim_set_option_value("modifiable", false, { buf = buf }) - local position = get_position(lines) - local title = tool_call.summary or tool_call.name - local win = vim.api.nvim_open_win(buf, true, { - border = "single", - title = "Approve Tool Call(y/n): " .. title, - relative = "editor", - row = position.row, - col = position.col, - width = position.width, - height = position.height, - }) - if tool_call.details then - vim.api.nvim_set_option_value("filetype", "diff", { buf = buf }) - else - vim.api.nvim_set_option_value("number", false, { win = win }) - vim.api.nvim_set_option_value("relativenumber", false, { win = win }) - end - - vim.keymap.set({ "n", "i" }, "y", "", { - buffer = buf, - callback = function() - vim.api.nvim_win_close(win, true) - vim.api.nvim_buf_delete(buf, { force = true }) - if on_accept then - on_accept() - end - end, - }) - vim.keymap.set({ "n", "i" }, "n", "", { - buffer = buf, - callback = function() - vim.api.nvim_win_close(win, true) - vim.api.nvim_buf_delete(buf, { force = true }) - if on_deny then - on_deny() - end - end, - }) -end - ----@param tool_call eca.ToolCallRun ----@param on_accept function ----@param on_deny function -function M.approve_tool_call(tool_call, on_accept, on_deny) - M.display_preview_lines(tool_call, on_accept, on_deny) -end -return M diff --git a/lua/eca/commands.lua b/lua/eca/commands.lua deleted file mode 100644 index 6e29181..0000000 --- a/lua/eca/commands.lua +++ /dev/null @@ -1,569 +0,0 @@ -local Utils = require("eca.utils") -local Logger = require("eca.logger") -local Picker = require("eca.ui.picker") - -local M = {} - ---- Setup ECA commands -function M.setup() - -- Define ECA commands - vim.api.nvim_create_user_command("EcaChat", function(opts) - require("eca.api").chat(opts.args and { message = opts.args } or {}) - end, { - desc = "Open ECA chat", - nargs = "?", - }) - - vim.api.nvim_create_user_command("EcaToggle", function() - require("eca.api").toggle() - end, { - desc = "Toggle ECA sidebar", - }) - - vim.api.nvim_create_user_command("EcaFocus", function() - require("eca.api").focus() - end, { - desc = "Focus ECA sidebar", - }) - - vim.api.nvim_create_user_command("EcaClose", function() - require("eca.api").close() - end, { - desc = "Close ECA sidebar", - }) - - vim.api.nvim_create_user_command("EcaAddFile", function(opts) - Logger.notify("EcaAddFile is deprecated. Use EcaChatAddFile instead.", vim.log.levels.WARN) - - if opts.args and opts.args ~= "" and type(opts.args) == "string" then - require("eca.api").add_file_context(vim.fn.fnamemodify(opts.args, ":p")) - else - require("eca.api").add_current_file_context() - end - end, { - desc = "Add file as context to ECA", - nargs = "?", - complete = "file", - }) - - vim.api.nvim_create_user_command("EcaChatAddFile", function(opts) - if opts.args and opts.args ~= "" and type(opts.args) == "string" then - require("eca.api").add_file_context(vim.fn.fnamemodify(opts.args, ":p")) - else - require("eca.api").add_current_file_context() - end - end, { - desc = "Add file as context to ECA", - nargs = "?", - complete = "file", - }) - - vim.api.nvim_create_user_command("EcaRemoveContext", function(opts) - Logger.notify("EcaRemoveContext is deprecated. Use EcaChatRemoveFile instead.", vim.log.levels.WARN) - - if opts.args and opts.args ~= "" and type(opts.args) == "string" then - require("eca.api").remove_file_context(vim.fn.fnamemodify(opts.args, ":p")) - else - require("eca.api").remove_current_file_context() - end - end, { - desc = "Remove specific file context from ECA", - nargs = "?", - complete = "file", - }) - - vim.api.nvim_create_user_command("EcaChatRemoveFile", function(opts) - if opts.args and opts.args ~= "" and type(opts.args) == "string" then - require("eca.api").remove_file_context(vim.fn.fnamemodify(opts.args, ":p")) - else - require("eca.api").remove_current_file_context() - end - end, { - desc = "Remove specific file context from ECA", - nargs = "?", - complete = "file", - }) - - vim.api.nvim_create_user_command("EcaAddSelection", function() - Logger.notify("EcaAddSelection is deprecated. Use EcaChatAddSelection instead.", vim.log.levels.WARN) - - -- Force exit visual mode and set marks - vim.cmd("normal! \\") - vim.defer_fn(function() - require("eca.api").add_selection_context() - end, 50) -- Small delay to ensure marks are set - end, { - desc = "Add current selection as context to ECA", - range = true, - }) - - vim.api.nvim_create_user_command("EcaChatAddSelection", function() - -- Force exit visual mode and set marks - vim.cmd("normal! \\") - vim.defer_fn(function() - require("eca.api").add_selection_context() - end, 50) -- Small delay to ensure marks are set - end, { - desc = "Add current selection as context to ECA", - range = true, - }) - - vim.api.nvim_create_user_command("EcaChatAddUrl", function() - vim.ui.input({ prompt = "Enter URL to add as context: " }, function(input) - if not input or input == "" then - return - end - - local url = vim.fn.trim(input) - if url == "" then - return - end - - require("eca.api").add_web_context(url) - end) - end, { - desc = "Add URL as web context to ECA", - }) - - vim.api.nvim_create_user_command("EcaListContexts", function() - Logger.notify("EcaListContexts is deprecated. Use EcaChatListContexts instead.", vim.log.levels.WARN) - - require("eca.api").list_contexts() - end, { - desc = "List active contexts in ECA", - }) - - vim.api.nvim_create_user_command("EcaChatListContexts", function() - require("eca.api").list_contexts() - end, { - desc = "List active contexts in ECA", - }) - - vim.api.nvim_create_user_command("EcaClearContexts", function() - Logger.notify("EcaClearContexts is deprecated. Use EcaChatClearContexts instead.", vim.log.levels.WARN) - - require("eca.api").clear_contexts() - end, { - desc = "Clear all contexts from ECA", - }) - - vim.api.nvim_create_user_command("EcaChatClearContexts", function() - require("eca.api").clear_contexts() - end, { - desc = "Clear all contexts from ECA", - }) - - -- ===== Server Commands ===== - - vim.api.nvim_create_user_command("EcaServerStart", function() - require("eca.api").start_server() - end, { - desc = "Start ECA server", - }) - - vim.api.nvim_create_user_command("EcaServerStop", function() - require("eca.api").stop_server() - end, { - desc = "Stop ECA server", - }) - - vim.api.nvim_create_user_command("EcaServerRestart", function() - require("eca.api").restart_server() - end, { - desc = "Restart ECA server", - }) - - vim.api.nvim_create_user_command("EcaServerMessages", function() - Picker.pick( - { - source = "eca messages", - finder = function(opts, _) - local items = {} - local eca = require("eca") - if not eca or not eca.server then - Logger.notify("ECA plugin is not available", vim.log.levels.ERROR) - return items - end - - -- First pass: collect messages so we can render them with - -- a fixed header width and keep the separator in a constant column. - local entries = {} - - for msg in vim.iter(eca.server.messages) do - local ok, decoded = pcall(vim.json.decode, msg.content) - if ok and type(decoded) == "table" then - local parts = {} - - if msg.direction then - table.insert(parts, string.format("[%s]", tostring(msg.direction))) - end - - if decoded.method then - table.insert(parts, tostring(decoded.method)) - end - - if decoded.id ~= nil then - table.insert(parts, string.format("#%s", tostring(decoded.id))) - end - - local header = table.concat(parts, " ") - local preview_text = vim.inspect(decoded) or "" - - -- Flatten whitespace so searching works on a single line - local flat_preview = "" - if preview_text ~= "" then - flat_preview = preview_text:gsub("%s+", " ") - end - - local json_text = "" - local ok_json, encoded = pcall(vim.json.encode, decoded) - if ok_json and type(encoded) == "string" and encoded ~= "" then - json_text = encoded - end - - table.insert(entries, { - header = header, - flat_preview = flat_preview, - preview_text = preview_text, - json_text = json_text, - id = decoded.id or msg.id, - }) - end - end - - if #entries == 0 then - return items - end - - -- Second pass: build display items with a fixed header width so that - -- the separator and body always start in the same column. - local separator = " | " - local header_width = 40 -- column where the header area ends - - for idx, entry in ipairs(entries) do - local header = entry.header or "" - local preview_text = entry.preview_text or "" - local flat_preview = entry.flat_preview or "" - - -- Truncate overly long headers so the separator stays fixed. - -- - -- NOTE: We truncate to exactly `header_width` characters so that the - -- padding logic below can reliably keep the separator aligned. - local display_header = header - if #display_header > header_width then - display_header = display_header:sub(1, header_width) - end - - -- Pad headers (or empty ones) up to header_width so the - -- first character of the separator is always in the same column. - local padding = math.max(0, header_width - #display_header) - local padded_header = display_header .. string.rep(" ", padding) - - local text = padded_header - if flat_preview ~= "" then - text = padded_header .. separator .. flat_preview - end - - if text == "" then - if preview_text ~= "" then - text = preview_text:gsub("%s+", " ") - elseif entry.json_text and entry.json_text ~= "" then - text = entry.json_text - else - text = "" - end - end - - table.insert(items, { - text = text, - idx = entry.id or idx, - preview = { - text = preview_text, - ft = "lua", - }, - }) - end - - return items - end, - preview = "preview", - format = "text", - confirm = function(self, item, _) - vim.fn.setreg("", item.preview.text) - self:close() - end, - } - ) - end, { - desc = "Display Messages Sent to and Received by ECA server", - }) - - vim.api.nvim_create_user_command("EcaLogs", function(opts) - local Api = require("eca.api") - local subcommand = opts.args and opts.args:match("%S+") or "show" - - if subcommand == "show" then - Api.show_logs() - elseif subcommand == "log_path" then - local log_path = Logger.get_log_path() - Logger.notify("ECA log file: " .. log_path, vim.log.levels.INFO) - elseif subcommand == "clear" then - if Logger.clear_log() then - Logger.notify("ECA log file cleared", vim.log.levels.INFO) - else - Logger.notify("Failed to clear log file", vim.log.levels.WARN) - end - elseif subcommand == "stats" then - local stats = Logger.get_log_stats() - if stats then - Logger.notify(string.format("Log file: %s", stats.path), vim.log.levels.INFO) - Logger.notify(string.format("Size: %.2fMB (%d bytes)", stats.size_mb, stats.size), vim.log.levels.INFO) - Logger.notify(string.format("Last modified: %s", stats.modified), vim.log.levels.INFO) - else - Logger.notify("No log file stats available", vim.log.levels.INFO) - end - else - Logger.notify("Unknown EcaLogs subcommand: " .. subcommand, vim.log.levels.WARN) - Logger.notify("Available subcommands: show, log_path, clear, stats", vim.log.levels.INFO) - end - end, { - desc = "ECA logging commands (show, log_path, clear, stats)", - nargs = "?", - complete = function(ArgLead, CmdLine, CursorPos) - local subcommands = { "show", "log_path", "clear", "stats" } - return vim.tbl_filter(function(cmd) - return cmd:match("^" .. ArgLead) - end, subcommands) - end, - }) - - vim.api.nvim_create_user_command("EcaSend", function(opts) - if opts.args and opts.args ~= "" then - require("eca.api").send_message(opts.args) - else - Logger.notify("Please provide a message to send", vim.log.levels.WARN) - end - end, { - desc = "Send a message to ECA", - nargs = "+", - }) - - vim.api.nvim_create_user_command("EcaDebugWidth", function() - local Config = require("eca.config") - local width = Config.get_window_width() - local columns = vim.o.columns - local percentage = Config.options.windows.width - Logger.notify( - string.format("Width: %d columns (%.1f%% of %d total columns)", width, percentage, columns), - vim.log.levels.INFO - ) - end, { - desc = "Debug window width calculation", - }) - - vim.api.nvim_create_user_command("EcaRedownload", function() - local eca = require("eca") - local Utils = require("eca.utils") - - if eca.server and eca.server:is_running() then - Logger.notify("Stopping server before re-download...", vim.log.levels.INFO) - eca.server:stop() - end - - -- Remove existing version file to force re-download - local cache_dir = Utils.get_cache_dir() - local version_file = cache_dir .. "/eca-version" - os.remove(version_file) - - -- Remove existing binary - local server_binary = cache_dir .. "/eca" - os.remove(server_binary) - - Logger.notify("Removed cached ECA server. Will re-download on next start.", vim.log.levels.INFO) - - -- Restart server - vim.defer_fn(function() - if eca.server then - eca.server:start() - end - end, 1000) - end, { - desc = "Force re-download of ECA server", - }) - - vim.api.nvim_create_user_command("EcaStopResponse", function() - local eca = require("eca") - local chat = eca.get() - local Utils = require("eca.utils") - - -- Force stop any ongoing streaming response - local chat_id = chat.mediator:id() - if chat_id then - chat.mediator:send("chat/promptStop", { chatId = chat_id }, nil) - end - - if eca.sidebar then - eca.sidebar:_finalize_streaming_response() - Logger.notify("Forced stop of streaming response", vim.log.levels.INFO) - else - Logger.notify("No active sidebar to stop", vim.log.levels.WARN) - end - end, { - desc = "Emergency stop for infinite loops or runaway responses", - }) - - vim.api.nvim_create_user_command("EcaFixTreesitter", function() - -- Emergency treesitter fix for chat buffer - vim.schedule(function() - local eca = require("eca") - local sidebar = eca.get() - if sidebar and sidebar.containers and sidebar.containers.chat then - local bufnr = sidebar.containers.chat.bufnr - if bufnr and vim.api.nvim_buf_is_valid(bufnr) then - -- Disable all highlighting for this buffer - pcall(vim.api.nvim_set_option_value, "syntax", "off", { buf = bufnr }) - - -- Destroy treesitter highlighter if it exists - pcall(function() - if vim.treesitter.highlighter.active[bufnr] then - vim.treesitter.highlighter.active[bufnr]:destroy() - vim.treesitter.highlighter.active[bufnr] = nil - end - end) - - Logger.notify("Disabled treesitter highlighting for ECA chat buffer", vim.log.levels.INFO) - Logger.notify("Buffer " .. bufnr .. " highlighting disabled", vim.log.levels.INFO) - else - Logger.notify("No valid chat buffer found", vim.log.levels.WARN) - end - else - Logger.notify("No active ECA sidebar found", vim.log.levels.WARN) - end - end) - end, { - desc = "Emergency fix for treesitter issues in ECA chat", - }) - - vim.api.nvim_create_user_command("EcaChatSelectModel", function() - local eca = require("eca") - local chat = eca.get() - - if not chat or not chat.mediator then - Logger.notify("No active ECA chat found", vim.log.levels.WARN) - return - end - - local models = chat.mediator:models() - - vim.ui.select(models, { - prompt = "Select ECA Chat Model:", - }, function(choice) - if choice then - chat.mediator:update_selected_model(choice) - chat.mediator:send("chat/selectedModelChanged", { model = choice, variant = vim.NIL }, nil) - end - end) - end, { - desc = "Select current ECA Chat model", - }) - - vim.api.nvim_create_user_command("EcaChatSelectBehavior", function() - local eca = require("eca") - local chat = eca.get() - - if not chat or not chat.mediator then - Logger.notify("No active ECA chat found", vim.log.levels.WARN) - return - end - - local behaviors = chat.mediator:behaviors() - - vim.ui.select(behaviors, { - prompt = "Select ECA Chat Behavior:", - }, function(choice) - if choice then - chat.mediator:update_selected_behavior(choice) - end - end) - end, { - desc = "Select current ECA Chat behavior", - }) - - vim.api.nvim_create_user_command("EcaServerTools", function() - Picker.pick( - { - source = "eca tools", - finder = function(_, _) - local items = {} - local eca = require("eca") - if not eca or not eca.state then - Logger.notify("ECA state is not available", vim.log.levels.ERROR) - return items - end - - local tools = eca.state.tools or {} - if not tools or vim.tbl_isempty(tools) then - Logger.notify("No tools registered in server state", vim.log.levels.INFO) - return items - end - - -- Collect and sort tool names for stable ordering - local names = vim.tbl_keys(tools) - table.sort(names) - - for _, name in ipairs(names) do - local tool = tools[name] or {} - - -- Build a human-readable preview string that always includes the - -- tool name and its primary "kind" field (when available), - -- followed by a full vim.inspect dump for debugging. - local preview_text - if next(tool) ~= nil then - local kind_value = tool.kind ~= nil and tostring(tool.kind) or "(unknown)" - preview_text = string.format("name: %s\nkind: %s", name, kind_value) - - local inspected = vim.inspect(tool) - if inspected and inspected ~= "" then - preview_text = preview_text .. "\n" .. inspected - end - else - preview_text = string.format("name: %s\n", name) - end - - table.insert(items, { - text = name, - idx = name, - preview = { - text = preview_text, - ft = "lua", - }, - }) - end - - return items - end, - preview = "preview", - format = "text", - confirm = function(self, item, _) - vim.fn.setreg("", item.preview.text) - self:close() - end, - } - ) - end, { - desc = "Display ECA server tools (yank preview on confirm)", - }) - - vim.api.nvim_create_user_command("EcaChatClear", function() - local sidebar = require("eca").get() - if sidebar then - sidebar:clear_chat() - end - end, { - desc = "Clear ECA chat buffer", - }) - - Logger.debug("ECA commands registered") -end - -return M diff --git a/lua/eca/completion/blink/commands.lua b/lua/eca/completion/blink/commands.lua deleted file mode 100644 index 579e199..0000000 --- a/lua/eca/completion/blink/commands.lua +++ /dev/null @@ -1,49 +0,0 @@ -local source = {} - --- `opts` table comes from `sources.providers.your_provider.opts` --- You may also accept a second argument `config`, to get the full --- `sources.providers.your_provider` table -function source.new(opts) - -- vim.validate("your-source.opts.some_option", opts.some_option, { "string" }) - -- vim.validate("your-source.opts.optional_option", opts.optional_option, { "string" }, true) - - local self = setmetatable({}, { __index = source }) - self.opts = opts - return self -end - -function source:enabled() - return vim.bo.filetype == "eca-input" -end - ----@return lsp.CompletionItem ----@param command eca.ChatCommand -local function as_completion_item(command) - ---@type lsp.CompletionItem - return { - label = command.name, - detail = command.description or ("ECA command: " .. command.name), - documentation = command.help and { - kind = "markdown", - value = command.help, - } or nil, - } -end - --- (Optional) Non-alphanumeric characters that trigger the source -function source:get_trigger_characters() - return { "/" } -end - ----@module 'blink.cmp' ----@param ctx blink.cmp.Context ----@param callback fun(response?: blink.cmp.CompletionResponse) -function source:get_completions(ctx, callback) - local commands = require("eca.completion.commands") - local q = commands.get_query(ctx.line) - if q then - commands.get_completion_candidates(q, as_completion_item, callback) - end -end - -return source diff --git a/lua/eca/completion/blink/context.lua b/lua/eca/completion/blink/context.lua deleted file mode 100644 index 0b25809..0000000 --- a/lua/eca/completion/blink/context.lua +++ /dev/null @@ -1,83 +0,0 @@ ----@module 'blink.cmp' ----@class blink.cmp.Source -local source = {} - --- `opts` table comes from `sources.providers.your_provider.opts` --- You may also accept a second argument `config`, to get the full --- `sources.providers.your_provider` table -function source.new(opts) - -- vim.validate("your-source.opts.some_option", opts.some_option, { "string" }) - -- vim.validate("your-source.opts.optional_option", opts.optional_option, { "string" }, true) - - local self = setmetatable({}, { __index = source }) - self.opts = opts - return self -end - -function source:enabled() - return vim.bo.filetype == "eca-input" -end - --- (Optional) Non-alphanumeric characters that trigger the source -function source:get_trigger_characters() - return { "@", "#" } -end - ----@param context eca.ChatContext ----@return lsp.CompletionItem -local function as_completion_item(context) - local kinds = require("blink.cmp.types").CompletionItemKind - ---@type lsp.CompletionItem - ---@diagnostic disable-next-line: missing-fields - local item = {} - if context.type == "file" then - item.label = vim.fn.fnamemodify(context.path, ":.") - item.kind = kinds.File - item.data = { - context_item = context, - } - elseif context.type == "directory" then - item.label = vim.fn.fnamemodify(context.path, ":.") - item.kind = kinds.Folder - elseif context.type == "web" then - item.label = context.url - item.kind = kinds.File - elseif context.type == "repoMap" then - item.label = "repoMap" - item.kind = kinds.Module - item.detail = "Summary view of workspace files." - elseif context.type == "mcpResource" then - item.label = string.format("%s:%s", context.server, context.name) - item.kind = kinds.Struct - item.detail = context.description - end - if not item.label then - return {} - end - return item -end - ----@param ctx blink.cmp.Context ----@param callback fun(response?: blink.cmp.CompletionResponse) -function source:get_completions(ctx, callback) - local context = require("eca.completion.context") - local query = context.get_query(ctx.line, ctx.cursor) - if query then - context.get_completion_candidates(query, as_completion_item, callback) - end -end - ----@param item lsp.CompletionItem ----@param callback fun(any) -function source:resolve(item, callback) - require("eca.completion.context").resolve_completion_item(item, callback) -end - ----Executed after the item was selected ----@param item lsp.CompletionItem ----@param callback fun(any) -function source:execute(item, callback) - require("eca.completion.context").execute(item, callback) -end - -return source diff --git a/lua/eca/completion/cmp/commands.lua b/lua/eca/completion/cmp/commands.lua deleted file mode 100644 index 1247c7c..0000000 --- a/lua/eca/completion/cmp/commands.lua +++ /dev/null @@ -1,40 +0,0 @@ ----@param command eca.ChatCommand ----@return lsp.CompletionItem -local function as_completion_item(command) - local cmp = require("cmp") - ---@type lsp.CompletionItem - return { - label = command.name, - kind = cmp.lsp.CompletionItemKind.Function, - detail = command.description or ("ECA command: " .. command.name), - documentation = command.help and { - kind = "markdown", - value = command.help, - } or nil, - } -end - -local source = {} - -source.new = function() - return setmetatable({ cache = {} }, { __index = source }) -end - -function source:get_trigger_characters() - return { "/" } -end - -function source:is_available() - return vim.bo.filetype == "eca-input" -end - ----@diagnostic disable-next-line: unused-local -function source:complete(params, callback) - -- Only complete if we're typing a command (starts with /) - local commands = require("eca.completion.commands") - local query = commands.get_query(params.context.cursor_line) - if query then - commands.get_completion_candidates(query, as_completion_item, callback) - end -end -return source diff --git a/lua/eca/completion/cmp/context.lua b/lua/eca/completion/cmp/context.lua deleted file mode 100644 index c27349e..0000000 --- a/lua/eca/completion/cmp/context.lua +++ /dev/null @@ -1,76 +0,0 @@ -local cmp = require("cmp") ----@module 'cmp' ----@param context eca.ChatContext ----@return cmp.CompletionItem -local function as_completion_item(context) - ---@type lsp.CompletionItem - ---@diagnostic disable-next-line: missing-fields - local item = {} - if context.type == "file" then - item.label = vim.fn.fnamemodify(context.path, ":.") - item.kind = cmp.lsp.CompletionItemKind.File - item.data = { - context_item = context, - } - elseif context.type == "directory" then - item.label = vim.fn.fnamemodify(context.path, ":.") - item.kind = cmp.lsp.CompletionItemKind.Folder - elseif context.type == "web" then - item.label = context.url - item.kind = cmp.lsp.CompletionItemKind.File - elseif context.type == "repoMap" then - item.label = "repoMap" - item.kind = cmp.lsp.CompletionItemKind.Module - item.detail = "Summary view of workspace files." - elseif context.type == "mcpResource" then - item.label = string.format("%s:%s", context.server, context.name) - item.kind = cmp.lsp.CompletionItemKind.Struct - item.detail = context.description - end - if not item.label then - return {} - end - return item -end - -local source = {} - -function source.new() - return setmetatable({}, { __index = source }) -end - -function source:get_trigger_characters() - return { "@", "#" } -end - -function source:get_keyword_pattern() - return [[\k\+]] -end - -function source:is_available() - return vim.bo.filetype == "eca-input" -end - ----@param params cmp.SourceCompletionApiParams ----@diagnostic disable-next-line: unused-local -function source:complete(params, callback) - local context = require("eca.completion.context") - local query = context.get_query(params.context.cursor_line, params.context.cursor) - if query then - context.get_completion_candidates(query, as_completion_item, callback) - end -end - ----@param completion_item lsp.CompletionItem -function source:resolve(completion_item, callback) - require("eca.completion.context").resolve_completion_item(completion_item, callback) -end - ----Executed after the item was selected. ----@param completion_item lsp.CompletionItem ----@param callback fun(completion_item: lsp.CompletionItem|nil) -function source:execute(completion_item, callback) - require("eca.completion.context").execute(completion_item, callback) -end - -return source diff --git a/lua/eca/completion/commands.lua b/lua/eca/completion/commands.lua deleted file mode 100644 index 1e8c864..0000000 --- a/lua/eca/completion/commands.lua +++ /dev/null @@ -1,40 +0,0 @@ -local M = {} - ----@param s string ----@return string? -function M.get_query(s) - return s:match("^>?%s*/(.*)$") -- Cursor character followed by slash -end - ----@param query string ----@param as_completion_item fun(eca.ChatCommand): lsp.CompletionItem ----@param callback fun(resp: {items: lsp.CompletionItem[], isIncomplete?: boolean, is_incomplete_forward?: boolean, is_incomplete_backward?: boolean}) -function M.get_completion_candidates(query, as_completion_item, callback) - local eca = require("eca") - local chat = eca.get() - - if not chat or not chat.mediator then - Logger.notify("No active ECA sidebar", vim.log.levels.WARN) - return - end - - chat.mediator:send("chat/queryCommands", { - chatId = chat.mediator:id(), - query = query, - }, - function(err, result) - if err then - ---@diagnostic disable-next-line: missing-fields - callback({ items = {} }) - end - - if result and result.commands then - local items = vim.iter(result.commands):map(as_completion_item):totable() - callback({ items = items }) - else - callback({ items = {} }) - end - end) -end - -return M diff --git a/lua/eca/completion/context.lua b/lua/eca/completion/context.lua deleted file mode 100644 index 538a0e3..0000000 --- a/lua/eca/completion/context.lua +++ /dev/null @@ -1,113 +0,0 @@ -local M = {} - ----@param cursor_line string ----@param cursor_position lsp.Position|vim.Position ----@return string -function M.get_query(cursor_line, cursor_position) - local before_cursor = cursor_line:sub(1, cursor_position.col) - ---@type string[] - local matches = {} - local it = before_cursor:gmatch("[@#]([%w%./_\\%-~]*)") - for match in it do - table.insert(matches, match) - end - return matches[#matches] -end - ----@param query string ----@param as_completion_item fun(eca.ChatContext): lsp.CompletionItem ----@param callback fun(resp: {items: lsp.CompletionItem[], isIncomplete?: boolean, is_incomplete_forward?: boolean, is_incomplete_backward?: boolean}) -function M.get_completion_candidates(query, as_completion_item, callback) - local eca = require("eca") - local chat = eca.get() - - if not chat or not chat.mediator then - Logger.notify("No active ECA sidebar", vim.log.levels.WARN) - return - end - - chat.mediator:send("chat/queryContext", { - chatId = chat.mediator:id(), - query = query, - contexts = chat.mediator:contexts() or {}, - }, - function(err, result) - if err then - callback({ items = {} }) - return - end - - if result and result.contexts then - local items = vim.iter(result.contexts):map(as_completion_item):totable() - callback({ items = items }) - else - callback({ items = {} }) - end - end) -end - ---- Taken from https://github.com/hrsh7th/cmp-path/blob/9a16c8e5d0be845f1d1b64a0331b155a9fe6db4d/lua/cmp_path/init.lua ---- Show a small preview of file context items in the documentation window. ----@param context_item eca.ChatContext ----@param max_lines integer ----@return lsp.MarkupContent -local function documentation(context_item, max_lines) - if context_item and context_item.path then - local filename = context_item.path - local binary = assert(io.open(context_item.path, "rb")) - local first_kb = binary:read(1024) - if first_kb and first_kb:find("\0") then - return { kind = vim.lsp.protocol.MarkupKind.PlainText, value = "binary file" } - end - - local content = io.lines(context_item.path) - - --- Try to support line ranges, I don't know if this works or not yet - local start = context_item.lines_range and context_item.lines_range.start or 1 - local last = context_item.lines_range and context_item.lines_range["end"] or max_lines - local skip_lines = start - 1 - local take_lines = last - start - local contents = vim.iter(content):skip(skip_lines):take(take_lines):totable() - - local filetype = vim.filetype.match({ filename = filename }) - if not filetype then - return { kind = vim.lsp.protocol.MarkupKind.PlainText, value = table.concat(contents, "\n") } - end - - table.insert(contents, 1, "```" .. filetype) - table.insert(contents, "```") - return { kind = vim.lsp.protocol.MarkupKind.Markdown, value = table.concat(contents, "\n") } - end - return {} -end - ----@param completion_item lsp.CompletionItem ----@param callback fun(any) -function M.resolve_completion_item(completion_item, callback) - if completion_item.data then - local context_item = completion_item.data.context_item - ---@cast context_item eca.ChatContext - if context_item.type == "file" then - completion_item.documentation = documentation(context_item, 20) - end - callback(completion_item) - end -end - ----Executed after the item was selected ----@param completion_item lsp.CompletionItem ----@param callback fun(any) -function M.execute(completion_item, callback) - if completion_item.data then - vim.api.nvim_exec_autocmds("User", { - pattern = { "CompletionItemSelected" }, - data = { - context_item = completion_item.data.context_item, - label = completion_item.label, - } - }) - callback(completion_item) - end -end - -return M diff --git a/lua/eca/config.lua b/lua/eca/config.lua deleted file mode 100644 index e1fe494..0000000 --- a/lua/eca/config.lua +++ /dev/null @@ -1,132 +0,0 @@ ----@class eca.Config -local M = {} - ----@class eca.Config -M._defaults = { - server_path = "", -- Path to the ECA binary, will download automatically if empty - server_args = "", -- Extra args for the eca start command - log = { - display = "split", - level = vim.log.levels.INFO, - file = "", - max_file_size_mb = 10, -- Maximum log file size in MB before warning - }, - behavior = { - auto_set_keymaps = true, - auto_focus_sidebar = true, - auto_start_server = false, -- Automatically start server on setup - auto_download = true, -- Automatically download server if not found - show_status_updates = true, -- Show status updates in notifications - preserve_chat_history = false, -- When true, chat history is preserved across sidebar open/close cycles - }, - context = { - auto_repo_map = true, -- Automatically add repoMap context when starting new chat - }, - mappings = { - chat = "ec", - focus = "ef", - toggle = "et", - -- Chat input submit keys (per-mode). Always bound regardless of `behavior.auto_set_keymaps`, - -- since the input window is unusable without a way to send. - submit = { - normal = "", - insert = "", - }, - }, - windows = { - wrap = true, - width = 40, -- Window width as percentage (40 = 40% of screen width) - sidebar_header = { - enabled = true, - align = "center", - rounded = true, - }, - input = { - prefix = "> ", - height = 8, -- Height of the input window - web_context_max_len = 20, -- Maximum length for web context names in input - }, - edit = { - border = "rounded", - start_insert = true, -- Start insert mode when opening the edit window - }, - usage = { - --- Supported placeholders: - --- {session_tokens} - raw session token count (e.g. "30376") - --- {limit_tokens} - raw token limit (e.g. "400000") - --- {session_tokens_short} - shortened session tokens (e.g. "30k") - --- {limit_tokens_short} - shortened token limit (e.g. "400k") - --- {session_cost} - session cost (e.g. "0.09") - --- Default: "30k / 400k ($0.09)" -> "{session_tokens_short} / {limit_tokens_short} (${session_cost})" - format = "{session_tokens_short} / {limit_tokens_short} (${session_cost})", - }, - chat = { - headers = { - user = "> ", - assistant = "", - }, - welcome = { - message = "", -- If non-empty, overrides server-provided welcome message - tips = { - -- Available placeholders: {submit_key_normal}, {submit_key_insert} - "Type your message and press {submit_key_insert} to send", -- Tips appended under the welcome (set empty list {} to disable) - }, - }, - typing = { - enabled = true, -- Enable typewriter effect for streaming responses - chars_per_tick = 1, -- Number of characters to display per tick (1 = realistic typing) - tick_delay = 10, -- Delay in milliseconds between ticks (lower = faster) - }, - tool_call = { - icons = { - success = "✅", -- Shown when a tool call succeeds - error = "❌", -- Shown when a tool call fails - running = "⏳", -- Shown while a tool call is running / has no final status yet - expanded = "▼", -- Arrow when the tool call details are expanded - collapsed = "▶", -- Arrow when the tool call details are collapsed - }, - diff = { - collapsed_label = "+ view diff", -- Label when the diff is collapsed - expanded_label = "- view diff", -- Label when the diff is expanded - expanded = false, -- When true, tool diffs start expanded - }, - preserve_cursor = true, -- When true, cursor position is preserved when expanding/collapsing - }, - reasoning = { - expanded = false, -- When true, "Thinking" blocks start expanded - running_label = "Thinking...", -- Label while reasoning is running - finished_label = "Thought", -- Base label when reasoning is finished - }, - }, - }, -} - ----@type eca.Config -M.options = M._defaults - ----@param opts eca.Config -function M.setup(opts) - M.options = vim.tbl_deep_extend("force", M._defaults, opts or {}) -end - ----@param override eca.Config -function M.override(override) - M.options = vim.tbl_deep_extend("force", M.options, override) -end - -function M.get_window_width() - return math.ceil(vim.o.columns * (M.options.windows.width / 100)) -end - -function M.get_input_height() - return M.options.windows.input.height -end - -return setmetatable(M, { - __index = function(_, k) - if M.options[k] ~= nil then - return M.options[k] - end - return M._defaults[k] - end, -}) diff --git a/lua/eca/editor.lua b/lua/eca/editor.lua deleted file mode 100644 index 87496e1..0000000 --- a/lua/eca/editor.lua +++ /dev/null @@ -1,45 +0,0 @@ -local M = {} - -local SEVERITY = { - [vim.diagnostic.severity.ERROR] = "error", - [vim.diagnostic.severity.WARN] = "warning", - [vim.diagnostic.severity.INFO] = "information", - [vim.diagnostic.severity.HINT] = "hint", -} - -local function uri_to_bufnr(uri) - if not uri or uri == "" then return -1 end - local path = vim.uri_to_fname(uri) - return vim.fn.bufnr(path) -end - -local function get_diagnostics(params) - local uri = params.uri - local bufnr = uri_to_bufnr(uri) - if bufnr == -1 then return { diagnostics = {} } end - local raw = vim.diagnostic.get(bufnr) - local diags = {} - for _, d in ipairs(raw) do - table.insert(diags, { - uri = uri, - message = d.message, - severity = SEVERITY[d.severity] or "information", - range = { - start = { line = d.lnum, character = d.col }, - ["end"] = { line = d.end_lnum or d.lnum, character = d.end_col or d.col }, - }, - source = d.source, - code = d.code, - }) - end - return { diagnostics = diags } -end - -function M.handle_request(message) - if message.method == "editor/getDiagnostics" then - return get_diagnostics(message.params or {}) - end - return nil -end - -return M diff --git a/lua/eca/highlights.lua b/lua/eca/highlights.lua deleted file mode 100644 index 7377be7..0000000 --- a/lua/eca/highlights.lua +++ /dev/null @@ -1,20 +0,0 @@ -local M = {} - -function M.setup() - -- Define highlight groups for ECA - vim.api.nvim_set_hl(0, "EcaTitle", { fg = "#7aa2f7", bold = true }) - vim.api.nvim_set_hl(0, "EcaUserMessage", { fg = "#9ece6a", bold = true }) - vim.api.nvim_set_hl(0, "EcaAssistantMessage", { fg = "#7dcfff", bold = true }) - vim.api.nvim_set_hl(0, "EcaPrompt", { fg = "#f7768e", bold = true }) - vim.api.nvim_set_hl(0, "EcaCode", { fg = "#bb9af7" }) - vim.api.nvim_set_hl(0, "EcaSeparator", { fg = "#414868" }) - vim.api.nvim_set_hl(0, "EcaError", { fg = "#f7768e", bg = "#3d2b2e" }) - vim.api.nvim_set_hl(0, "EcaSuccess", { fg = "#9ece6a", bg = "#2b3b2e" }) - vim.api.nvim_set_hl(0, "EcaWarning", { fg = "#e0af68", bg = "#3d3a2b" }) - vim.api.nvim_set_hl(0, "EcaInfo", { fg = "#7dcfff", bg = "#2b3a3d" }) - vim.api.nvim_set_hl(0, "EcaToolCall", { link = "Title" }) - vim.api.nvim_set_hl(0, "EcaHyperlink", { link = "Underlined", underline = true }) - vim.api.nvim_set_hl(0, "EcaLabel", { link = "Comment" }) -end - -return M diff --git a/lua/eca/init.lua b/lua/eca/init.lua index 558cf78..ed605a4 100644 --- a/lua/eca/init.lua +++ b/lua/eca/init.lua @@ -1,258 +1,8 @@ ----@diagnostic disable: undefined-global -local api = vim.api - -local Utils = require("eca.utils") -local Logger = require("eca.logger") -local Sidebar = require("eca.sidebar") -local Config = require("eca.config") -local Server = require("eca.server") - ----@class Eca -local M = { - ---@type eca.Sidebar[] we use this to track chat command across tabs - sidebars = {}, - ---@type {sidebar?: eca.Sidebar} - current = { sidebar = nil }, - ---@type eca.Server - server = nil, -} - -M.did_setup = false - -local H = {} - -function H.keymaps() - vim.keymap.set({ "n", "v" }, "(EcaChat)", function() - require("eca.api").chat() - end, { noremap = true }) - vim.keymap.set("n", "(EcaToggle)", function() - M.toggle() - end, { noremap = true }) - vim.keymap.set("n", "(EcaFocus)", function() - require("eca.api").focus() - end, { noremap = true }) - - if Config.behavior and Config.behavior.auto_set_keymaps then - Utils.safe_keymap_set({ "n", "v" }, Config.mappings.chat, function() - require("eca.api").chat() - end, { desc = "eca: open chat" }) - Utils.safe_keymap_set("n", Config.mappings.focus, function() - require("eca.api").focus() - end, { desc = "eca: focus" }) - Utils.safe_keymap_set("n", Config.mappings.toggle, function() - M.toggle() - end, { desc = "eca: toggle" }) - end -end - -function H.signs() - vim.fn.sign_define("EcaInputPromptSign", { text = Config.windows.input.prefix }) -end - -H.augroup = api.nvim_create_augroup("eca_autocmds", { clear = true }) - -function H.autocmds() - api.nvim_create_autocmd("TabEnter", { - group = H.augroup, - pattern = "*", - once = true, - callback = function(ev) - local tab = tonumber(ev.file) - M._init(tab or api.nvim_get_current_tabpage()) - end, - }) - - api.nvim_create_autocmd("VimResized", { - group = H.augroup, - callback = function() - local sidebar = M.get() - if not sidebar then - return - end - if not sidebar:is_open() then - return - end - sidebar:resize() - end, - }) - - api.nvim_create_autocmd("QuitPre", { - group = H.augroup, - callback = function() - local current_buf = vim.api.nvim_get_current_buf() - if Utils.is_sidebar_buffer(current_buf) then - return - end - - local non_sidebar_wins = 0 - local sidebar_wins = {} - for _, win in ipairs(vim.api.nvim_list_wins()) do - if vim.api.nvim_win_is_valid(win) then - local win_buf = vim.api.nvim_win_get_buf(win) - if Utils.is_sidebar_buffer(win_buf) then - table.insert(sidebar_wins, win) - else - non_sidebar_wins = non_sidebar_wins + 1 - end - end - end - - if non_sidebar_wins <= 1 then - for _, win in ipairs(sidebar_wins) do - pcall(vim.api.nvim_win_close, win, false) - end - end - end, - nested = true, - }) - - api.nvim_create_autocmd("TabClosed", { - group = H.augroup, - pattern = "*", - callback = function(ev) - local tab = tonumber(ev.file) - local s = M.sidebars[tab] - if s then - s:reset() - end - if tab ~= nil then - M.sidebars[tab] = nil - end - end, - }) - - vim.schedule(function() - M._init(api.nvim_get_current_tabpage()) - end) - - local function setup_colors() - Logger.debug("Setting up eca colors") - require("eca.highlights").setup() - end - - api.nvim_create_autocmd("ColorSchemePre", { - group = H.augroup, - callback = function() - vim.schedule(function() - setup_colors() - end) - end, - }) - - api.nvim_create_autocmd("ColorScheme", { - group = H.augroup, - callback = function() - vim.schedule(function() - setup_colors() - end) - end, - }) - - -- automatically setup Eca filetype to markdown - vim.treesitter.language.register("markdown", "Eca") -end - ----@param current boolean? false to disable setting current, otherwise use this to track across tabs. ----@return eca.Sidebar -function M.get(current) - local tab = api.nvim_get_current_tabpage() - local sidebar = M.sidebars[tab] - if current ~= false then - M.current.sidebar = sidebar - end - return sidebar -end - ----@param id integer -function M._init(id) - local sidebar = M.sidebars[id] - - if not sidebar then - sidebar = Sidebar.new(id, M.mediator) - M.sidebars[id] = sidebar - end - M.current = { sidebar = sidebar } - return M -end - -M.toggle = { api = true } - ----@param opts? table -function M.toggle_sidebar(opts) - opts = opts or {} - - local sidebar = M.get() - if not sidebar then - M._init(api.nvim_get_current_tabpage()) - M.current.sidebar:open(opts) - return true - end - - return sidebar:toggle(opts) -end - -function M.is_sidebar_open() - local sidebar = M.get() - if not sidebar then - return false - end - return sidebar:is_open() -end - ----@param opts? table -function M.open_sidebar(opts) - opts = opts or {} - local sidebar = M.get() - if not sidebar then - M._init(api.nvim_get_current_tabpage()) - end - M.current.sidebar:open(opts) -end - -function M.close_sidebar() - local sidebar = M.get() - if not sidebar then - return - end - sidebar:close() -end - -setmetatable(M.toggle, { - __index = M.toggle, - __call = function() - M.toggle_sidebar() - end, -}) - ----@param opts? eca.Config -function M.setup(opts) - Config.setup(opts or {}) - - if M.did_setup then - return - end - - require("eca.logger").setup(Config.options.log) - require("eca.highlights").setup() - require("eca.commands").setup() - - -- setup helpers - H.autocmds() - H.keymaps() - H.signs() - - -- Initialize the ECA server with callbacks - M.state = require("eca.state").new() - M.server = Server.new() - M.mediator = require("eca.mediator").new(M.server, M.state) - - if Config.behavior and Config.behavior.auto_start_server then - vim.defer_fn(function() - M.server:start() - end, 100) -- Small delay to ensure everything is loaded - end - - M.did_setup = true -end - -return M +-- [nfnl] fnl/eca/init.fnl +local _local_1_ = require("eca.nfnl.module") +local autoload = _local_1_.autoload +local notify = autoload("eca.nfnl.notify") +local function setup() + return notify.info("Hello, World!") +end +return {setup = setup} diff --git a/lua/eca/logger.lua b/lua/eca/logger.lua deleted file mode 100644 index 2171d3d..0000000 --- a/lua/eca/logger.lua +++ /dev/null @@ -1,198 +0,0 @@ -local uv = vim.uv or vim.loop - ----@class eca.Logger -local M = {} - ----@type eca.LogConfig -M.config = nil - -local LEVEL_NAMES = { - [vim.log.levels.TRACE] = "TRACE", - [vim.log.levels.DEBUG] = "DEBUG", - [vim.log.levels.INFO] = "INFO", - [vim.log.levels.WARN] = "WARN", - [vim.log.levels.ERROR] = "ERROR", -} - ----Get XDG-compliant default log path ----@return string -local function get_default_log_path() - return vim.fn.stdpath("state") .. "/eca.log" -end - ----@type eca.LogConfig -local DEFAULT_CONFIG = { - level = vim.log.levels.INFO, - file = get_default_log_path(), - display = "split", - max_file_size_mb = 10, -} - ----Get log level name ----@param level integer ----@return string -local function get_level_name(level) - return LEVEL_NAMES[level] or "UNKNOWN" -end - ----Check if log file is over size limit and notify if needed ----@param log_path string ----@param max_size_mb number -local function check_log_size_and_notify(log_path, max_size_mb) - uv.fs_stat(log_path, function(err, stat) - if err or not stat then - return - end - - local max_size = max_size_mb * 1024 * 1024 -- Convert MB to bytes - if stat.size > max_size then - local size_mb = math.floor(stat.size / 1024 / 1024 * 100) / 100 - vim.notify( - string.format("ECA log file is large (%.1fMB). Consider clearing it with :EcaLogs clear", size_mb), - vim.log.levels.WARN, - { title = "ECA" } - ) - end - end) -end - ---- Initialize logger with configuration ----@param config eca.LogConfig -function M.setup(config) - config = config or {} - local strings = require("eca.strings") - - M.config = { - level = config.level or DEFAULT_CONFIG.level, - file = strings.is_nil_or_empty(config.file) and DEFAULT_CONFIG.file or config.file, - display = config.display or DEFAULT_CONFIG.display, - max_file_size_mb = config.max_file_size_mb or DEFAULT_CONFIG.max_file_size_mb, - } - - local log_path = M.get_log_path() - check_log_size_and_notify(log_path, M.config.max_file_size_mb) -end - ----@return string -function M.get_display() - return M.config and M.config.display or "split" -end - ---- Get current log file path ----@return string -function M.get_log_path() - assert(M.config and M.config.file ~= "", "Logger must be configured with a non-empty file path") - return vim.fn.expand(M.config.file) -end - ---- Log a message to the log file ----@param message string ----@param level integer -function M.log(message, level) - if vim.in_fast_event() then - return vim.schedule(function() - M.log(message, level) - end) - end - - if not M.config then - return - end - - if level < M.config.level then - return - end - - local log_path = M.get_log_path() - - vim.fn.mkdir(vim.fn.fnamemodify(log_path, ":h"), "p") - - local timestamp = os.date("%Y-%m-%d %H:%M:%S") - local level_name = get_level_name(level) - local formatted = string.format("[%s] %-5s %s\n", timestamp, level_name, message) - - uv.fs_open(log_path, "a", 420, function(err, fd) - if err or not fd then - return - end - uv.fs_write(fd, formatted, -1, function() - uv.fs_close(fd) - end) - end) -end - ---- Log debug message ----@param message string -function M.debug(message) - M.log(message, vim.log.levels.DEBUG) -end - ---- Log info message ----@param message string -function M.info(message) - M.log(message, vim.log.levels.INFO) -end - ---- Log warn message ----@param message string -function M.warn(message) - M.log(message, vim.log.levels.WARN) -end - ---- Log error message ----@param message string -function M.error(message) - M.log(message, vim.log.levels.ERROR) -end - ---- Send notification to user via vim.notify ----@param message string ----@param level? integer vim.log.levels (default: INFO) ----@param opts? {title?: string} -function M.notify(message, level, opts) - if vim.in_fast_event() then - return vim.schedule(function() - M.notify(message, level, opts) - end) - end - - level = level or vim.log.levels.INFO - opts = opts or {} - - M.log(message, level) - - vim.notify(message, level, { - title = opts.title or "ECA", - }) -end - ---- Get log file statistics ----@return table|nil -function M.get_log_stats() - local log_path = M.get_log_path() - local stat = uv.fs_stat(log_path) - if not stat then - return nil - end - - return { - path = log_path, - size = stat.size, - size_mb = math.floor(stat.size / 1024 / 1024 * 100) / 100, - modified = os.date("%Y-%m-%d %H:%M:%S", stat.mtime.sec), - } -end - ---- Clear log file ----@return boolean -function M.clear_log() - local log_path = M.get_log_path() - local file = io.open(log_path, "w") - if file then - file:close() - return true - end - return false -end - -return M diff --git a/lua/eca/mediator.lua b/lua/eca/mediator.lua deleted file mode 100644 index 5816e48..0000000 --- a/lua/eca/mediator.lua +++ /dev/null @@ -1,222 +0,0 @@ ----@class eca.Mediator ----@field server eca.Server ----@field state eca.State -local mediator = {} - ----@param server eca.Server ----@param state eca.State ----@return eca.Mediator -function mediator.new(server, state) - return setmetatable({ - server = server, - state = state, - }, { __index = mediator }) -end - -local function context_adapter(context) - if not context or not context.type or not context.data then - return nil - end - - local function is_pos(p) - return type(p) == "table" and type(p.line) == "number" and type(p.character) == "number" - end - - local adapters = { - cursor = function(ctx) - local d = ctx.data - - if type(d.path) ~= "string" or type(d.position) ~= "table" then - return nil - end - - local start_src = d.position.position_start - local end_src = d.position.position_end - - if not (is_pos(start_src) and is_pos(end_src)) then - return nil - end - - return { - type = ctx.type, - path = d.path, - position = { - start = { - line = start_src.line, - character = start_src.character, - }, - ["end"] = { - line = end_src.line, - character = end_src.character, - }, - }, - } - end, - directory = function(ctx) - if type(ctx.data.path) ~= "string" then - return nil - end - return { - type = ctx.type, - path = ctx.data.path, - } - end, - file = function(ctx) - local d = ctx.data - if type(d.path) ~= "string" then - return nil - end - local linesRange = nil - if type(d.lines_range) == "table" and type(d.lines_range.line_start) == "number" and type(d.lines_range.line_end) == "number" then - linesRange = { - start = d.lines_range.line_start, - ["end"] = d.lines_range.line_end, - } - end - - return { - type = ctx.type, - path = d.path, - linesRange = linesRange, - } - end, - web = function(ctx) - if type(ctx.data.path) ~= "string" then - return nil - end - return { - type = ctx.type, - url = ctx.data.path, - } - end, - } - - local adapter = adapters[context.type] - - if not adapter then - return nil - end - - return adapter(context) -end - ----@param method string ----@param params eca.MessageParams ----@param callback? fun(err?: string, result?: table) -function mediator:send(method, params, callback) - if not self.server:is_running() then - if callback then - callback("Server is not running, please start the server", nil) - end - require("eca.logger").notify("Server is not running, please start the server", vim.log.levels.WARN) - end - - if params.contexts then - local contexts = {} - - for _, context in pairs(params.contexts) do - local adapted = context_adapter(context) - if adapted then - table.insert(contexts, adapted) - end - end - - params.contexts = contexts - end - - self.server:send_request(method, params, callback) -end - -function mediator:behaviors() - return self.state.config.behaviors.list -end - -function mediator:selected_behavior() - return self.state.config.behaviors.selected -end - -function mediator:update_selected_behavior(behavior) - self.state:update_selected_behavior(behavior) -end - -function mediator:models() - return self.state.config.models.list -end - -function mediator:selected_model() - return self.state.config.models.selected -end - -function mediator:update_selected_model(model) - self.state:update_selected_model(model) -end - -function mediator:tokens_session() - return self.state.usage.tokens.session -end - -function mediator:tokens_limit() - return self.state.usage.tokens.limit -end - -function mediator:costs_session() - return self.state.usage.costs.session -end - -function mediator:status_state() - return self.state.status.state -end - -function mediator:status_text() - return self.state.status.text -end - -function mediator:welcome_message() - return (self.state and self.state.config and self.state.config.welcome_message) or nil -end - -function mediator:mcps() - local mcps = {} - - for _, tool in pairs(self.state.tools) do - if tool.type == "mcp" then - table.insert(mcps, tool) - end - end - - return mcps -end - -function mediator:id() - return self.state and self.state.id -end - -function mediator:contexts() - return self.state and self.state.contexts -end - -function mediator:add_context(context) - if not self.state then - return - end - - self.state:add_context(context) -end - -function mediator:remove_context(context) - if not self.state then - return - end - - self.state:remove_context(context) -end - -function mediator:clear_contexts() - if not self.state then - return - end - - self.state:clear_contexts() -end - -return mediator diff --git a/lua/eca/message_handler.lua b/lua/eca/message_handler.lua deleted file mode 100644 index 9a9d21a..0000000 --- a/lua/eca/message_handler.lua +++ /dev/null @@ -1,21 +0,0 @@ -local M = {} - ---- Parse raw messages coming from the ECA server ----@param data string ----@return {content_length: integer, content: string}[] -function M.parse_raw_messages(data) - local messages = {} - local seek_head = 1 - while true do - local first, last, capture = string.find(data, "Content%-Length: (%d+)[\r\n]+", seek_head) - if not first then - break - end - capture = tonumber(capture) - seek_head = last + capture - table.insert(messages, { content_length = capture, content = string.sub(data, last + 1, seek_head) }) - end - return messages -end - -return M diff --git a/lua/eca/nfnl/api.lua b/lua/eca/nfnl/api.lua new file mode 100644 index 0000000..68f1eb2 --- /dev/null +++ b/lua/eca/nfnl/api.lua @@ -0,0 +1,111 @@ +-- [nfnl] fnl/nfnl/api.fnl +local _local_1_ = require("eca.nfnl.module") +local autoload = _local_1_.autoload +local define = _local_1_.define +local core = autoload("eca.nfnl.core") +local str = autoload("eca.nfnl.string") +local compile = autoload("eca.nfnl.compile") +local config = autoload("eca.nfnl.config") +local notify = autoload("eca.nfnl.notify") +local fs = autoload("eca.nfnl.fs") +local gc = autoload("eca.nfnl.gc") +local vim = _G.vim +local M = define("eca.nfnl.api") +M["find-orphans"] = function(_2_) + local passive_3f = _2_["passive?"] + local dir = _2_.dir + local config0 = _2_.config + local root_dir = _2_["root-dir"] + local cfg = _2_.cfg + local dir0 = (dir or vim.fn.getcwd()) + local function _3_() + if config0 then + return {config = config0, ["root-dir"] = root_dir, cfg = cfg} + else + return config0["find-and-load"](dir0) + end + end + local _let_4_ = _3_() + local config1 = _let_4_.config + local root_dir0 = _let_4_["root-dir"] + local cfg0 = _let_4_.cfg + if config1 then + local orphan_files = gc["find-orphan-lua-files"]({["root-dir"] = root_dir0, cfg = cfg0}) + if core["empty?"](orphan_files) then + if not passive_3f then + notify.info("No orphan files detected.") + else + end + else + local function _6_(f) + return (" - " .. f) + end + notify.warn("Orphan files detected, delete them with :NfnlDeleteOrphans.\n", str.join("\n", core.map(_6_, orphan_files))) + end + return orphan_files + else + notify.warn("No .nfnl.fnl configuration found.") + return {} + end +end +M["delete-orphans"] = function(_9_) + local dir = _9_.dir + local dir0 = (dir or vim.fn.getcwd()) + local _let_10_ = config["find-and-load"](dir0) + local config0 = _let_10_.config + local root_dir = _let_10_["root-dir"] + local cfg = _let_10_.cfg + if config0 then + local orphan_files = gc["find-orphan-lua-files"]({["root-dir"] = root_dir, cfg = cfg}) + if core["empty?"](orphan_files) then + notify.info("No orphan files detected.") + else + local function _11_(f) + return (" - " .. f) + end + notify.info("Deleting orphan files:\n", str.join("\n", core.map(_11_, orphan_files))) + core.map(os.remove, orphan_files) + end + return orphan_files + else + notify.warn("No .nfnl.fnl configuration found.") + return {} + end +end +M["compile-file"] = function(_14_) + local path = _14_.path + local dir = _14_.dir + local dir0 = (dir or vim.fn.getcwd()) + local _let_15_ = config["find-and-load"](dir0) + local config0 = _let_15_.config + local root_dir = _let_15_["root-dir"] + local cfg = _let_15_.cfg + if config0 then + local path0 = fs["absolute-path"](vim.fn.expand((path or "%"))) + local result = compile["into-file"]({["root-dir"] = root_dir, cfg = cfg, path = path0, source = core.slurp(path0), ["batch?"] = true}) + notify.info("Compilation complete.\n", result) + return result + else + notify.warn("No .nfnl.fnl configuration found.") + return {} + end +end +M["compile-all-files"] = function(dir) + local dir0 = (dir or vim.fn.getcwd()) + local _let_17_ = config["find-and-load"](dir0) + local config0 = _let_17_.config + local root_dir = _let_17_["root-dir"] + local cfg = _let_17_.cfg + if config0 then + local results = compile["all-files"]({["root-dir"] = root_dir, cfg = cfg}) + notify.info("Compilation complete.\n", results) + return results + else + notify.warn("No .nfnl.fnl configuration found.") + return {} + end +end +M.dofile = function(file) + return dofile(fs["fnl-path->lua-path"](vim.fn.expand((file or "%")))) +end +return M diff --git a/lua/eca/nfnl/callback.lua b/lua/eca/nfnl/callback.lua new file mode 100644 index 0000000..1c176a0 --- /dev/null +++ b/lua/eca/nfnl/callback.lua @@ -0,0 +1,71 @@ +-- [nfnl] fnl/nfnl/callback.fnl +local _local_1_ = require("eca.nfnl.module") +local autoload = _local_1_.autoload +local define = _local_1_.define +local core = autoload("eca.nfnl.core") +local str = autoload("eca.nfnl.string") +local fs = autoload("eca.nfnl.fs") +local nvim = autoload("eca.nfnl.nvim") +local compile = autoload("eca.nfnl.compile") +local config = autoload("eca.nfnl.config") +local api = autoload("eca.nfnl.api") +local notify = autoload("eca.nfnl.notify") +local vim = _G.vim +local M = define("eca.nfnl.callback") +M["supported-path?"] = function(file_path) + local _2_ + if core["string?"](file_path) then + _2_ = not file_path:find("^[%w-]+:/") + else + _2_ = nil + end + return (_2_ or false) +end +local function buf_write_callback(ev) + do + local path = fs["full-path"](ev.file) + if M["supported-path?"](path) then + local _let_4_ = config["find-and-load"](fs.basename(path)) + local config0 = _let_4_.config + local root_dir = _let_4_["root-dir"] + local cfg = _let_4_.cfg + if config0 then + compile["into-file"]({["root-dir"] = root_dir, cfg = cfg, path = path, source = nvim["get-buf-content-as-string"](ev.buf)}) + if cfg({"orphan-detection", "auto?"}) then + api["find-orphans"]({dir = root_dir, ["passive?"] = true, config = config0, ["root-dir"] = root_dir, cfg = cfg}) + else + end + else + end + else + end + end + return nil +end +M["setup-buffer"] = function(ev) + if (false ~= vim.g["nfnl#compile_on_write"]) then + vim.api.nvim_create_autocmd({"BufWritePost"}, {group = vim.api.nvim_create_augroup(str.join({"nfnl-on-write", ev.buf}), {}), buffer = ev.buf, callback = buf_write_callback}) + else + end + local function _9_(_241) + return api.dofile(core.first(core.get(_241, "fargs"))) + end + vim.api.nvim_buf_create_user_command(ev.buf, "NfnlFile", _9_, {desc = "Run the matching Lua file for this Fennel file from disk. Does not recompile the Lua, you must use nfnl to compile your Fennel to Lua first. Calls nfnl.api/dofile under the hood.", force = true, complete = "file", nargs = "?"}) + local function _10_(_241) + return api["compile-file"]({path = core.first(core.get(_241, "fargs"))}) + end + vim.api.nvim_buf_create_user_command(ev.buf, "NfnlCompileFile", _10_, {desc = "Executes (nfnl.api/compile-file) which compiles the current file or the one provided as an argumet. The output is written to the appropriate Lua file.", force = true, complete = "file", nargs = "?"}) + local function _11_(_241) + return api["compile-all-files"](core.first(core.get(_241, "fargs"))) + end + vim.api.nvim_buf_create_user_command(ev.buf, "NfnlCompileAllFiles", _11_, {desc = "Executes (nfnl.api/compile-all-files) which will, you guessed it, compile all of your files.", force = true, complete = "file", nargs = "?"}) + local function _12_(_241) + return api["find-orphans"]({dir = core.first(core.get(_241, "fargs"))}) + end + vim.api.nvim_buf_create_user_command(ev.buf, "NfnlFindOrphans", _12_, {desc = "Executes (nfnl.api/find-orphans) which will find and display all Lua files that no longer have a matching Fennel file.", force = true, complete = "file", nargs = "?"}) + local function _13_(_241) + return api["delete-orphans"]({dir = core.first(core.get(_241, "fargs"))}) + end + return vim.api.nvim_buf_create_user_command(ev.buf, "NfnlDeleteOrphans", _13_, {desc = "Executes (nfnl.api/delete-orphans) deletes any orphan Lua files that no longer have their original Fennel file they were compiled from.", force = true, complete = "file", nargs = "?"}) +end +return M diff --git a/lua/eca/nfnl/compile.lua b/lua/eca/nfnl/compile.lua new file mode 100644 index 0000000..9743445 --- /dev/null +++ b/lua/eca/nfnl/compile.lua @@ -0,0 +1,124 @@ +-- [nfnl] fnl/nfnl/compile.fnl +local _local_1_ = require("eca.nfnl.module") +local autoload = _local_1_.autoload +local define = _local_1_.define +local core = autoload("eca.nfnl.core") +local str = autoload("eca.nfnl.string") +local fs = autoload("eca.nfnl.fs") +local fennel = autoload("eca.nfnl.fennel") +local notify = autoload("eca.nfnl.notify") +local config = autoload("eca.nfnl.config") +local header = autoload("eca.nfnl.header") +local M = define("eca.nfnl.compile") +local function safe_target_3f(path) + local line = fs["read-first-line"](path) + return (not line or header["tagged?"](line)) +end +M["macro-source?"] = function(_2_) + local source = _2_.source + local path = _2_.path + return ((core["string?"](source) and string.find(source, "%s*;+%s*%[nfnl%-macro%]") and true) or (core["string?"](path) and path and str["ends-with?"](path, ".fnlm"))) +end +local function valid_source_files(glob_fn, _3_) + local root_dir = _3_["root-dir"] + local cfg = _3_.cfg + local function _4_(_241) + return glob_fn(root_dir, _241) + end + return core.mapcat(_4_, cfg({"source-file-patterns"})) +end +local function valid_source_file_3f(path, _5_) + local root_dir = _5_["root-dir"] + local cfg = _5_.cfg + local function _6_(_241) + return fs["glob-matches?"](root_dir, _241, path) + end + return core.some(_6_, cfg({"source-file-patterns"})) +end +M["into-string"] = function(_7_) + local root_dir = _7_["root-dir"] + local path = _7_.path + local cfg = _7_.cfg + local source = _7_.source + local batch_3f = _7_["batch?"] + local opts = _7_ + local macro_3f = M["macro-source?"](opts) + if (macro_3f and batch_3f) then + return {status = "macros-are-not-compiled", ["source-path"] = path} + elseif macro_3f then + core["clear-table!"](fennel["macro-loaded"]) + return M["all-files"]({["root-dir"] = root_dir, cfg = cfg}) + elseif config["config-file-path?"](path) then + return {status = "nfnl-config-is-not-compiled", ["source-path"] = path} + elseif not valid_source_file_3f(path, opts) then + return {status = "path-is-not-in-source-file-patterns", ["source-path"] = path} + else + local rel_file_name = path:sub((2 + root_dir:len())) + local ok, res + do + fennel.path = cfg({"fennel-path"}) + fennel["macro-path"] = cfg({"fennel-macro-path"}) + ok, res = pcall(fennel["compile-string"], source, core.merge({filename = rel_file_name, warn = notify.warn}, cfg({"compiler-options"}))) + end + if ok then + if cfg({"verbose"}) then + notify.info("Successfully compiled: ", path) + else + end + local _9_ + if cfg({"header-comment"}) then + _9_ = header["with-header"](rel_file_name, res) + else + _9_ = res + end + return {status = "ok", ["source-path"] = path, result = (_9_ .. "\n")} + else + if not batch_3f then + notify.error(res) + else + end + return {status = "compilation-error", error = res, ["source-path"] = path} + end + end +end +M["into-file"] = function(_14_) + local _root_dir = _14_["_root-dir"] + local cfg = _14_.cfg + local _source = _14_._source + local path = _14_.path + local batch_3f = _14_["batch?"] + local opts = _14_ + local fnl_path__3elua_path = cfg({"fnl-path->lua-path"}) + local destination_path = fnl_path__3elua_path(path) + local _let_15_ = M["into-string"](opts) + local status = _let_15_.status + local source_path = _let_15_["source-path"] + local result = _let_15_.result + local res = _let_15_ + if ("ok" ~= status) then + return res + elseif (safe_target_3f(destination_path) or not cfg({"header-comment"})) then + fs.mkdirp(fs.basename(destination_path)) + core.spit(destination_path, result) + return {status = "ok", ["source-path"] = source_path, ["destination-path"] = destination_path} + else + if not batch_3f then + notify.warn(destination_path, " was not compiled by nfnl. Delete it manually if you wish to compile into this file.") + else + end + return {status = "destination-exists", ["source-path"] = path, ["destination-path"] = destination_path} + end +end +M["all-files"] = function(_18_) + local root_dir = _18_["root-dir"] + local cfg = _18_.cfg + local opts = _18_ + local function _19_(path) + return M["into-file"]({["root-dir"] = root_dir, path = path, cfg = cfg, source = core.slurp(path), ["batch?"] = true}) + end + local function _20_(_241) + return fs["join-path"]({root_dir, _241}) + end + return core.map(_19_, core.map(_20_, valid_source_files(fs.relglob, opts))) +end +return M diff --git a/lua/eca/nfnl/config.lua b/lua/eca/nfnl/config.lua new file mode 100644 index 0000000..df3f874 --- /dev/null +++ b/lua/eca/nfnl/config.lua @@ -0,0 +1,105 @@ +-- [nfnl] fnl/nfnl/config.fnl +local _local_1_ = require("eca.nfnl.module") +local autoload = _local_1_.autoload +local define = _local_1_.define +local core = autoload("eca.nfnl.core") +local fs = autoload("eca.nfnl.fs") +local str = autoload("eca.nfnl.string") +local fennel = autoload("eca.nfnl.fennel") +local notify = autoload("eca.nfnl.notify") +local vim = _G.vim +local M = define("eca.nfnl.config") +local config_file_name = ".nfnl.fnl" +M.find = function(dir) + return fs.findfile(config_file_name, (dir .. ";")) +end +M["path-dirs"] = function(_2_) + local rtp_patterns = _2_["rtp-patterns"] + local runtimepath = _2_.runtimepath + local base_dirs = _2_["base-dirs"] + local function _3_(path) + local function _4_(_241) + return string.find(path, _241) + end + return core.some(_4_, rtp_patterns) + end + return core.distinct(core.concat(base_dirs, core.filter(_3_, str.split(runtimepath, ",")))) +end +M.default = function(opts) + local root_dir + local or_5_ = core.get(opts, "root-dir") + if not or_5_ then + local tmp_3_ = vim.fn.getcwd() + if (nil ~= tmp_3_) then + local tmp_3_0 = M.find(tmp_3_) + if (nil ~= tmp_3_0) then + local tmp_3_1 = fs["full-path"](tmp_3_0) + if (nil ~= tmp_3_1) then + or_5_ = fs.basename(tmp_3_1) + else + or_5_ = nil + end + else + or_5_ = nil + end + else + or_5_ = nil + end + end + root_dir = (or_5_ or vim.fn.getcwd()) + local dirs = M["path-dirs"]({runtimepath = vim.o.runtimepath, ["rtp-patterns"] = core.get(opts, "rtp-patterns", {(fs["path-sep"]() .. "nfnl$")}), ["base-dirs"] = {root_dir}}) + local function _12_(root_dir0) + return core.map(fs["join-path"], {{root_dir0, "?.fnl"}, {root_dir0, "?", "init.fnl"}, {root_dir0, "fnl", "?.fnl"}, {root_dir0, "fnl", "?", "init.fnl"}}) + end + local function _13_(root_dir0) + return core.map(fs["join-path"], {{root_dir0, "?.fnlm"}, {root_dir0, "?", "init.fnlm"}, {root_dir0, "?", "init-macros.fnlm"}, {root_dir0, "fnl", "?.fnlm"}, {root_dir0, "fnl", "?", "init.fnlm"}, {root_dir0, "fnl", "?", "init-macros.fnlm"}, {root_dir0, "?.fnl"}, {root_dir0, "?", "init.fnl"}, {root_dir0, "?", "init-macros.fnl"}, {root_dir0, "fnl", "?.fnl"}, {root_dir0, "fnl", "?", "init.fnl"}, {root_dir0, "fnl", "?", "init-macros.fnl"}}) + end + return {["header-comment"] = true, ["compiler-options"] = {["error-pinpoint"] = false}, ["orphan-detection"] = {["auto?"] = true, ["ignore-patterns"] = {}}, ["root-dir"] = root_dir, ["fennel-path"] = str.join(";", core.mapcat(_12_, dirs)), ["fennel-macro-path"] = str.join(";", core.mapcat(_13_, dirs)), ["source-file-patterns"] = {".*.fnl", "*.fnl", fs["join-path"]({"**", "*.fnl"})}, ["fnl-path->lua-path"] = fs["fnl-path->lua-path"], verbose = false} +end +M["cfg-fn"] = function(t, opts) + local default_cfg = M.default(opts) + local function _14_(path) + return core["get-in"](t, path, core["get-in"](default_cfg, path)) + end + return _14_ +end +local notified = {} +M["config-file-path?"] = function(path) + return (config_file_name == fs.filename(path)) +end +M["find-and-load"] = function(dir) + local _15_ + do + local config_file_path = M.find(dir) + if config_file_path then + local root_dir = fs.basename(config_file_path) + local config_source = vim.secure.read(config_file_path) + local ok, config + if core["nil?"](config_source) then + if not notified[config_file_path] then + notified[config_file_path] = true + notify.info(config_file_path, " is not trusted yet. Open it and :trust to enable nfnl.") + else + end + ok, config = false, nil + elseif (str["blank?"](config_source) or ("{}" == str.trim(config_source))) then + ok, config = true, {} + else + ok, config = pcall(fennel.eval, config_source, {filename = config_file_path}) + end + if ok then + _15_ = {config = config, ["root-dir"] = root_dir, cfg = M["cfg-fn"](config, {["root-dir"] = root_dir})} + else + if config then + _15_ = notify.error(config) + else + _15_ = nil + end + end + else + _15_ = nil + end + end + return (_15_ or {}) +end +return M diff --git a/lua/eca/nfnl/core.lua b/lua/eca/nfnl/core.lua new file mode 100644 index 0000000..937d4e1 --- /dev/null +++ b/lua/eca/nfnl/core.lua @@ -0,0 +1,530 @@ +-- [nfnl] fnl/nfnl/core.fnl +local _local_1_ = require("eca.nfnl.module") +local autoload = _local_1_.autoload +local fennel = autoload("eca.nfnl.fennel") +local function rand(n) + return (math.random() * (n or 1)) +end +local function nil_3f(x) + return (nil == x) +end +local function number_3f(x) + return ("number" == type(x)) +end +local function boolean_3f(x) + return ("boolean" == type(x)) +end +local function string_3f(x) + return ("string" == type(x)) +end +local function table_3f(x) + return ("table" == type(x)) +end +local function function_3f(value) + return ("function" == type(value)) +end +local function keys(t) + local result = {} + if t then + for k, _ in pairs(t) do + table.insert(result, k) + end + else + end + return result +end +local function first(xs) + if xs then + return xs[1] + else + return nil + end +end +local function second(xs) + if xs then + return xs[2] + else + return nil + end +end +local function count(xs) + if table_3f(xs) then + local maxn = table.maxn(xs) + if (0 == maxn) then + return table.maxn(keys(xs)) + else + return maxn + end + elseif not xs then + return 0 + else + return #xs + end +end +local function empty_3f(xs) + return (0 == count(xs)) +end +local function sequential_3f(xs) + return (table_3f(xs) and (empty_3f(xs) or (1 == first(keys(xs))))) +end +local function kv_pairs(t) + local result = {} + if t then + for k, v in pairs(t) do + table.insert(result, {k, v}) + end + else + end + return result +end +local function seq(x) + if empty_3f(x) then + return nil + elseif sequential_3f(x) then + return x + elseif table_3f(x) then + return kv_pairs(x) + elseif string_3f(x) then + local acc = {} + for i = 1, count(x) do + table.insert(acc, x:sub(i, i)) + end + if not empty_3f(acc) then + return acc + else + return nil + end + else + return nil + end +end +local function last(xs) + if xs then + return xs[count(xs)] + else + return nil + end +end +local function inc(n) + return (n + 1) +end +local function dec(n) + return (n - 1) +end +local function even_3f(n) + return ((n % 2) == 0) +end +local function odd_3f(n) + return not even_3f(n) +end +local function vals(t) + local result = {} + if t then + for _, v in pairs(t) do + table.insert(result, v) + end + else + end + return result +end +local function run_21(f, xs) + if xs then + local nxs = count(xs) + if (nxs > 0) then + for i = 1, nxs do + f(xs[i]) + end + return nil + else + return nil + end + else + return nil + end +end +local function complement(f) + local function _14_(...) + return not f(...) + end + return _14_ +end +local function filter(f, xs) + local result = {} + local function _15_(x) + if f(x) then + return table.insert(result, x) + else + return nil + end + end + run_21(_15_, xs) + return result +end +local function remove(f, xs) + return filter(complement(f), xs) +end +local function map(f, xs) + local result = {} + local function _17_(x) + local mapped = f(x) + local function _18_() + if (0 == select("#", mapped)) then + return nil + else + return mapped + end + end + return table.insert(result, _18_()) + end + run_21(_17_, xs) + return result +end +local function map_indexed(f, xs) + return map(f, kv_pairs(xs)) +end +local function identity(x) + return x +end +local function reduce(f, init, xs) + local result = init + local function _19_(x) + result = f(result, x) + return nil + end + run_21(_19_, xs) + return result +end +local function some(f, xs) + local result = nil + local n = 1 + while (nil_3f(result) and (n <= count(xs))) do + local candidate = f(xs[n]) + if candidate then + result = candidate + else + end + n = inc(n) + end + return result +end +local function butlast(xs) + local total = count(xs) + local function _22_(_21_) + local n = _21_[1] + local v = _21_[2] + return (n ~= total) + end + return map(second, filter(_22_, kv_pairs(xs))) +end +local function rest(xs) + local function _24_(_23_) + local n = _23_[1] + local v = _23_[2] + return (n ~= 1) + end + return map(second, filter(_24_, kv_pairs(xs))) +end +local function concat(...) + local result = {} + local function _25_(xs) + local function _26_(x) + return table.insert(result, x) + end + return run_21(_26_, xs) + end + run_21(_25_, {...}) + return result +end +local function mapcat(f, xs) + return concat(unpack(map(f, xs))) +end +local function pr_str(...) + local s + local function _27_(x) + return fennel.view(x, {["one-line"] = true}) + end + s = table.concat(map(_27_, {...}), " ") + if (nil_3f(s) or ("" == s)) then + return "nil" + else + return s + end +end +local function str(...) + local function _29_(acc, s) + return (acc .. s) + end + local function _30_(s) + if string_3f(s) then + return s + else + return pr_str(s) + end + end + return reduce(_29_, "", map(_30_, {...})) +end +local function println(...) + local function _32_(acc, s) + return (acc .. s) + end + local function _34_(_33_) + local i = _33_[1] + local s = _33_[2] + if (1 == i) then + return s + else + return (" " .. s) + end + end + local function _36_(s) + if string_3f(s) then + return s + else + return pr_str(s) + end + end + return print(reduce(_32_, "", map_indexed(_34_, map(_36_, {...})))) +end +local function pr(...) + return println(pr_str(...)) +end +local function slurp(path) + if path then + local case_38_, case_39_ = io.open(path, "r") + if ((case_38_ == nil) and true) then + local _msg = case_39_ + return nil + elseif (nil ~= case_38_) then + local f = case_38_ + local content = f:read("*all") + f:close() + return content + else + return nil + end + else + return nil + end +end +local function get(t, k, d) + local res + if table_3f(t) then + local val = t[k] + if not nil_3f(val) then + res = val + else + res = nil + end + else + res = nil + end + if nil_3f(res) then + return d + else + return res + end +end +local function spit(path, content, opts) + if path then + local case_45_, case_46_ + local function _47_() + if get(opts, "append") then + return "a" + else + return "w" + end + end + case_45_, case_46_ = io.open(path, _47_()) + if ((case_45_ == nil) and (nil ~= case_46_)) then + local msg = case_46_ + return error(("Could not open file: " .. msg)) + elseif (nil ~= case_45_) then + local f = case_45_ + f:write(content) + f:close() + return nil + else + return nil + end + else + return nil + end +end +local function merge_21(base, ...) + local function _50_(acc, m) + if m then + for k, v in pairs(m) do + acc[k] = v + end + else + end + return acc + end + return reduce(_50_, (base or {}), {...}) +end +local function merge(...) + return merge_21({}, ...) +end +local function select_keys(t, ks) + if (t and ks) then + local function _52_(acc, k) + if k then + acc[k] = t[k] + else + end + return acc + end + return reduce(_52_, {}, ks) + else + return {} + end +end +local function get_in(t, ks, d) + local res + local function _55_(acc, k) + if table_3f(acc) then + return get(acc, k) + else + return nil + end + end + res = reduce(_55_, t, ks) + if nil_3f(res) then + return d + else + return res + end +end +local function assoc(t, ...) + local _let_58_ = {...} + local k = _let_58_[1] + local v = _let_58_[2] + local xs = (function (t, k) return ((getmetatable(t) or {}).__fennelrest or function (t, k) return {(table.unpack or unpack)(t, k)} end)(t, k) end)(_let_58_, 3) + local rem = count(xs) + local t0 = (t or {}) + if odd_3f(rem) then + error("assoc expects even number of arguments after table, found odd number") + else + end + if not nil_3f(k) then + t0[k] = v + else + end + if (rem > 0) then + assoc(t0, unpack(xs)) + else + end + return t0 +end +local function assoc_in(t, ks, v) + local path = butlast(ks) + local final = last(ks) + local t0 = (t or {}) + local function _62_(acc, k) + local step = get(acc, k) + if nil_3f(step) then + return get(assoc(acc, k, {}), k) + else + return step + end + end + assoc(reduce(_62_, t0, path), final, v) + return t0 +end +local function update(t, k, f) + return assoc(t, k, f(get(t, k))) +end +local function update_in(t, ks, f) + return assoc_in(t, ks, f(get_in(t, ks))) +end +local function constantly(v) + local function _64_() + return v + end + return _64_ +end +local function distinct(xs) + local function _65_(acc, x) + acc[x] = true + return acc + end + return keys(reduce(_65_, {}, xs)) +end +local function sort(xs) + local copy = map(identity, xs) + table.sort(copy) + return copy +end +local function clear_table_21(t) + if t then + for k, _ in pairs(t) do + t[k] = nil + end + else + end + return nil +end +local function take_while(f, xs) + local xs0 = seq(xs) + if xs0 then + local acc = {} + local done_3f = false + for i = 1, count(xs0), 1 do + local v = xs0[i] + if (not done_3f and f(v)) then + table.insert(acc, v) + else + done_3f = true + end + end + return acc + else + return nil + end +end +local function drop_while(f, xs) + local xs0 = seq(xs) + if xs0 then + local acc = {} + local done_3f = false + for i = 1, count(xs0), 1 do + local v = xs0[i] + if (done_3f or not f(v)) then + table.insert(acc, v) + done_3f = true + else + end + end + return acc + else + return nil + end +end +local function __3eset(tbl) + if tbl then + assert(table_3f(tbl), "Table required as input to ->set.") + local result = {} + for _n, v in ipairs(tbl) do + result[v] = true + end + return result + else + return nil + end +end +local function contains_3f(tbl, v) + if tbl then + assert(table_3f(tbl), "contains? expects a table") + if sequential_3f(tbl) then + local function _72_(_241) + return (_241 == v) + end + return (some(_72_, tbl) or false) + else + return (true == tbl[v]) + end + else + return nil + end +end +return {rand = rand, ["nil?"] = nil_3f, ["number?"] = number_3f, ["boolean?"] = boolean_3f, ["string?"] = string_3f, ["table?"] = table_3f, ["function?"] = function_3f, keys = keys, count = count, ["empty?"] = empty_3f, first = first, second = second, last = last, inc = inc, dec = dec, ["even?"] = even_3f, ["odd?"] = odd_3f, vals = vals, ["kv-pairs"] = kv_pairs, ["run!"] = run_21, complement = complement, filter = filter, remove = remove, map = map, ["map-indexed"] = map_indexed, identity = identity, reduce = reduce, some = some, butlast = butlast, rest = rest, concat = concat, mapcat = mapcat, ["pr-str"] = pr_str, str = str, println = println, pr = pr, slurp = slurp, spit = spit, ["merge!"] = merge_21, merge = merge, ["select-keys"] = select_keys, get = get, ["get-in"] = get_in, assoc = assoc, ["assoc-in"] = assoc_in, update = update, ["update-in"] = update_in, constantly = constantly, distinct = distinct, sort = sort, ["clear-table!"] = clear_table_21, ["sequential?"] = sequential_3f, seq = seq, ["take-while"] = take_while, ["drop-while"] = drop_while, ["->set"] = __3eset, ["contains?"] = contains_3f} diff --git a/lua/eca/nfnl/fennel.lua b/lua/eca/nfnl/fennel.lua new file mode 100644 index 0000000..4b29c52 --- /dev/null +++ b/lua/eca/nfnl/fennel.lua @@ -0,0 +1,7061 @@ +-- SPDX-License-Identifier: MIT +-- SPDX-FileCopyrightText: Calvin Rose and contributors +package.preload["eca.nfnl.fennel.repl"] = package.preload["eca.nfnl.fennel.repl"] or function(...) + local _760_ = require("eca.nfnl.fennel.utils") + local utils = _760_ + local copy = _760_["copy"] + local parser = require("eca.nfnl.fennel.parser") + local compiler = require("eca.nfnl.fennel.compiler") + local specials = require("eca.nfnl.fennel.specials") + local view = require("eca.nfnl.fennel.view") + local depth = 0 + local function prompt_for(top_3f) + if top_3f then + return (string.rep(">", (depth + 1)) .. " ") + else + return (string.rep(".", (depth + 1)) .. " ") + end + end + local function default_read_chunk(parser_state) + io.write(prompt_for((0 == parser_state["stack-size"]))) + io.flush() + local _762_0 = io.read() + if (nil ~= _762_0) then + local input = _762_0 + return (input .. "\n") + end + end + local function default_on_values(xs) + io.write(table.concat(xs, "\9")) + return io.write("\n") + end + local function default_on_error(errtype, err) + local function _765_() + local _764_0 = errtype + if (_764_0 == "Runtime") then + return (compiler.traceback(tostring(err), 4) .. "\n") + else + local _ = _764_0 + return ("%s error: %s\n"):format(errtype, tostring(err)) + end + end + return io.write(_765_()) + end + local function splice_save_locals(env, lua_source, scope) + local saves = nil + do + local tbl_17_ = {} + local i_18_ = #tbl_17_ + for name in pairs(env.___replLocals___) do + local val_19_ = ("local %s = ___replLocals___[%q]"):format((scope.manglings[name] or name), name) + if (nil ~= val_19_) then + i_18_ = (i_18_ + 1) + tbl_17_[i_18_] = val_19_ + end + end + saves = tbl_17_ + end + local binds = nil + do + local tbl_17_ = {} + local i_18_ = #tbl_17_ + for raw, name in pairs(scope.manglings) do + local val_19_ = nil + if (scope.symmeta[raw] and not scope.gensyms[name]) then + val_19_ = ("___replLocals___[%q] = %s"):format(raw, name) + else + val_19_ = nil + end + if (nil ~= val_19_) then + i_18_ = (i_18_ + 1) + tbl_17_[i_18_] = val_19_ + end + end + binds = tbl_17_ + end + local gap = nil + if lua_source:find("\n") then + gap = "\n" + else + gap = " " + end + local function _771_() + if next(saves) then + return (table.concat(saves, " ") .. gap) + else + return "" + end + end + local function _774_() + local _772_0, _773_0 = lua_source:match("^(.*)[\n ](return .*)$") + if ((nil ~= _772_0) and (nil ~= _773_0)) then + local body = _772_0 + local _return = _773_0 + return (body .. gap .. table.concat(binds, " ") .. gap .. _return) + else + local _ = _772_0 + return lua_source + end + end + return (_771_() .. _774_()) + end + local commands = {} + local function completer(env, scope, text, _3ffulltext, _from, _to) + local max_items = 2000 + local seen = {} + local matches = {} + local input_fragment = text:gsub(".*[%s)(]+", "") + local stop_looking_3f = false + local function add_partials(input, tbl, prefix) + local scope_first_3f = ((tbl == env) or (tbl == env.___replLocals___)) + local tbl_17_ = matches + local i_18_ = #tbl_17_ + local function _776_() + if scope_first_3f then + return scope.manglings + else + return tbl + end + end + for k, is_mangled in utils.allpairs(_776_()) do + if (max_items <= #matches) then break end + local val_19_ = nil + do + local lookup_k = nil + if scope_first_3f then + lookup_k = is_mangled + else + lookup_k = k + end + if ((type(k) == "string") and (input == k:sub(0, #input)) and not seen[k] and ((":" ~= prefix:sub(-1)) or ("function" == type(tbl[lookup_k])))) then + seen[k] = true + val_19_ = (prefix .. k) + else + val_19_ = nil + end + end + if (nil ~= val_19_) then + i_18_ = (i_18_ + 1) + tbl_17_[i_18_] = val_19_ + end + end + return tbl_17_ + end + local function descend(input, tbl, prefix, add_matches, method_3f) + local splitter = nil + if method_3f then + splitter = "^([^:]+):(.*)" + else + splitter = "^([^.]+)%.(.*)" + end + local head, tail = input:match(splitter) + local raw_head = (scope.manglings[head] or head) + if (type(tbl[raw_head]) == "table") then + stop_looking_3f = true + if method_3f then + return add_partials(tail, tbl[raw_head], (prefix .. head .. ":")) + else + return add_matches(tail, tbl[raw_head], (prefix .. head)) + end + end + end + local function add_matches(input, tbl, _3fprefix) + local prefix = nil + if _3fprefix then + prefix = (_3fprefix .. ".") + else + prefix = "" + end + if (not input:find("%.") and input:find(":")) then + return descend(input, tbl, prefix, add_matches, true) + elseif not input:find("%.") then + return add_partials(input, tbl, prefix) + else + return descend(input, tbl, prefix, add_matches, false) + end + end + do + local _785_0 = tostring((_3ffulltext or text)):match("^%s*,([^%s()[%]]*)$") + if (nil ~= _785_0) then + local cmd_fragment = _785_0 + add_partials(cmd_fragment, commands, ",") + else + local _ = _785_0 + for _0, source in ipairs({scope.specials, scope.macros, (env.___replLocals___ or {}), env, env._G}) do + if stop_looking_3f then break end + add_matches(input_fragment, source) + end + end + end + return matches + end + local function command_3f(input) + return input:match("^%s*,") + end + local function command_docs() + local _787_ + do + local tbl_17_ = {} + local i_18_ = #tbl_17_ + for name, f in utils.stablepairs(commands) do + local val_19_ = (" ,%s - %s"):format(name, ((compiler.metadata):get(f, "fnl/docstring") or "undocumented")) + if (nil ~= val_19_) then + i_18_ = (i_18_ + 1) + tbl_17_[i_18_] = val_19_ + end + end + _787_ = tbl_17_ + end + return table.concat(_787_, "\n") + end + commands.help = function(_, _0, on_values) + return on_values({("Welcome to Fennel.\nThis is the REPL where you can enter code to be evaluated.\nYou can also run these repl commands:\n\n" .. command_docs() .. "\n ,return FORM - Evaluate FORM and return its value to the REPL's caller.\n ,exit - Leave the repl.\n\nUse ,doc something to see descriptions for individual macros and special forms.\nValues from previous inputs are kept in *1, *2, and *3.\n\nFor more information about the language, see https://fennel-lang.org/reference")}) + end + do end (compiler.metadata):set(commands.help, "fnl/docstring", "Show this message.") + local function reload(module_name, env, on_values, on_error) + local _789_0, _790_0 = pcall(specials["load-code"]("return require(...)", env), module_name) + if ((_789_0 == true) and (nil ~= _790_0)) then + local old = _790_0 + local old_macro_module = specials["macro-loaded"][module_name] + local _ = nil + specials["macro-loaded"][module_name] = nil + _ = nil + local _0 = nil + package.loaded[module_name] = nil + _0 = nil + local new = nil + do + local _791_0, _792_0 = pcall(require, module_name) + if ((_791_0 == true) and (nil ~= _792_0)) then + local new0 = _792_0 + new = new0 + elseif (true and (nil ~= _792_0)) then + local _1 = _791_0 + local msg = _792_0 + on_error("Repl", msg) + specials["macro-loaded"][module_name] = old_macro_module + new = old + else + new = nil + end + end + if ((type(old) == "table") and (type(new) == "table")) then + for k, v in pairs(new) do + old[k] = v + end + for k in pairs(old) do + if (nil == new[k]) then + old[k] = nil + end + end + package.loaded[module_name] = old + end + return on_values({"ok"}) + elseif ((_789_0 == false) and (nil ~= _790_0)) then + local msg = _790_0 + if msg:match("loop or previous error loading module") then + package.loaded[module_name] = nil + return reload(module_name, env, on_values, on_error) + elseif specials["macro-loaded"][module_name] then + specials["macro-loaded"][module_name] = nil + return nil + else + local function _797_() + local _796_0 = msg:gsub("\n.*", "") + return _796_0 + end + return on_error("Runtime", _797_()) + end + end + end + local function run_command(read, on_error, f) + local _800_0, _801_0, _802_0 = pcall(read) + if ((_800_0 == true) and (_801_0 == true) and (nil ~= _802_0)) then + local val = _802_0 + local _803_0, _804_0 = pcall(f, val) + if ((_803_0 == false) and (nil ~= _804_0)) then + local msg = _804_0 + return on_error("Runtime", msg) + end + elseif (_800_0 == false) then + return on_error("Parse", "Couldn't parse input.") + end + end + commands.reload = function(env, read, on_values, on_error) + local function _807_(_241) + return reload(tostring(_241), env, on_values, on_error) + end + return run_command(read, on_error, _807_) + end + do end (compiler.metadata):set(commands.reload, "fnl/docstring", "Reload the specified module.") + commands.reset = function(env, _, on_values) + env.___replLocals___ = {} + return on_values({"ok"}) + end + do end (compiler.metadata):set(commands.reset, "fnl/docstring", "Erase all repl-local scope.") + commands.complete = function(env, read, on_values, on_error, scope, chars) + local function _808_() + return on_values(completer(env, scope, table.concat(chars):gsub("^%s*,complete%s+", ""):sub(1, -2))) + end + return run_command(read, on_error, _808_) + end + do end (compiler.metadata):set(commands.complete, "fnl/docstring", "Print all possible completions for a given input symbol.") + local function apropos_2a(pattern, tbl, prefix, seen, names) + for name, subtbl in pairs(tbl) do + if (("string" == type(name)) and (package ~= subtbl)) then + local _809_0 = type(subtbl) + if (_809_0 == "function") then + if ((prefix .. name)):match(pattern) then + table.insert(names, (prefix .. name)) + end + elseif (_809_0 == "table") then + if not seen[subtbl] then + local _811_ + do + seen[subtbl] = true + _811_ = seen + end + apropos_2a(pattern, subtbl, (prefix .. name:gsub("%.", "/") .. "."), _811_, names) + end + end + end + end + return names + end + local function apropos(pattern) + return apropos_2a(pattern:gsub("^_G%.", ""), package.loaded, "", {}, {}) + end + commands.apropos = function(_env, read, on_values, on_error, _scope) + local function _815_(_241) + return on_values(apropos(tostring(_241))) + end + return run_command(read, on_error, _815_) + end + do end (compiler.metadata):set(commands.apropos, "fnl/docstring", "Print all functions matching a pattern in all loaded modules.") + local function apropos_follow_path(path) + local paths = nil + do + local tbl_17_ = {} + local i_18_ = #tbl_17_ + for p in path:gmatch("[^%.]+") do + local val_19_ = p + if (nil ~= val_19_) then + i_18_ = (i_18_ + 1) + tbl_17_[i_18_] = val_19_ + end + end + paths = tbl_17_ + end + local tgt = package.loaded + for _, path0 in ipairs(paths) do + if (nil == tgt) then break end + local _818_ + do + local _817_0 = path0:gsub("%/", ".") + _818_ = _817_0 + end + tgt = tgt[_818_] + end + return tgt + end + local function apropos_doc(pattern) + local tbl_17_ = {} + local i_18_ = #tbl_17_ + for _, path in ipairs(apropos(".*")) do + local val_19_ = nil + do + local tgt = apropos_follow_path(path) + if ("function" == type(tgt)) then + local _819_0 = (compiler.metadata):get(tgt, "fnl/docstring") + if (nil ~= _819_0) then + local docstr = _819_0 + val_19_ = (docstr:match(pattern) and path) + else + val_19_ = nil + end + else + val_19_ = nil + end + end + if (nil ~= val_19_) then + i_18_ = (i_18_ + 1) + tbl_17_[i_18_] = val_19_ + end + end + return tbl_17_ + end + commands["apropos-doc"] = function(_env, read, on_values, on_error, _scope) + local function _823_(_241) + return on_values(apropos_doc(tostring(_241))) + end + return run_command(read, on_error, _823_) + end + do end (compiler.metadata):set(commands["apropos-doc"], "fnl/docstring", "Print all functions that match the pattern in their docs") + local function apropos_show_docs(on_values, pattern) + for _, path in ipairs(apropos(pattern)) do + local tgt = apropos_follow_path(path) + if (("function" == type(tgt)) and (compiler.metadata):get(tgt, "fnl/docstring")) then + on_values({specials.doc(tgt, path)}) + on_values({}) + end + end + return nil + end + commands["apropos-show-docs"] = function(_env, read, on_values, on_error) + local function _825_(_241) + return apropos_show_docs(on_values, tostring(_241)) + end + return run_command(read, on_error, _825_) + end + do end (compiler.metadata):set(commands["apropos-show-docs"], "fnl/docstring", "Print all documentations matching a pattern in function name") + local function resolve(identifier, _826_0, scope) + local _827_ = _826_0 + local env = _827_ + local ___replLocals___ = _827_["___replLocals___"] + local e = nil + local function _828_(_241, _242) + return (___replLocals___[scope.unmanglings[_242]] or env[_242]) + end + e = setmetatable({}, {__index = _828_}) + local function _829_(...) + local _830_0, _831_0 = ... + if ((_830_0 == true) and (nil ~= _831_0)) then + local code = _831_0 + local function _832_(...) + local _833_0, _834_0 = ... + if ((_833_0 == true) and (nil ~= _834_0)) then + local val = _834_0 + return val + else + local _ = _833_0 + return nil + end + end + return _832_(pcall(specials["load-code"](code, e))) + else + local _ = _830_0 + return nil + end + end + return _829_(pcall(compiler["compile-string"], tostring(identifier), {scope = scope})) + end + commands.find = function(env, read, on_values, on_error, scope) + local function _837_(_241) + local _838_0 = nil + do + local _839_0 = utils["sym?"](_241) + if (nil ~= _839_0) then + local _840_0 = resolve(_839_0, env, scope) + if (nil ~= _840_0) then + _838_0 = debug.getinfo(_840_0) + else + _838_0 = _840_0 + end + else + _838_0 = _839_0 + end + end + local function _843_() + local line = _838_0.linedefined + local source = _838_0.source + return (("string" == type(source)) and ("@" == source:sub(1, 1))) + end + if (((_G.type(_838_0) == "table") and (nil ~= _838_0.linedefined) and (nil ~= _838_0.source) and (_838_0.what == "Lua")) and _843_()) then + local line = _838_0.linedefined + local source = _838_0.source + local fnlsrc = nil + do + local _844_0 = compiler.sourcemap + if (nil ~= _844_0) then + _844_0 = _844_0[source] + end + if (nil ~= _844_0) then + _844_0 = _844_0[line] + end + if (nil ~= _844_0) then + _844_0 = _844_0[2] + end + fnlsrc = _844_0 + end + return on_values({string.format("%s:%s", source:sub(2), (fnlsrc or line))}) + elseif (_838_0 == nil) then + return on_error("Repl", "Unknown value") + else + local _ = _838_0 + return on_error("Repl", "No source info") + end + end + return run_command(read, on_error, _837_) + end + do end (compiler.metadata):set(commands.find, "fnl/docstring", "Print the filename and line number for a given function") + commands.doc = function(env, read, on_values, on_error, scope) + local function _849_(_241) + local name = tostring(_241) + local path = (utils["multi-sym?"](name) or {name}) + local ok_3f, target = nil, nil + local function _850_() + return (scope.specials[name] or utils["get-in"](scope.macros, path) or resolve(name, env, scope)) + end + ok_3f, target = pcall(_850_) + if ok_3f then + return on_values({specials.doc(target, name)}) + else + return on_error("Repl", ("Could not find " .. name .. " for docs.")) + end + end + return run_command(read, on_error, _849_) + end + do end (compiler.metadata):set(commands.doc, "fnl/docstring", "Print the docstring and arglist for a function, macro, or special form.") + commands.compile = function(_, read, on_values, on_error, _0, _1, opts) + local function _852_(_241) + local _853_0, _854_0 = pcall(compiler.compile, _241, opts) + if ((_853_0 == true) and (nil ~= _854_0)) then + local result = _854_0 + return on_values({result}) + elseif (true and (nil ~= _854_0)) then + local _2 = _853_0 + local msg = _854_0 + return on_error("Repl", ("Error compiling expression: " .. msg)) + end + end + return run_command(read, on_error, _852_) + end + do end (compiler.metadata):set(commands.compile, "fnl/docstring", "compiles the expression into lua and prints the result.") + local function load_plugin_commands(plugins) + for i = #(plugins or {}), 1, -1 do + for name, f in pairs(plugins[i]) do + local _856_0 = name:match("^repl%-command%-(.*)") + if (nil ~= _856_0) then + local cmd_name = _856_0 + commands[cmd_name] = f + end + end + end + return nil + end + local function run_command_loop(input, read, loop, env, on_values, on_error, scope, chars, opts) + local command_name = input:match(",([^%s/]+)") + do + local _858_0 = commands[command_name] + if (nil ~= _858_0) then + local command = _858_0 + command(env, read, on_values, on_error, scope, chars, opts) + else + local _ = _858_0 + if ((command_name ~= "exit") and (command_name ~= "return")) then + on_values({"Unknown command", command_name}) + end + end + end + if ("exit" ~= command_name) then + return loop((command_name == "return")) + end + end + local function try_readline_21(opts, ok, readline) + if ok then + if readline.set_readline_name then + readline.set_readline_name("fennel") + end + readline.set_options({histfile = "", keeplines = 1000}) + opts.readChunk = function(parser_state) + local _863_0 = readline.readline(prompt_for((0 == parser_state["stack-size"]))) + if (nil ~= _863_0) then + local input = _863_0 + return (input .. "\n") + end + end + local completer0 = nil + opts.registerCompleter = function(repl_completer) + completer0 = repl_completer + return nil + end + local function repl_completer(text, from, to) + if completer0 then + readline.set_completion_append_character("") + return completer0(text:sub(from, to), text, from, to) + else + return {} + end + end + readline.set_complete_function(repl_completer) + return readline + end + end + local function should_use_readline_3f(opts) + return (("dumb" ~= os.getenv("TERM")) and not opts.readChunk and not opts.registerCompleter) + end + local function repl(_3foptions) + local old_root_options = utils.root.options + local _867_ = copy(_3foptions) + local opts = _867_ + local _3ffennelrc = _867_["fennelrc"] + local _ = nil + opts.fennelrc = nil + _ = nil + local readline = (should_use_readline_3f(opts) and try_readline_21(opts, pcall(require, "readline"))) + local _0 = nil + if _3ffennelrc then + _0 = _3ffennelrc() + else + _0 = nil + end + local env = specials["wrap-env"]((opts.env or rawget(_G, "_ENV") or _G)) + local callbacks = {["view-opts"] = (opts["view-opts"] or {depth = 4}), env = env, onError = (opts.onError or default_on_error), onValues = (opts.onValues or default_on_values), pp = (opts.pp or view), readChunk = (opts.readChunk or default_read_chunk)} + local save_locals_3f = (opts.saveLocals ~= false) + local byte_stream, clear_stream = nil, nil + local function _869_(_241) + return callbacks.readChunk(_241) + end + byte_stream, clear_stream = parser.granulate(_869_) + local chars = {} + local read, reset = nil, nil + local function _870_(parser_state) + local b = byte_stream(parser_state) + if b then + table.insert(chars, string.char(b)) + end + return b + end + read, reset = parser.parser(_870_) + depth = (depth + 1) + if opts.message then + callbacks.onValues({opts.message}) + end + env.___repl___ = callbacks + opts.env, opts.scope = env, compiler["make-scope"]() + opts.useMetadata = (opts.useMetadata ~= false) + if (opts.allowedGlobals == nil) then + opts.allowedGlobals = specials["current-global-names"](env) + end + if opts.init then + opts.init(opts, depth) + end + if opts.registerCompleter then + local function _876_() + local _875_0 = opts.scope + local function _877_(...) + return completer(env, _875_0, ...) + end + return _877_ + end + opts.registerCompleter(_876_()) + end + load_plugin_commands(opts.plugins) + if save_locals_3f then + local function newindex(t, k, v) + if opts.scope.manglings[k] then + return rawset(t, k, v) + end + end + env.___replLocals___ = setmetatable({}, {__newindex = newindex}) + end + local function print_values(...) + local vals = {...} + local out = {} + local pp = callbacks.pp + env._, env.__ = vals[1], vals + for i = 1, select("#", ...) do + table.insert(out, pp(vals[i], callbacks["view-opts"])) + end + return callbacks.onValues(out) + end + local function save_value(...) + env.___replLocals___["*3"] = env.___replLocals___["*2"] + env.___replLocals___["*2"] = env.___replLocals___["*1"] + env.___replLocals___["*1"] = ... + return ... + end + opts.scope.manglings["*1"], opts.scope.unmanglings._1 = "_1", "*1" + opts.scope.manglings["*2"], opts.scope.unmanglings._2 = "_2", "*2" + opts.scope.manglings["*3"], opts.scope.unmanglings._3 = "_3", "*3" + local function loop(_3fexit_next_3f) + for k in pairs(chars) do + chars[k] = nil + end + reset() + local ok, parser_not_eof_3f, form = pcall(read) + local src_string = table.concat(chars) + local readline_not_eof_3f = (not readline or (src_string ~= "(null)")) + local not_eof_3f = (readline_not_eof_3f and parser_not_eof_3f) + if not ok then + callbacks.onError("Parse", not_eof_3f) + clear_stream() + return loop() + elseif command_3f(src_string) then + return run_command_loop(src_string, read, loop, env, callbacks.onValues, callbacks.onError, opts.scope, chars, opts) + else + if not_eof_3f then + local function _881_(...) + local _882_0, _883_0 = ... + if ((_882_0 == true) and (nil ~= _883_0)) then + local src = _883_0 + local function _884_(...) + local _885_0, _886_0 = ... + if ((_885_0 == true) and (nil ~= _886_0)) then + local chunk = _886_0 + local function _887_() + return print_values(save_value(chunk())) + end + local function _888_(...) + return callbacks.onError("Runtime", ...) + end + return xpcall(_887_, _888_) + elseif ((_885_0 == false) and (nil ~= _886_0)) then + local msg = _886_0 + clear_stream() + return callbacks.onError("Compile", msg) + end + end + local function _891_(...) + local src0 = nil + if save_locals_3f then + src0 = splice_save_locals(env, src, opts.scope) + else + src0 = src + end + return pcall(specials["load-code"], src0, env) + end + return _884_(_891_(...)) + elseif ((_882_0 == false) and (nil ~= _883_0)) then + local msg = _883_0 + clear_stream() + return callbacks.onError("Compile", msg) + end + end + local function _893_() + opts["source"] = src_string + return opts + end + _881_(pcall(compiler.compile, form, _893_())) + utils.root.options = old_root_options + if _3fexit_next_3f then + return env.___replLocals___["*1"] + else + return loop() + end + end + end + end + local value = loop() + depth = (depth - 1) + if readline then + readline.save_history() + end + if opts.exit then + opts.exit(opts, depth) + end + return value + end + local repl_mt = {__index = {repl = repl}} + repl_mt.__call = function(_899_0, _3fopts) + local _900_ = _899_0 + local overrides = _900_ + local view_opts = _900_["view-opts"] + local opts = copy(_3fopts, copy(overrides)) + local _902_ + do + local _901_0 = _3fopts + if (nil ~= _901_0) then + _901_0 = _901_0["view-opts"] + end + _902_ = _901_0 + end + opts["view-opts"] = copy(_902_, copy(view_opts)) + return repl(opts) + end + return setmetatable({["view-opts"] = {}}, repl_mt) +end +package.preload["eca.nfnl.fennel.specials"] = package.preload["eca.nfnl.fennel.specials"] or function(...) + local _530_ = require("eca.nfnl.fennel.utils") + local utils = _530_ + local pack = _530_["pack"] + local unpack = _530_["unpack"] + local view = require("eca.nfnl.fennel.view") + local parser = require("eca.nfnl.fennel.parser") + local compiler = require("eca.nfnl.fennel.compiler") + local SPECIALS = compiler.scopes.global.specials + local function str1(x) + return tostring(x[1]) + end + local function wrap_env(env) + local function _531_(_, key) + if utils["string?"](key) then + return env[compiler["global-unmangling"](key)] + else + return env[key] + end + end + local function _533_(_, key, value) + if utils["string?"](key) then + env[compiler["global-unmangling"](key)] = value + return nil + else + env[key] = value + return nil + end + end + local function _535_() + local _536_ + do + local tbl_14_ = {} + for k, v in utils.stablepairs(env) do + local k_15_, v_16_ = nil, nil + local _537_ + if utils["string?"](k) then + _537_ = compiler["global-unmangling"](k) + else + _537_ = k + end + k_15_, v_16_ = _537_, v + if ((k_15_ ~= nil) and (v_16_ ~= nil)) then + tbl_14_[k_15_] = v_16_ + end + end + _536_ = tbl_14_ + end + return next, _536_, nil + end + return setmetatable({}, {__index = _531_, __newindex = _533_, __pairs = _535_}) + end + local function fennel_module_name() + return (utils.root.options.moduleName or "fennel") + end + local function current_global_names(_3fenv) + local mt = nil + do + local _540_0 = getmetatable(_3fenv) + if ((_G.type(_540_0) == "table") and (nil ~= _540_0.__pairs)) then + local mtpairs = _540_0.__pairs + local tbl_14_ = {} + for k, v in mtpairs(_3fenv) do + local k_15_, v_16_ = k, v + if ((k_15_ ~= nil) and (v_16_ ~= nil)) then + tbl_14_[k_15_] = v_16_ + end + end + mt = tbl_14_ + elseif (_540_0 == nil) then + mt = (_3fenv or _G) + else + mt = nil + end + end + local function _543_() + local tbl_17_ = {} + local i_18_ = #tbl_17_ + for k in utils.stablepairs(mt) do + local val_19_ = compiler["global-unmangling"](k) + if (nil ~= val_19_) then + i_18_ = (i_18_ + 1) + tbl_17_[i_18_] = val_19_ + end + end + return tbl_17_ + end + return (mt and _543_()) + end + local function load_code(code, _3fenv, _3ffilename) + local env = (_3fenv or rawget(_G, "_ENV") or _G) + local _545_0, _546_0 = rawget(_G, "setfenv"), rawget(_G, "loadstring") + if ((nil ~= _545_0) and (nil ~= _546_0)) then + local setfenv = _545_0 + local loadstring = _546_0 + local f = assert(loadstring(code, _3ffilename, "t")) + setfenv(f, env) + return f + else + local _ = _545_0 + return assert(load(code, _3ffilename, "t", env)) + end + end + local function v__3edocstring(tgt) + return (((compiler.metadata):get(tgt, "fnl/docstring") or "#")):gsub("\n$", ""):gsub("\n", "\n ") + end + local function doc_2a(tgt, name) + assert(("string" == type(name)), "name must be a string") + if not tgt then + return (name .. " not found") + else + local function _549_() + local _548_0 = getmetatable(tgt) + if ((_G.type(_548_0) == "table") and true) then + local __call = _548_0.__call + return ("function" == type(__call)) + end + end + if ((type(tgt) == "function") or _549_()) then + local arglist = ((compiler.metadata):get(tgt, "fnl/arglist") or {"#"}) + local elts = nil + local function _551_() + local tbl_17_ = {} + local i_18_ = #tbl_17_ + for _, a in ipairs(arglist) do + local val_19_ = tostring(a) + if (nil ~= val_19_) then + i_18_ = (i_18_ + 1) + tbl_17_[i_18_] = val_19_ + end + end + return tbl_17_ + end + elts = {name, unpack(_551_())} + return string.format("(%s)\n %s", table.concat(elts, " "), v__3edocstring(tgt)) + else + return string.format("%s\n %s", name, v__3edocstring(tgt)) + end + end + end + local function doc_special(name, arglist, docstring, _3fbody_form_3f) + for i, a in ipairs(arglist) do + if ("table" == type(a)) then + arglist[i] = ("[" .. table.concat(a, " ") .. "]") + end + end + compiler.metadata[SPECIALS[name]] = {["fnl/arglist"] = arglist, ["fnl/body-form?"] = _3fbody_form_3f, ["fnl/docstring"] = docstring} + return nil + end + local function compile_do(ast, scope, parent, _3fstart) + local start = (_3fstart or 2) + local len = #ast + local sub_scope = compiler["make-scope"](scope) + for i = start, len do + compiler.compile1(ast[i], sub_scope, parent, {nval = 0}) + end + return nil + end + SPECIALS["do"] = function(ast, scope, parent, opts, _3fstart, _3fchunk, _3fsub_scope, _3fpre_syms) + local start = (_3fstart or 2) + local sub_scope = (_3fsub_scope or compiler["make-scope"](scope)) + local chunk = (_3fchunk or {}) + local len = #ast + local retexprs = {returned = true} + utils.hook("pre-do", ast, sub_scope) + local function compile_body(outer_target, outer_tail, _3fouter_retexprs) + for i = start, len do + local subopts = {nval = (((i ~= len) and 0) or opts.nval), tail = (((i == len) and outer_tail) or nil), target = (((i == len) and outer_target) or nil)} + local _ = utils["propagate-options"](opts, subopts) + local subexprs = compiler.compile1(ast[i], sub_scope, chunk, subopts) + if (i ~= len) then + compiler["keep-side-effects"](subexprs, parent, nil, ast[i]) + end + end + compiler.emit(parent, chunk, ast) + compiler.emit(parent, "end", ast) + utils.hook("do", ast, sub_scope) + return (_3fouter_retexprs or retexprs) + end + if (opts.target or (opts.nval == 0) or opts.tail) then + compiler.emit(parent, "do", ast) + return compile_body(opts.target, opts.tail) + elseif opts.nval then + local syms = {} + for i = 1, opts.nval do + local s = ((_3fpre_syms and _3fpre_syms[i]) or compiler.gensym(scope)) + syms[i] = s + retexprs[i] = utils.expr(s, "sym") + end + local outer_target = table.concat(syms, ", ") + compiler.emit(parent, string.format("local %s", outer_target), ast) + compiler.emit(parent, "do", ast) + return compile_body(outer_target, opts.tail) + else + local fname = compiler.gensym(scope) + local fargs = nil + if scope.vararg then + fargs = "..." + else + fargs = "" + end + compiler.emit(parent, string.format("local function %s(%s)", fname, fargs), ast) + return compile_body(nil, true, utils.expr((fname .. "(" .. fargs .. ")"), "statement")) + end + end + doc_special("do", {"..."}, "Evaluate multiple forms; return last value.", true) + local function iter_args(ast) + local ast0, len, i = ast, #ast, 1 + local function _558_() + i = (1 + i) + while ((i == len) and utils["call-of?"](ast0[i], "values")) do + ast0 = ast0[i] + len = #ast0 + i = 2 + end + return ast0[i], (nil == ast0[(i + 1)]) + end + return _558_ + end + SPECIALS.values = function(ast, scope, parent) + local exprs = {} + for subast, last_3f in iter_args(ast) do + local subexprs = compiler.compile1(subast, scope, parent, {nval = (not last_3f and 1)}) + table.insert(exprs, subexprs[1]) + if last_3f then + for j = 2, #subexprs do + table.insert(exprs, subexprs[j]) + end + end + end + return exprs + end + doc_special("values", {"..."}, "Return multiple values from a function. Must be in tail position.") + local function __3estack(stack, tbl) + for k, v in pairs(tbl) do + table.insert(stack, k) + table.insert(stack, v) + end + return stack + end + local function literal_3f(val) + local res = true + if utils["list?"](val) then + res = false + elseif utils["table?"](val) then + local stack = __3estack({}, val) + for _, elt in ipairs(stack) do + if not res then break end + if utils["list?"](elt) then + res = false + elseif utils["table?"](elt) then + __3estack(stack, elt) + end + end + end + return res + end + local function compile_value(v) + local opts = {nval = 1, tail = false} + local scope = compiler["make-scope"]() + local chunk = {} + local _562_ = compiler.compile1(v, scope, chunk, opts) + local _563_ = _562_[1] + local v0 = _563_[1] + return v0 + end + local function insert_meta(meta, k, v) + local view_opts = {["escape-newlines?"] = true, ["line-length"] = math.huge, ["one-line?"] = true} + compiler.assert((type(k) == "string"), ("expected string keys in metadata table, got: %s"):format(view(k, view_opts))) + compiler.assert(literal_3f(v), ("expected literal value in metadata table, got: %s %s"):format(view(k, view_opts), view(v, view_opts))) + table.insert(meta, view(k)) + local function _564_() + if ("string" == type(v)) then + return view(v, view_opts) + else + return compile_value(v) + end + end + table.insert(meta, _564_()) + return meta + end + local function insert_arglist(meta, arg_list) + local opts = {["escape-newlines?"] = true, ["line-length"] = math.huge, ["one-line?"] = true} + local view_args = nil + do + local tbl_17_ = {} + local i_18_ = #tbl_17_ + for _, arg in ipairs(arg_list) do + local val_19_ = view(view(arg, opts)) + if (nil ~= val_19_) then + i_18_ = (i_18_ + 1) + tbl_17_[i_18_] = val_19_ + end + end + view_args = tbl_17_ + end + table.insert(meta, "\"fnl/arglist\"") + table.insert(meta, ("{" .. table.concat(view_args, ", ") .. "}")) + return meta + end + local function set_fn_metadata(f_metadata, parent, fn_name) + if utils.root.options.useMetadata then + local meta_fields = {} + for k, v in utils.stablepairs(f_metadata) do + if (k == "fnl/arglist") then + insert_arglist(meta_fields, v) + else + insert_meta(meta_fields, k, v) + end + end + if (type(utils.root.options.useMetadata) == "string") then + return compiler.emit(parent, ("%s:setall(%s, %s)"):format(utils.root.options.useMetadata, fn_name, table.concat(meta_fields, ", "))) + else + local meta_str = ("require(\"%s\").metadata"):format(fennel_module_name()) + return compiler.emit(parent, ("pcall(function() %s:setall(%s, %s) end)"):format(meta_str, fn_name, table.concat(meta_fields, ", "))) + end + end + end + local function get_fn_name(ast, scope, fn_name, _3fmulti) + if (fn_name and (fn_name[1] ~= "nil")) then + local _569_ + if not _3fmulti then + _569_ = compiler["declare-local"](fn_name, scope, ast) + else + _569_ = compiler["symbol-to-expression"](fn_name, scope)[1] + end + return _569_, not _3fmulti, 3 + else + return nil, true, 2 + end + end + local function compile_named_fn(ast, f_scope, f_chunk, parent, index, fn_name, local_3f, arg_name_list, f_metadata) + utils.hook("pre-fn", ast, f_scope, parent) + for i = (index + 1), #ast do + compiler.compile1(ast[i], f_scope, f_chunk, {nval = (((i ~= #ast) and 0) or nil), tail = (i == #ast)}) + end + local _572_ + if local_3f then + _572_ = "local function %s(%s)" + else + _572_ = "%s = function(%s)" + end + compiler.emit(parent, string.format(_572_, fn_name, table.concat(arg_name_list, ", ")), ast) + compiler.emit(parent, f_chunk, ast) + compiler.emit(parent, "end", ast) + set_fn_metadata(f_metadata, parent, fn_name) + utils.hook("fn", ast, f_scope, parent) + return utils.expr(fn_name, "sym") + end + local function compile_anonymous_fn(ast, f_scope, f_chunk, parent, index, arg_name_list, f_metadata, scope) + local fn_name = compiler.gensym(scope) + return compile_named_fn(ast, f_scope, f_chunk, parent, index, fn_name, true, arg_name_list, f_metadata) + end + local function maybe_metadata(ast, pred, handler, mt, index) + local index_2a = (index + 1) + local index_2a_before_ast_end_3f = (index_2a < #ast) + local expr = ast[index_2a] + if (index_2a_before_ast_end_3f and pred(expr)) then + return handler(mt, expr), index_2a + else + return mt, index + end + end + local function get_function_metadata(ast, arg_list, index) + local function _575_(_241, _242) + local tbl_14_ = _241 + for k, v in pairs(_242) do + local k_15_, v_16_ = k, v + if ((k_15_ ~= nil) and (v_16_ ~= nil)) then + tbl_14_[k_15_] = v_16_ + end + end + return tbl_14_ + end + local function _577_(_241, _242) + _241["fnl/docstring"] = _242 + return _241 + end + return maybe_metadata(ast, utils["kv-table?"], _575_, maybe_metadata(ast, utils["string?"], _577_, {["fnl/arglist"] = arg_list}, index)) + end + SPECIALS.fn = function(ast, scope, parent) + local f_scope = nil + do + local _578_0 = compiler["make-scope"](scope) + _578_0["vararg"] = false + f_scope = _578_0 + end + local f_chunk = {} + local fn_sym = utils["sym?"](ast[2]) + local multi = (fn_sym and utils["multi-sym?"](fn_sym[1])) + local fn_name, local_3f, index = get_fn_name(ast, scope, fn_sym, multi) + local arg_list = compiler.assert(utils["table?"](ast[index]), "expected parameters table", ast) + compiler.assert((not multi or not multi["multi-sym-method-call"]), ("unexpected multi symbol " .. tostring(fn_name)), fn_sym) + if (multi and not scope.symmeta[multi[1]] and not compiler["global-allowed?"](multi[1])) then + compiler.assert(nil, ("expected local table " .. multi[1]), ast[2]) + end + local function destructure_arg(arg) + local raw = utils.sym(compiler.gensym(scope)) + local declared = compiler["declare-local"](raw, f_scope, ast) + compiler.destructure(arg, raw, ast, f_scope, f_chunk, {declaration = true, nomulti = true, symtype = "arg"}) + return declared + end + local function destructure_amp(i) + compiler.assert((i == (#arg_list - 1)), "expected rest argument before last parameter", arg_list[(i + 1)], arg_list) + f_scope.vararg = true + compiler.destructure(arg_list[#arg_list], {utils.varg()}, ast, f_scope, f_chunk, {declaration = true, nomulti = true, symtype = "arg"}) + return "..." + end + local function get_arg_name(arg, i) + if f_scope.vararg then + return nil + elseif utils["varg?"](arg) then + compiler.assert((arg == arg_list[#arg_list]), "expected vararg as last parameter", ast) + f_scope.vararg = true + return "..." + elseif utils["sym?"](arg, "&") then + return destructure_amp(i) + elseif (utils["sym?"](arg) and (tostring(arg) ~= "nil") and not utils["multi-sym?"](tostring(arg))) then + return compiler["declare-local"](arg, f_scope, ast) + elseif utils["table?"](arg) then + return destructure_arg(arg) + else + return compiler.assert(false, ("expected symbol for function parameter: %s"):format(tostring(arg)), ast[index]) + end + end + local arg_name_list = nil + do + local tbl_17_ = {} + local i_18_ = #tbl_17_ + for i, a in ipairs(arg_list) do + local val_19_ = get_arg_name(a, i) + if (nil ~= val_19_) then + i_18_ = (i_18_ + 1) + tbl_17_[i_18_] = val_19_ + end + end + arg_name_list = tbl_17_ + end + local f_metadata, index0 = get_function_metadata(ast, arg_list, index) + if fn_name then + return compile_named_fn(ast, f_scope, f_chunk, parent, index0, fn_name, local_3f, arg_name_list, f_metadata) + else + return compile_anonymous_fn(ast, f_scope, f_chunk, parent, index0, arg_name_list, f_metadata, scope) + end + end + doc_special("fn", {"?name", "args", "?docstring", "..."}, "Function syntax. May optionally include a name and docstring or a metadata table.\nIf a name is provided, the function will be bound in the current scope.\nWhen called with the wrong number of args, excess args will be discarded\nand lacking args will be nil, use lambda for functions with nil checks.", true) + SPECIALS.lua = function(ast, _, parent) + compiler.assert(((#ast == 2) or (#ast == 3)), "expected 1 or 2 arguments", ast) + local _584_ + do + local _583_0 = utils["sym?"](ast[2]) + if (nil ~= _583_0) then + _584_ = tostring(_583_0) + else + _584_ = _583_0 + end + end + if ("nil" ~= _584_) then + table.insert(parent, {ast = ast, leaf = tostring(ast[2])}) + end + local _588_ + do + local _587_0 = utils["sym?"](ast[3]) + if (nil ~= _587_0) then + _588_ = tostring(_587_0) + else + _588_ = _587_0 + end + end + if ("nil" ~= _588_) then + return tostring(ast[3]) + end + end + local function dot(ast, scope, parent) + compiler.assert((1 < #ast), "expected table argument", ast) + local len = #ast + local lhs_node = compiler.macroexpand(ast[2], scope) + local _591_ = compiler.compile1(lhs_node, scope, parent, {nval = 1}) + local lhs = _591_[1] + if (len == 2) then + return tostring(lhs) + else + local indices = {} + for i = 3, len do + local index = ast[i] + if (utils["string?"](index) and utils["valid-lua-identifier?"](index)) then + table.insert(indices, ("." .. index)) + else + local _592_ = compiler.compile1(index, scope, parent, {nval = 1}) + local index0 = _592_[1] + table.insert(indices, ("[" .. tostring(index0) .. "]")) + end + end + if (not (utils["sym?"](lhs_node) or utils["list?"](lhs_node)) or ("nil" == tostring(lhs_node))) then + return ("(" .. tostring(lhs) .. ")" .. table.concat(indices)) + else + return (tostring(lhs) .. table.concat(indices)) + end + end + end + SPECIALS["."] = dot + doc_special(".", {"tbl", "key1", "..."}, "Look up key1 in tbl table. If more args are provided, do a nested lookup.") + SPECIALS.global = function(ast, scope, parent) + compiler.assert((#ast == 3), "expected name and value", ast) + compiler.destructure(ast[2], ast[3], ast, scope, parent, {forceglobal = true, nomulti = true, symtype = "global"}) + return nil + end + doc_special("global", {"name", "val"}, "Set name as a global with val. Deprecated.") + SPECIALS.set = function(ast, scope, parent) + compiler.assert((#ast == 3), "expected name and value", ast) + compiler.destructure(ast[2], ast[3], ast, scope, parent, {noundef = true, symtype = "set"}) + return nil + end + doc_special("set", {"name", "val"}, "Set a local variable to a new value. Only works on locals using var.") + local function set_forcibly_21_2a(ast, scope, parent) + compiler.assert((#ast == 3), "expected name and value", ast) + compiler.destructure(ast[2], ast[3], ast, scope, parent, {forceset = true, symtype = "set"}) + return nil + end + SPECIALS["set-forcibly!"] = set_forcibly_21_2a + local function local_2a(ast, scope, parent, opts) + compiler.assert(((0 == opts.nval) or opts.tail), "can't introduce local here", ast) + compiler.assert((#ast == 3), "expected name and value", ast) + compiler.destructure(ast[2], ast[3], ast, scope, parent, {declaration = true, nomulti = true, symtype = "local"}) + return nil + end + SPECIALS["local"] = local_2a + doc_special("local", {"name", "val"}, "Introduce new top-level immutable local.") + SPECIALS.var = function(ast, scope, parent, opts) + compiler.assert(((0 == opts.nval) or opts.tail), "can't introduce var here", ast) + compiler.assert((#ast == 3), "expected name and value", ast) + compiler.destructure(ast[2], ast[3], ast, scope, parent, {declaration = true, isvar = true, nomulti = true, symtype = "var"}) + return nil + end + doc_special("var", {"name", "val"}, "Introduce new mutable local.") + local function kv_3f(t) + local _596_ + do + local tbl_17_ = {} + local i_18_ = #tbl_17_ + for k in pairs(t) do + local val_19_ = nil + if ("number" ~= type(k)) then + val_19_ = k + else + val_19_ = nil + end + if (nil ~= val_19_) then + i_18_ = (i_18_ + 1) + tbl_17_[i_18_] = val_19_ + end + end + _596_ = tbl_17_ + end + return _596_[1] + end + SPECIALS.let = function(_599_0, scope, parent, opts) + local _600_ = _599_0 + local _ = _600_[1] + local bindings = _600_[2] + local ast = _600_ + compiler.assert((utils["table?"](bindings) and not kv_3f(bindings)), "expected binding sequence", (bindings or ast[1])) + compiler.assert(((#bindings % 2) == 0), "expected even number of name/value bindings", bindings) + compiler.assert((3 <= #ast), "expected body expression", ast[1]) + local pre_syms = nil + do + local tbl_17_ = {} + local i_18_ = #tbl_17_ + for _0 = 1, (opts.nval or 0) do + local val_19_ = compiler.gensym(scope) + if (nil ~= val_19_) then + i_18_ = (i_18_ + 1) + tbl_17_[i_18_] = val_19_ + end + end + pre_syms = tbl_17_ + end + local sub_scope = compiler["make-scope"](scope) + local sub_chunk = {} + for i = 1, #bindings, 2 do + compiler.destructure(bindings[i], bindings[(i + 1)], ast, sub_scope, sub_chunk, {declaration = true, nomulti = true, symtype = "let"}) + end + return SPECIALS["do"](ast, scope, parent, opts, 3, sub_chunk, sub_scope, pre_syms) + end + doc_special("let", {{"name1", "val1", "...", "nameN", "valN"}, "..."}, "Introduces a new scope in which a given set of local bindings are used.", true) + local function get_prev_line(parent) + if ("table" == type(parent)) then + return get_prev_line((parent.leaf or parent[#parent])) + else + return parent + end + end + local function needs_separator_3f(root, prev_line) + return (root:match("^%(") and prev_line and not prev_line:find(" end$")) + end + SPECIALS.tset = function(ast, scope, parent) + compiler.assert((3 < #ast), "expected table, key, and value arguments", ast) + compiler.assert(((type(ast[2]) ~= "boolean") and (type(ast[2]) ~= "number")), "cannot set field of literal value", ast) + local root = str1(compiler.compile1(ast[2], scope, parent, {nval = 1})) + local root0 = nil + if root:match("^[.{\"]") then + root0 = string.format("(%s)", root) + else + root0 = root + end + local keys = nil + do + local tbl_17_ = {} + local i_18_ = #tbl_17_ + for i = 3, (#ast - 1) do + local val_19_ = str1(compiler.compile1(ast[i], scope, parent, {nval = 1})) + if (nil ~= val_19_) then + i_18_ = (i_18_ + 1) + tbl_17_[i_18_] = val_19_ + end + end + keys = tbl_17_ + end + local value = str1(compiler.compile1(ast[#ast], scope, parent, {nval = 1})) + local fmtstr = nil + if needs_separator_3f(root0, get_prev_line(parent)) then + fmtstr = "; %s[%s] = %s" + else + fmtstr = "%s[%s] = %s" + end + return compiler.emit(parent, fmtstr:format(root0, table.concat(keys, "]["), value), ast) + end + doc_special("tset", {"tbl", "key1", "...", "keyN", "val"}, "Set the value of a table field. Deprecated in favor of set.") + local function calculate_if_target(scope, opts) + if not (opts.tail or opts.target or opts.nval) then + return "iife", true, nil + elseif (opts.nval and (opts.nval ~= 0) and not opts.target) then + local accum = {} + local target_exprs = {} + for i = 1, opts.nval do + local s = compiler.gensym(scope) + accum[i] = s + target_exprs[i] = utils.expr(s, "sym") + end + return "target", opts.tail, table.concat(accum, ", "), target_exprs + else + return "none", opts.tail, opts.target + end + end + local function if_2a(ast, scope, parent, opts) + compiler.assert((2 < #ast), "expected condition and body", ast) + if ((1 == (#ast % 2)) and (ast[(#ast - 1)] == true)) then + table.remove(ast, (#ast - 1)) + end + if (1 == (#ast % 2)) then + table.insert(ast, utils.sym("nil")) + end + if (#ast == 2) then + return SPECIALS["do"](utils.list(utils.sym("do"), ast[2]), scope, parent, opts) + else + local do_scope = compiler["make-scope"](scope) + local branches = {} + local wrapper, inner_tail, inner_target, target_exprs = calculate_if_target(scope, opts) + local body_opts = {nval = opts.nval, tail = inner_tail, target = inner_target} + local function compile_body(i) + local chunk = {} + local cscope = compiler["make-scope"](do_scope) + compiler["keep-side-effects"](compiler.compile1(ast[i], cscope, chunk, body_opts), chunk, nil, ast[i]) + return {chunk = chunk, scope = cscope} + end + for i = 2, (#ast - 1), 2 do + local condchunk = {} + local _609_ = compiler.compile1(ast[i], do_scope, condchunk, {nval = 1}) + local cond = _609_[1] + local branch = compile_body((i + 1)) + branch.cond = cond + branch.condchunk = condchunk + branch.nested = ((i ~= 2) and (next(condchunk, nil) == nil)) + table.insert(branches, branch) + end + local else_branch = compile_body(#ast) + local s = compiler.gensym(scope) + local buffer = {} + local last_buffer = buffer + for i = 1, #branches do + local branch = branches[i] + local fstr = nil + if not branch.nested then + fstr = "if %s then" + else + fstr = "elseif %s then" + end + local cond = tostring(branch.cond) + local cond_line = fstr:format(cond) + if branch.nested then + compiler.emit(last_buffer, branch.condchunk, ast) + else + for _, v in ipairs(branch.condchunk) do + compiler.emit(last_buffer, v, ast) + end + end + compiler.emit(last_buffer, cond_line, ast) + compiler.emit(last_buffer, branch.chunk, ast) + if (i == #branches) then + compiler.emit(last_buffer, "else", ast) + compiler.emit(last_buffer, else_branch.chunk, ast) + compiler.emit(last_buffer, "end", ast) + elseif not branches[(i + 1)].nested then + local next_buffer = {} + compiler.emit(last_buffer, "else", ast) + compiler.emit(last_buffer, next_buffer, ast) + compiler.emit(last_buffer, "end", ast) + last_buffer = next_buffer + end + end + if (wrapper == "iife") then + local iifeargs = ((scope.vararg and "...") or "") + compiler.emit(parent, ("local function %s(%s)"):format(tostring(s), iifeargs), ast) + compiler.emit(parent, buffer, ast) + compiler.emit(parent, "end", ast) + return utils.expr(("%s(%s)"):format(tostring(s), iifeargs), "statement") + elseif (wrapper == "none") then + for i = 1, #buffer do + compiler.emit(parent, buffer[i], ast) + end + return {returned = true} + else + compiler.emit(parent, ("local %s"):format(inner_target), ast) + for i = 1, #buffer do + compiler.emit(parent, buffer[i], ast) + end + return target_exprs + end + end + end + SPECIALS["if"] = if_2a + doc_special("if", {"cond1", "body1", "...", "condN", "bodyN"}, "Conditional form.\nTakes any number of condition/body pairs and evaluates the first body where\nthe condition evaluates to truthy. Similar to cond in other lisps.") + local function clause_3f(v) + return (utils["string?"](v) or (utils["sym?"](v) and not utils["multi-sym?"](v) and tostring(v):match("^&(.+)"))) + end + local function remove_until_condition(bindings, ast) + local _until = nil + for i = (#bindings - 1), 3, -1 do + local _615_0 = clause_3f(bindings[i]) + if ((_615_0 == false) or (_615_0 == nil)) then + elseif (nil ~= _615_0) then + local clause = _615_0 + compiler.assert(((clause == "until") and not _until), ("unexpected iterator clause: " .. clause), ast) + table.remove(bindings, i) + _until = table.remove(bindings, i) + end + end + return _until + end + local function compile_until(_3fcondition, scope, chunk) + if _3fcondition then + local _617_ = compiler.compile1(_3fcondition, scope, chunk, {nval = 1}) + local condition_lua = _617_[1] + return compiler.emit(chunk, ("if %s then break end"):format(tostring(condition_lua)), utils.expr(_3fcondition, "expression")) + end + end + local function iterator_bindings(ast) + local bindings = utils.copy(ast) + local _3funtil = remove_until_condition(bindings, ast) + local iter = table.remove(bindings) + local bindings0 = nil + if (1 == #bindings) then + bindings0 = (utils["list?"](bindings[1]) or bindings) + else + for _, b in ipairs(bindings) do + if utils["list?"](b) then + utils.warn("unexpected parens in iterator", b) + end + end + bindings0 = bindings + end + return bindings0, iter, _3funtil + end + SPECIALS.each = function(ast, scope, parent) + compiler.assert((3 <= #ast), "expected body expression", ast[1]) + compiler.assert(utils["table?"](ast[2]), "expected binding table", ast) + local sub_scope = compiler["make-scope"](scope) + local binding, iter, _3funtil_condition = iterator_bindings(ast[2]) + local destructures = {} + local deferred_scope_changes = {manglings = {}, symmeta = {}} + utils.hook("pre-each", ast, sub_scope, binding, iter, _3funtil_condition) + local function destructure_binding(v) + if utils["sym?"](v) then + return compiler["declare-local"](v, sub_scope, ast, nil, deferred_scope_changes) + else + local raw = utils.sym(compiler.gensym(sub_scope)) + destructures[raw] = v + return compiler["declare-local"](raw, sub_scope, ast) + end + end + local bind_vars = nil + do + local tbl_17_ = {} + local i_18_ = #tbl_17_ + for _, b in ipairs(binding) do + local val_19_ = destructure_binding(b) + if (nil ~= val_19_) then + i_18_ = (i_18_ + 1) + tbl_17_[i_18_] = val_19_ + end + end + bind_vars = tbl_17_ + end + local vals = compiler.compile1(iter, scope, parent) + local val_names = nil + do + local tbl_17_ = {} + local i_18_ = #tbl_17_ + for _, v in ipairs(vals) do + local val_19_ = tostring(v) + if (nil ~= val_19_) then + i_18_ = (i_18_ + 1) + tbl_17_[i_18_] = val_19_ + end + end + val_names = tbl_17_ + end + local chunk = {} + compiler.assert(bind_vars[1], "expected binding and iterator", ast) + compiler.emit(parent, ("for %s in %s do"):format(table.concat(bind_vars, ", "), table.concat(val_names, ", ")), ast) + for raw, args in utils.stablepairs(destructures) do + compiler.destructure(args, raw, ast, sub_scope, chunk, {declaration = true, nomulti = true, symtype = "each"}) + end + compiler["apply-deferred-scope-changes"](sub_scope, deferred_scope_changes, ast) + compile_until(_3funtil_condition, sub_scope, chunk) + compile_do(ast, sub_scope, chunk, 3) + compiler.emit(parent, chunk, ast) + return compiler.emit(parent, "end", ast) + end + doc_special("each", {{"vals...", "iterator"}, "..."}, "Runs the body once for each set of values provided by the given iterator.\nMost commonly used with ipairs for sequential tables or pairs for undefined\norder, but can be used with any iterator with any number of values.", true) + local function while_2a(ast, scope, parent) + local len1 = #parent + local condition = compiler.compile1(ast[2], scope, parent, {nval = 1})[1] + local len2 = #parent + local sub_chunk = {} + if (len1 ~= len2) then + for i = (len1 + 1), len2 do + table.insert(sub_chunk, parent[i]) + parent[i] = nil + end + compiler.emit(parent, "while true do", ast) + compiler.emit(sub_chunk, ("if not %s then break end"):format(condition[1]), ast) + else + compiler.emit(parent, ("while " .. tostring(condition) .. " do"), ast) + end + compile_do(ast, compiler["make-scope"](scope), sub_chunk, 3) + compiler.emit(parent, sub_chunk, ast) + return compiler.emit(parent, "end", ast) + end + SPECIALS["while"] = while_2a + doc_special("while", {"condition", "..."}, "The classic while loop. Evaluates body until a condition is non-truthy.", true) + local function for_2a(ast, scope, parent) + compiler.assert(utils["table?"](ast[2]), "expected binding table", ast) + local ranges = setmetatable(utils.copy(ast[2]), getmetatable(ast[2])) + local until_condition = remove_until_condition(ranges, ast) + local binding_sym = table.remove(ranges, 1) + local sub_scope = compiler["make-scope"](scope) + local range_args = {} + local chunk = {} + compiler.assert(utils["sym?"](binding_sym), ("unable to bind %s %s"):format(type(binding_sym), tostring(binding_sym)), ast[2]) + compiler.assert((3 <= #ast), "expected body expression", ast[1]) + compiler.assert((#ranges <= 3), "unexpected arguments", ranges) + compiler.assert((1 < #ranges), "expected range to include start and stop", ranges) + utils.hook("pre-for", ast, sub_scope, binding_sym) + for i = 1, math.min(#ranges, 3) do + range_args[i] = str1(compiler.compile1(ranges[i], scope, parent, {nval = 1})) + end + compiler.emit(parent, ("for %s = %s do"):format(compiler["declare-local"](binding_sym, sub_scope, ast), table.concat(range_args, ", ")), ast) + compile_until(until_condition, sub_scope, chunk) + compile_do(ast, sub_scope, chunk, 3) + compiler.emit(parent, chunk, ast) + return compiler.emit(parent, "end", ast) + end + SPECIALS["for"] = for_2a + doc_special("for", {{"index", "start", "stop", "?step"}, "..."}, "Numeric loop construct.\nEvaluates body once for each value between start and stop (inclusive).", true) + local function method_special_type(ast) + if (utils["string?"](ast[3]) and utils["valid-lua-identifier?"](ast[3])) then + return "native" + elseif utils["sym?"](ast[2]) then + return "nonnative" + else + return "binding" + end + end + local function native_method_call(ast, _scope, _parent, target, args) + local _626_ = ast + local _ = _626_[1] + local _0 = _626_[2] + local method_string = _626_[3] + local call_string = nil + if ((target.type == "literal") or (target.type == "varg") or ((target.type == "expression") and not (target[1]):match("[%)%]]$") and not (target[1]):match("%.[%a_][%w_]*$"))) then + call_string = "(%s):%s(%s)" + else + call_string = "%s:%s(%s)" + end + return utils.expr(string.format(call_string, tostring(target), method_string, table.concat(args, ", ")), "statement") + end + local function nonnative_method_call(ast, scope, parent, target, args) + local method_string = str1(compiler.compile1(ast[3], scope, parent, {nval = 1})) + local args0 = {tostring(target), unpack(args)} + return utils.expr(string.format("%s[%s](%s)", tostring(target), method_string, table.concat(args0, ", ")), "statement") + end + local function binding_method_call(ast, scope, parent, target, args) + local method_string = str1(compiler.compile1(ast[3], scope, parent, {nval = 1})) + local target_local = compiler.gensym(scope, "tgt") + local args0 = {target_local, unpack(args)} + compiler.emit(parent, string.format("local %s = %s", target_local, tostring(target))) + return utils.expr(string.format("(%s)[%s](%s)", target_local, method_string, table.concat(args0, ", ")), "statement") + end + local function method_call(ast, scope, parent) + compiler.assert((2 < #ast), "expected at least 2 arguments", ast) + local _628_ = compiler.compile1(ast[2], scope, parent, {nval = 1}) + local target = _628_[1] + local args = {} + for i = 4, #ast do + local subexprs = nil + local _629_ + if (i ~= #ast) then + _629_ = 1 + else + _629_ = nil + end + subexprs = compiler.compile1(ast[i], scope, parent, {nval = _629_}) + local tbl_17_ = args + local i_18_ = #tbl_17_ + for _, subexpr in ipairs(subexprs) do + local val_19_ = tostring(subexpr) + if (nil ~= val_19_) then + i_18_ = (i_18_ + 1) + tbl_17_[i_18_] = val_19_ + end + end + end + local _632_0 = method_special_type(ast) + if (_632_0 == "native") then + return native_method_call(ast, scope, parent, target, args) + elseif (_632_0 == "nonnative") then + return nonnative_method_call(ast, scope, parent, target, args) + elseif (_632_0 == "binding") then + return binding_method_call(ast, scope, parent, target, args) + end + end + SPECIALS[":"] = method_call + doc_special(":", {"tbl", "method-name", "..."}, "Call the named method on tbl with the provided args.\nMethod name doesn't have to be known at compile-time; if it is, use\n(tbl:method-name ...) instead.") + SPECIALS.comment = function(ast, _, parent) + local c = nil + local _634_ + do + local tbl_17_ = {} + local i_18_ = #tbl_17_ + for i, elt in ipairs(ast) do + local val_19_ = nil + if (i ~= 1) then + val_19_ = view(elt, {["one-line?"] = true}) + else + val_19_ = nil + end + if (nil ~= val_19_) then + i_18_ = (i_18_ + 1) + tbl_17_[i_18_] = val_19_ + end + end + _634_ = tbl_17_ + end + c = table.concat(_634_, " "):gsub("%]%]", "]\\]") + return compiler.emit(parent, ("--[[ " .. c .. " ]]"), ast) + end + doc_special("comment", {"..."}, "Comment which will be emitted in Lua output.", true) + local function hashfn_max_used(f_scope, i, max) + local max0 = nil + if f_scope.symmeta[("$" .. i)].used then + max0 = i + else + max0 = max + end + if (i < 9) then + return hashfn_max_used(f_scope, (i + 1), max0) + else + return max0 + end + end + SPECIALS.hashfn = function(ast, scope, parent) + compiler.assert((#ast == 2), "expected one argument", ast) + local f_scope = nil + do + local _639_0 = compiler["make-scope"](scope) + _639_0["vararg"] = false + _639_0["hashfn"] = true + f_scope = _639_0 + end + local f_chunk = {} + local name = compiler.gensym(scope) + local symbol = utils.sym(name) + local args = {} + compiler["declare-local"](symbol, scope, ast) + for i = 1, 9 do + args[i] = compiler["declare-local"](utils.sym(("$" .. i)), f_scope, ast) + end + local function walker(idx, node, _3fparent_node) + if utils["sym?"](node, "$...") then + f_scope.vararg = true + if _3fparent_node then + _3fparent_node[idx] = utils.varg() + return nil + else + return utils.varg() + end + else + return ((utils["list?"](node) and (not _3fparent_node or not utils["sym?"](node[1], "hashfn"))) or utils["table?"](node)) + end + end + utils["walk-tree"](ast, walker) + compiler.compile1(ast[2], f_scope, f_chunk, {tail = true}) + local max_used = hashfn_max_used(f_scope, 1, 0) + if f_scope.vararg then + compiler.assert((max_used == 0), "$ and $... in hashfn are mutually exclusive", ast) + end + local arg_str = nil + if f_scope.vararg then + arg_str = tostring(utils.varg()) + else + arg_str = table.concat(args, ", ", 1, max_used) + end + compiler.emit(parent, string.format("local function %s(%s)", name, arg_str), ast) + compiler.emit(parent, f_chunk, ast) + compiler.emit(parent, "end", ast) + return utils.expr(name, "sym") + end + doc_special("hashfn", {"..."}, "Function literal shorthand; args are either $... OR $1, $2, etc.") + local function comparator_special_type(ast) + if (3 == #ast) then + return "native" + elseif utils["every?"]({unpack(ast, 3, (#ast - 1))}, utils["idempotent-expr?"]) then + return "idempotent" + else + return "binding" + end + end + local function short_circuit_safe_3f(x, scope) + if (("table" ~= type(x)) or utils["sym?"](x) or utils["varg?"](x)) then + return true + elseif utils["table?"](x) then + local ok = true + for k, v in pairs(x) do + if not ok then break end + ok = (short_circuit_safe_3f(v, scope) and short_circuit_safe_3f(k, scope)) + end + return ok + elseif utils["list?"](x) then + if utils["sym?"](x[1]) then + local _645_0 = str1(x) + if ((_645_0 == "fn") or (_645_0 == "hashfn") or (_645_0 == "let") or (_645_0 == "local") or (_645_0 == "var") or (_645_0 == "set") or (_645_0 == "tset") or (_645_0 == "if") or (_645_0 == "each") or (_645_0 == "for") or (_645_0 == "while") or (_645_0 == "do") or (_645_0 == "lua") or (_645_0 == "global")) then + return false + elseif (((_645_0 == "<") or (_645_0 == ">") or (_645_0 == "<=") or (_645_0 == ">=") or (_645_0 == "=") or (_645_0 == "not=") or (_645_0 == "~=")) and (comparator_special_type(x) == "binding")) then + return false + else + local function _646_() + return (1 ~= x[2]) + end + if ((_645_0 == "pick-values") and _646_()) then + return false + else + local function _647_() + local call = _645_0 + return scope.macros[call] + end + if ((nil ~= _645_0) and _647_()) then + local call = _645_0 + return false + else + local function _648_() + return (method_special_type(x) == "binding") + end + if ((_645_0 == ":") and _648_()) then + return false + else + local _ = _645_0 + local ok = true + for i = 2, #x do + if not ok then break end + ok = short_circuit_safe_3f(x[i], scope) + end + return ok + end + end + end + end + else + local ok = true + for _, v in ipairs(x) do + if not ok then break end + ok = short_circuit_safe_3f(v, scope) + end + return ok + end + end + end + local function operator_special_result(ast, zero_arity, unary_prefix, padded_op, operands) + local _652_0 = #operands + if (_652_0 == 0) then + if zero_arity then + return utils.expr(zero_arity, "literal") + else + return compiler.assert(false, "Expected more than 0 arguments", ast) + end + elseif (_652_0 == 1) then + if unary_prefix then + return ("(" .. unary_prefix .. padded_op .. operands[1] .. ")") + else + return operands[1] + end + else + local _ = _652_0 + return ("(" .. table.concat(operands, padded_op) .. ")") + end + end + local function emit_short_circuit_if(ast, scope, parent, name, subast, accumulator, expr_string, setter) + if (accumulator ~= expr_string) then + compiler.emit(parent, string.format(setter, accumulator, expr_string), ast) + end + local function _657_() + if (name == "and") then + return accumulator + else + return ("not " .. accumulator) + end + end + compiler.emit(parent, ("if %s then"):format(_657_()), subast) + do + local chunk = {} + compiler.compile1(subast, scope, chunk, {nval = 1, target = accumulator}) + compiler.emit(parent, chunk) + end + return compiler.emit(parent, "end") + end + local function operator_special(name, zero_arity, unary_prefix, ast, scope, parent) + compiler.assert(not ((#ast == 2) and utils["varg?"](ast[2])), "tried to use vararg with operator", ast) + local padded_op = (" " .. name .. " ") + local operands, accumulator = {} + if utils["call-of?"](ast[#ast], "values") then + utils.warn("multiple values in operators are deprecated", ast) + end + for subast in iter_args(ast) do + if ((nil ~= next(operands)) and ((name == "or") or (name == "and")) and not short_circuit_safe_3f(subast, scope)) then + local expr_string = table.concat(operands, padded_op) + local setter = nil + if accumulator then + setter = "%s = %s" + else + setter = "local %s = %s" + end + if not accumulator then + accumulator = compiler.gensym(scope, name) + end + emit_short_circuit_if(ast, scope, parent, name, subast, accumulator, expr_string, setter) + operands = {accumulator} + else + table.insert(operands, str1(compiler.compile1(subast, scope, parent, {nval = 1}))) + end + end + return operator_special_result(ast, zero_arity, unary_prefix, padded_op, operands) + end + local function define_arithmetic_special(name, _3fzero_arity, _3funary_prefix, _3flua_name) + local _663_ + do + local _662_0 = (_3flua_name or name) + local function _664_(...) + return operator_special(_662_0, _3fzero_arity, _3funary_prefix, ...) + end + _663_ = _664_ + end + SPECIALS[name] = _663_ + return doc_special(name, {"a", "b", "..."}, "Arithmetic operator; works the same as Lua but accepts more arguments.") + end + define_arithmetic_special("+", "0", "0") + define_arithmetic_special("..", "''") + define_arithmetic_special("^") + define_arithmetic_special("-", nil, "") + define_arithmetic_special("*", "1", "1") + define_arithmetic_special("%") + define_arithmetic_special("/", nil, "1") + define_arithmetic_special("//", nil, "1") + SPECIALS["or"] = function(ast, scope, parent) + return operator_special("or", "false", nil, ast, scope, parent) + end + SPECIALS["and"] = function(ast, scope, parent) + return operator_special("and", "true", nil, ast, scope, parent) + end + doc_special("and", {"a", "b", "..."}, "Boolean operator; works the same as Lua but accepts more arguments.") + doc_special("or", {"a", "b", "..."}, "Boolean operator; works the same as Lua but accepts more arguments.") + local function bitop_special(native_name, lib_name, zero_arity, unary_prefix, ast, scope, parent) + if (#ast == 1) then + return compiler.assert(zero_arity, "Expected more than 0 arguments.", ast) + else + local len = #ast + local operands = {} + local padded_native_name = (" " .. native_name .. " ") + local prefixed_lib_name = ("bit." .. lib_name) + for i = 2, len do + local subexprs = nil + local _665_ + if (i ~= len) then + _665_ = 1 + else + _665_ = nil + end + subexprs = compiler.compile1(ast[i], scope, parent, {nval = _665_}) + local tbl_17_ = operands + local i_18_ = #tbl_17_ + for _, s in ipairs(subexprs) do + local val_19_ = tostring(s) + if (nil ~= val_19_) then + i_18_ = (i_18_ + 1) + tbl_17_[i_18_] = val_19_ + end + end + end + if (#operands == 1) then + if utils.root.options.useBitLib then + return (prefixed_lib_name .. "(" .. unary_prefix .. ", " .. operands[1] .. ")") + else + return ("(" .. unary_prefix .. padded_native_name .. operands[1] .. ")") + end + else + if utils.root.options.useBitLib then + return (prefixed_lib_name .. "(" .. table.concat(operands, ", ") .. ")") + else + return ("(" .. table.concat(operands, padded_native_name) .. ")") + end + end + end + end + local function define_bitop_special(name, zero_arity, unary_prefix, native) + local function _672_(...) + return bitop_special(native, name, zero_arity, unary_prefix, ...) + end + SPECIALS[name] = _672_ + return nil + end + define_bitop_special("lshift", nil, "1", "<<") + define_bitop_special("rshift", nil, "1", ">>") + define_bitop_special("band", "-1", "-1", "&") + define_bitop_special("bor", "0", "0", "|") + define_bitop_special("bxor", "0", "0", "~") + doc_special("lshift", {"x", "n"}, "Bitwise logical left shift of x by n bits.\nOnly works in Lua 5.3+ or LuaJIT with the --use-bit-lib flag.") + doc_special("rshift", {"x", "n"}, "Bitwise logical right shift of x by n bits.\nOnly works in Lua 5.3+ or LuaJIT with the --use-bit-lib flag.") + doc_special("band", {"x1", "x2", "..."}, "Bitwise AND of any number of arguments.\nOnly works in Lua 5.3+ or LuaJIT with the --use-bit-lib flag.") + doc_special("bor", {"x1", "x2", "..."}, "Bitwise OR of any number of arguments.\nOnly works in Lua 5.3+ or LuaJIT with the --use-bit-lib flag.") + doc_special("bxor", {"x1", "x2", "..."}, "Bitwise XOR of any number of arguments.\nOnly works in Lua 5.3+ or LuaJIT with the --use-bit-lib flag.") + SPECIALS.bnot = function(ast, scope, parent) + compiler.assert((#ast == 2), "expected one argument", ast) + local _673_ = compiler.compile1(ast[2], scope, parent, {nval = 1}) + local value = _673_[1] + if utils.root.options.useBitLib then + return ("bit.bnot(" .. tostring(value) .. ")") + else + return ("~(" .. tostring(value) .. ")") + end + end + doc_special("bnot", {"x"}, "Bitwise negation; only works in Lua 5.3+ or LuaJIT with the --use-bit-lib flag.") + doc_special("..", {"a", "b", "..."}, "String concatenation operator; works the same as Lua but accepts more arguments.") + local function native_comparator(op, _675_0, scope, parent) + local _676_ = _675_0 + local _ = _676_[1] + local lhs_ast = _676_[2] + local rhs_ast = _676_[3] + local _677_ = compiler.compile1(lhs_ast, scope, parent, {nval = 1}) + local lhs = _677_[1] + local _678_ = compiler.compile1(rhs_ast, scope, parent, {nval = 1}) + local rhs = _678_[1] + return string.format("(%s %s %s)", tostring(lhs), op, tostring(rhs)) + end + local function idempotent_comparator(op, chain_op, ast, scope, parent) + local vals = nil + do + local tbl_17_ = {} + local i_18_ = #tbl_17_ + for i = 2, #ast do + local val_19_ = str1(compiler.compile1(ast[i], scope, parent, {nval = 1})) + if (nil ~= val_19_) then + i_18_ = (i_18_ + 1) + tbl_17_[i_18_] = val_19_ + end + end + vals = tbl_17_ + end + local comparisons = nil + do + local tbl_17_ = {} + local i_18_ = #tbl_17_ + for i = 1, (#vals - 1) do + local val_19_ = string.format("(%s %s %s)", vals[i], op, vals[(i + 1)]) + if (nil ~= val_19_) then + i_18_ = (i_18_ + 1) + tbl_17_[i_18_] = val_19_ + end + end + comparisons = tbl_17_ + end + local chain = string.format(" %s ", (chain_op or "and")) + return ("(" .. table.concat(comparisons, chain) .. ")") + end + local function binding_comparator(op, chain_op, ast, scope, parent) + local binding_left = {} + local binding_right = {} + local vals = {} + local chain = string.format(" %s ", (chain_op or "and")) + for i = 2, #ast do + local compiled = str1(compiler.compile1(ast[i], scope, parent, {nval = 1})) + if (utils["idempotent-expr?"](ast[i]) or (i == 2) or (i == #ast)) then + table.insert(vals, compiled) + else + local my_sym = compiler.gensym(scope) + table.insert(binding_left, my_sym) + table.insert(binding_right, compiled) + table.insert(vals, my_sym) + end + end + compiler.emit(parent, string.format("local %s = %s", table.concat(binding_left, ", "), table.concat(binding_right, ", "), ast)) + local _682_ + do + local tbl_17_ = {} + local i_18_ = #tbl_17_ + for i = 1, (#vals - 1) do + local val_19_ = string.format("(%s %s %s)", vals[i], op, vals[(i + 1)]) + if (nil ~= val_19_) then + i_18_ = (i_18_ + 1) + tbl_17_[i_18_] = val_19_ + end + end + _682_ = tbl_17_ + end + return ("(" .. table.concat(_682_, chain) .. ")") + end + local function define_comparator_special(name, _3flua_op, _3fchain_op) + do + local op = (_3flua_op or name) + local function opfn(ast, scope, parent) + compiler.assert((2 < #ast), "expected at least two arguments", ast) + local _684_0 = comparator_special_type(ast) + if (_684_0 == "native") then + return native_comparator(op, ast, scope, parent) + elseif (_684_0 == "idempotent") then + return idempotent_comparator(op, _3fchain_op, ast, scope, parent) + elseif (_684_0 == "binding") then + return binding_comparator(op, _3fchain_op, ast, scope, parent) + else + local _ = _684_0 + return error("internal compiler error. please report this to the fennel devs.") + end + end + SPECIALS[name] = opfn + end + return doc_special(name, {"a", "b", "..."}, "Comparison operator; works the same as Lua but accepts more arguments.") + end + define_comparator_special(">") + define_comparator_special("<") + define_comparator_special(">=") + define_comparator_special("<=") + define_comparator_special("=", "==") + define_comparator_special("not=", "~=", "or") + local function define_unary_special(op, _3frealop) + local function opfn(ast, scope, parent) + compiler.assert((#ast == 2), "expected one argument", ast) + local tail = compiler.compile1(ast[2], scope, parent, {nval = 1}) + return ((_3frealop or op) .. str1(tail)) + end + SPECIALS[op] = opfn + return nil + end + define_unary_special("not", "not ") + doc_special("not", {"x"}, "Logical operator; works the same as Lua.") + define_unary_special("length", "#") + doc_special("length", {"x"}, "Returns the length of a table or string.") + SPECIALS["~="] = SPECIALS["not="] + SPECIALS["#"] = SPECIALS.length + local function compile_time_3f(scope) + return ((scope == compiler.scopes.compiler) or (scope.parent and compile_time_3f(scope.parent))) + end + SPECIALS.quote = function(ast, scope, parent) + compiler.assert((#ast == 2), "expected one argument", ast) + return compiler["do-quote"](ast[2], scope, parent, not compile_time_3f(scope)) + end + doc_special("quote", {"x"}, "Quasiquote the following form. Only works in macro/compiler scope.") + local macro_loaded = {} + local function safe_getmetatable(tbl) + local mt = getmetatable(tbl) + assert((mt ~= getmetatable("")), "Illegal metatable access!") + return mt + end + local function safe_open(filename, _3fmode) + assert(((nil == _3fmode) or _3fmode:find("^r")), ("unsafe file mode: " .. tostring(_3fmode))) + assert(not (filename:find("^/") or filename:find("%.%.")), ("unsafe file name: " .. filename)) + return io.open(filename, _3fmode) + end + local safe_require = nil + local function safe_compiler_env() + local _687_ + do + local _686_0 = rawget(_G, "utf8") + if (nil ~= _686_0) then + _687_ = utils.copy(_686_0) + else + _687_ = _686_0 + end + end + return {_VERSION = _VERSION, assert = assert, bit = rawget(_G, "bit"), error = error, getmetatable = safe_getmetatable, io = {open = safe_open}, ipairs = ipairs, math = utils.copy(math), next = next, pairs = utils.stablepairs, pcall = pcall, print = print, rawequal = rawequal, rawget = rawget, rawlen = rawget(_G, "rawlen"), rawset = rawset, require = safe_require, select = select, setmetatable = setmetatable, string = utils.copy(string), table = utils.copy(table), tonumber = tonumber, tostring = tostring, type = type, utf8 = _687_, xpcall = xpcall} + end + local function combined_mt_pairs(env) + local combined = {} + local _689_ = getmetatable(env) + local __index = _689_["__index"] + if ("table" == type(__index)) then + for k, v in pairs(__index) do + combined[k] = v + end + end + for k, v in next, env, nil do + combined[k] = v + end + return next, combined, nil + end + local function make_compiler_env(_3fast, _3fscope, _3fparent, _3fopts) + local provided = nil + do + local _691_0 = (_3fopts or utils.root.options) + if ((_G.type(_691_0) == "table") and (_691_0["compiler-env"] == "strict")) then + provided = safe_compiler_env() + elseif ((_G.type(_691_0) == "table") and (nil ~= _691_0.compilerEnv)) then + local compilerEnv = _691_0.compilerEnv + provided = compilerEnv + elseif ((_G.type(_691_0) == "table") and (nil ~= _691_0["compiler-env"])) then + local compiler_env = _691_0["compiler-env"] + provided = compiler_env + elseif ((_G.type(_691_0) == "table") and (nil ~= _691_0["extra-compiler-env"])) then + local extra_compiler_env = _691_0["extra-compiler-env"] + local tbl_14_ = safe_compiler_env() + for k, v in pairs(extra_compiler_env) do + local k_15_, v_16_ = k, v + if ((k_15_ ~= nil) and (v_16_ ~= nil)) then + tbl_14_[k_15_] = v_16_ + end + end + provided = tbl_14_ + else + local _ = _691_0 + provided = safe_compiler_env() + end + end + local env = nil + local function _694_() + return compiler.scopes.macro + end + local function _695_(symbol) + compiler.assert(compiler.scopes.macro, "must call from macro", _3fast) + return compiler.scopes.macro.manglings[tostring(symbol)] + end + local function _696_(base) + return utils.sym(compiler.gensym((compiler.scopes.macro or _3fscope), base)) + end + local function _697_(form) + compiler.assert(compiler.scopes.macro, "must call from macro", _3fast) + return compiler.macroexpand(form, compiler.scopes.macro) + end + env = {["assert-compile"] = compiler.assert, ["ast-source"] = utils["ast-source"], ["comment?"] = utils["comment?"], ["fennel-module-name"] = fennel_module_name, ["get-scope"] = _694_, ["in-scope?"] = _695_, ["list?"] = utils["list?"], ["macro-loaded"] = macro_loaded, ["multi-sym?"] = utils["multi-sym?"], ["sequence?"] = utils["sequence?"], ["sym?"] = utils["sym?"], ["table?"] = utils["table?"], ["varg?"] = utils["varg?"], _AST = _3fast, _CHUNK = _3fparent, _IS_COMPILER = true, _SCOPE = _3fscope, _SPECIALS = compiler.scopes.global.specials, _VARARG = utils.varg(), comment = utils.comment, gensym = _696_, list = utils.list, macroexpand = _697_, pack = pack, sequence = utils.sequence, sym = utils.sym, unpack = unpack, version = utils.version, view = view} + env._G = env + return setmetatable(env, {__index = provided, __newindex = provided, __pairs = combined_mt_pairs}) + end + local function _698_(...) + local tbl_17_ = {} + local i_18_ = #tbl_17_ + for c in string.gmatch((package.config or ""), "([^\n]+)") do + local val_19_ = c + if (nil ~= val_19_) then + i_18_ = (i_18_ + 1) + tbl_17_[i_18_] = val_19_ + end + end + return tbl_17_ + end + local _700_ = _698_(...) + local dirsep = _700_[1] + local pathsep = _700_[2] + local pathmark = _700_[3] + local pkg_config = {dirsep = (dirsep or "/"), pathmark = (pathmark or "?"), pathsep = (pathsep or ";")} + local function escapepat(str) + return string.gsub(str, "[^%w]", "%%%1") + end + local function search_module(modulename, _3fpathstring) + local pathsepesc = escapepat(pkg_config.pathsep) + local pattern = ("([^%s]*)%s"):format(pathsepesc, pathsepesc) + local no_dot_module = modulename:gsub("%.", pkg_config.dirsep) + local fullpath = ((_3fpathstring or utils["fennel-module"].path) .. pkg_config.pathsep) + local function try_path(path) + local filename = path:gsub(escapepat(pkg_config.pathmark), no_dot_module) + local _701_0 = io.open(filename) + if (nil ~= _701_0) then + local file = _701_0 + file:close() + return filename + else + local _ = _701_0 + return nil, ("no file '" .. filename .. "'") + end + end + local function find_in_path(start, _3ftried_paths) + local _703_0 = fullpath:match(pattern, start) + if (nil ~= _703_0) then + local path = _703_0 + local _704_0, _705_0 = try_path(path) + if (nil ~= _704_0) then + local filename = _704_0 + return filename + elseif ((_704_0 == nil) and (nil ~= _705_0)) then + local error = _705_0 + local function _707_() + local _706_0 = (_3ftried_paths or {}) + table.insert(_706_0, error) + return _706_0 + end + return find_in_path((start + #path + 1), _707_()) + end + else + local _ = _703_0 + local function _709_() + local tried_paths = table.concat((_3ftried_paths or {}), "\n\9") + if (_VERSION < "Lua 5.4") then + return ("\n\9" .. tried_paths) + else + return tried_paths + end + end + return nil, _709_() + end + end + return find_in_path(1) + end + local function make_searcher(_3foptions) + local function _712_(module_name) + local opts = utils.copy(utils.root.options) + for k, v in pairs((_3foptions or {})) do + opts[k] = v + end + opts["module-name"] = module_name + local _713_0, _714_0 = search_module(module_name, (_3foptions and _3foptions.path)) + if (nil ~= _713_0) then + local filename = _713_0 + local function _715_(...) + return utils["fennel-module"].dofile(filename, opts, ...) + end + return _715_, filename + elseif ((_713_0 == nil) and (nil ~= _714_0)) then + local error = _714_0 + return error + end + end + return _712_ + end + local function dofile_with_searcher(fennel_macro_searcher, filename, opts, ...) + local searchers = (package.loaders or package.searchers or {}) + local _ = table.insert(searchers, 1, fennel_macro_searcher) + local m = utils["fennel-module"].dofile(filename, opts, ...) + table.remove(searchers, 1) + return m + end + local function fennel_macro_searcher(module_name) + local opts = nil + do + local _717_0 = utils.copy(utils.root.options) + _717_0["module-name"] = module_name + _717_0["env"] = "_COMPILER" + _717_0["requireAsInclude"] = false + _717_0["allowedGlobals"] = nil + opts = _717_0 + end + local _718_0 = search_module(module_name, utils["fennel-module"]["macro-path"]) + if (nil ~= _718_0) then + local filename = _718_0 + local _719_ + if (opts["compiler-env"] == _G) then + local function _720_(...) + return dofile_with_searcher(fennel_macro_searcher, filename, opts, ...) + end + _719_ = _720_ + else + local function _721_(...) + return utils["fennel-module"].dofile(filename, opts, ...) + end + _719_ = _721_ + end + return _719_, filename + end + end + local function lua_macro_searcher(module_name) + local _724_0 = search_module(module_name, package.path) + if (nil ~= _724_0) then + local filename = _724_0 + local code = nil + do + local f = io.open(filename) + local function close_handlers_10_(ok_11_, ...) + f:close() + if ok_11_ then + return ... + else + return error(..., 0) + end + end + local function _726_() + return assert(f:read("*a")) + end + code = close_handlers_10_(_G.xpcall(_726_, (package.loaded.fennel or debug).traceback)) + end + local chunk = load_code(code, make_compiler_env(), filename) + return chunk, filename + end + end + local macro_searchers = {fennel_macro_searcher, lua_macro_searcher} + local function search_macro_module(modname, n) + local _728_0 = macro_searchers[n] + if (nil ~= _728_0) then + local f = _728_0 + local _729_0, _730_0 = f(modname) + if ((nil ~= _729_0) and true) then + local loader = _729_0 + local _3ffilename = _730_0 + return loader, _3ffilename + else + local _ = _729_0 + return search_macro_module(modname, (n + 1)) + end + end + end + local function sandbox_fennel_module(modname) + if ((modname == "eca.nfnl.fennel.macros") or (package and package.loaded and ("table" == type(package.loaded[modname])) and (package.loaded[modname].metadata == compiler.metadata))) then + local function _733_(_, ...) + return (compiler.metadata):setall(...) + end + return {metadata = {setall = _733_}, view = view} + end + end + local function _735_(modname) + local function _736_() + local loader, filename = search_macro_module(modname, 1) + compiler.assert(loader, (modname .. " module not found.")) + macro_loaded[modname] = loader(modname, filename) + return macro_loaded[modname] + end + return (macro_loaded[modname] or sandbox_fennel_module(modname) or _736_()) + end + safe_require = _735_ + local function add_macros(macros_2a, ast, scope) + compiler.assert(utils["table?"](macros_2a), "expected macros to be table", ast) + for k, v in pairs(macros_2a) do + compiler.assert((type(v) == "function"), "expected each macro to be function", ast) + compiler["check-binding-valid"](utils.sym(k), scope, ast, {["macro?"] = true}) + scope.macros[k] = v + end + return nil + end + local function resolve_module_name(_737_0, _scope, _parent, opts) + local _738_ = _737_0 + local second = _738_[2] + local filename = _738_["filename"] + local filename0 = (filename or (utils["table?"](second) and second.filename)) + local module_name = utils.root.options["module-name"] + local modexpr = compiler.compile(second, opts) + local modname_chunk = load_code(modexpr) + return modname_chunk(module_name, filename0) + end + SPECIALS["require-macros"] = function(ast, scope, parent, _3freal_ast) + compiler.assert((#ast == 2), "Expected one module name argument", (_3freal_ast or ast)) + local modname = resolve_module_name(ast, scope, parent, {}) + compiler.assert(utils["string?"](modname), "module name must compile to string", (_3freal_ast or ast)) + if not macro_loaded[modname] then + local loader, filename = search_macro_module(modname, 1) + compiler.assert(loader, (modname .. " module not found."), ast) + macro_loaded[modname] = compiler.assert(utils["table?"](loader(modname, filename)), "expected macros to be table", (_3freal_ast or ast)) + end + if ("import-macros" == str1(ast)) then + return macro_loaded[modname] + else + return add_macros(macro_loaded[modname], ast, scope) + end + end + doc_special("require-macros", {"macro-module-name"}, "Load given module and use its contents as macro definitions in current scope.\nDeprecated.") + local function emit_included_fennel(src, path, opts, sub_chunk) + local subscope = compiler["make-scope"](utils.root.scope.parent) + local forms = {} + if utils.root.options.requireAsInclude then + subscope.specials.require = compiler["require-include"] + end + for _, val in parser.parser(parser["string-stream"](src), path) do + table.insert(forms, val) + end + for i = 1, #forms do + local subopts = nil + if (i == #forms) then + subopts = {tail = true} + else + subopts = {nval = 0} + end + utils["propagate-options"](opts, subopts) + compiler.compile1(forms[i], subscope, sub_chunk, subopts) + end + return nil + end + local function include_path(ast, opts, path, mod, fennel_3f) + utils.root.scope.includes[mod] = "fnl/loading" + local src = nil + do + local f = assert(io.open(path)) + local function close_handlers_10_(ok_11_, ...) + f:close() + if ok_11_ then + return ... + else + return error(..., 0) + end + end + local function _744_() + return assert(f:read("*all")):gsub("[\13\n]*$", "") + end + src = close_handlers_10_(_G.xpcall(_744_, (package.loaded.fennel or debug).traceback)) + end + local ret = utils.expr(("require(\"" .. mod .. "\")"), "statement") + local target = ("package.preload[%q]"):format(mod) + local preload_str = (target .. " = " .. target .. " or function(...)") + local temp_chunk, sub_chunk = {}, {} + compiler.emit(temp_chunk, preload_str, ast) + compiler.emit(temp_chunk, sub_chunk) + compiler.emit(temp_chunk, "end", ast) + for _, v in ipairs(temp_chunk) do + table.insert(utils.root.chunk, v) + end + if fennel_3f then + emit_included_fennel(src, path, opts, sub_chunk) + else + compiler.emit(sub_chunk, src, ast) + end + utils.root.scope.includes[mod] = ret + return ret + end + local function include_circular_fallback(mod, modexpr, fallback, ast) + if (utils.root.scope.includes[mod] == "fnl/loading") then + compiler.assert(fallback, "circular include detected", ast) + return fallback(modexpr) + end + end + SPECIALS.include = function(ast, scope, parent, opts) + compiler.assert((#ast == 2), "expected one argument", ast) + local modexpr = nil + do + local _747_0, _748_0 = pcall(resolve_module_name, ast, scope, parent, opts) + if ((_747_0 == true) and (nil ~= _748_0)) then + local modname = _748_0 + modexpr = utils.expr(string.format("%q", modname), "literal") + else + local _ = _747_0 + modexpr = compiler.compile1(ast[2], scope, parent, {nval = 1})[1] + end + end + if ((modexpr.type ~= "literal") or ((modexpr[1]):byte() ~= 34)) then + if opts.fallback then + return opts.fallback(modexpr, true) + else + return compiler.assert(false, "module name must be string literal", ast) + end + else + local mod = load_code(("return " .. modexpr[1]))() + local oldmod = utils.root.options["module-name"] + local _ = nil + utils.root.options["module-name"] = mod + _ = nil + local res = nil + local function _752_() + local _751_0 = search_module(mod) + if (nil ~= _751_0) then + local fennel_path = _751_0 + return include_path(ast, opts, fennel_path, mod, true) + else + local _0 = _751_0 + local lua_path = search_module(mod, package.path) + if lua_path then + return include_path(ast, opts, lua_path, mod, false) + elseif opts.fallback then + return opts.fallback(modexpr) + else + return compiler.assert(false, ("module not found " .. mod), ast) + end + end + end + res = ((utils["member?"](mod, (utils.root.options.skipInclude or {})) and opts.fallback(modexpr, true)) or include_circular_fallback(mod, modexpr, opts.fallback, ast) or utils.root.scope.includes[mod] or _752_()) + utils.root.options["module-name"] = oldmod + return res + end + end + doc_special("include", {"module-name-literal"}, "Like require but load the target module during compilation and embed it in the\nLua output. The module must be a string literal and resolvable at compile time.") + local function eval_compiler_2a(ast, scope, parent) + local env = make_compiler_env(ast, scope, parent) + local opts = utils.copy(utils.root.options) + opts.scope = compiler["make-scope"](compiler.scopes.compiler) + opts.allowedGlobals = current_global_names(env) + return assert(load_code(compiler.compile(ast, opts), wrap_env(env)))(opts["module-name"], ast.filename) + end + SPECIALS.macros = function(ast, scope, parent) + compiler.assert((#ast == 2), "Expected one table argument", ast) + local macro_tbl = eval_compiler_2a(ast[2], scope, parent) + compiler.assert(utils["table?"](macro_tbl), "Expected one table argument", ast) + return add_macros(macro_tbl, ast, scope) + end + doc_special("macros", {"{:macro-name-1 (fn [...] ...) ... :macro-name-N macro-body-N}"}, "Define all functions in the given table as macros local to the current scope.") + SPECIALS["tail!"] = function(ast, scope, parent, opts) + compiler.assert((#ast == 2), "Expected one argument", ast) + local call = utils["list?"](compiler.macroexpand(ast[2], scope)) + local callee = tostring((call and utils["sym?"](call[1]))) + compiler.assert((call and not scope.specials[callee]), "Expected a function call as argument", ast) + compiler.assert(opts.tail, "Must be in tail position", ast) + return compiler.compile1(call, scope, parent, opts) + end + doc_special("tail!", {"body"}, "Assert that the body being called is in tail position.") + SPECIALS["pick-values"] = function(ast, scope, parent) + local n = ast[2] + local vals = utils.list(utils.sym("values"), unpack(ast, 3)) + compiler.assert((("number" == type(n)) and (0 <= n) and (n == math.floor(n))), ("Expected n to be an integer >= 0, got " .. tostring(n))) + if (1 == n) then + local _756_ = compiler.compile1(vals, scope, parent, {nval = 1}) + local _757_ = _756_[1] + local expr = _757_[1] + return {("(" .. expr .. ")")} + elseif (0 == n) then + for i = 3, #ast do + compiler["keep-side-effects"](compiler.compile1(ast[i], scope, parent, {nval = 0}), parent, nil, ast[i]) + end + return {} + else + local syms = nil + do + local tbl_17_ = utils.list() + local i_18_ = #tbl_17_ + for _ = 1, n do + local val_19_ = utils.sym(compiler.gensym(scope, "pv")) + if (nil ~= val_19_) then + i_18_ = (i_18_ + 1) + tbl_17_[i_18_] = val_19_ + end + end + syms = tbl_17_ + end + compiler.destructure(syms, vals, ast, scope, parent, {declaration = true, nomulti = true, noundef = true, symtype = "pv"}) + return syms + end + end + doc_special("pick-values", {"n", "..."}, "Evaluate to exactly n values.\n\nFor example,\n (pick-values 2 ...)\nexpands to\n (let [(_0_ _1_) ...]\n (values _0_ _1_))") + SPECIALS["eval-compiler"] = function(ast, scope, parent) + local old_first = ast[1] + ast[1] = utils.sym("do") + local val = eval_compiler_2a(ast, scope, parent) + ast[1] = old_first + return val + end + doc_special("eval-compiler", {"..."}, "Evaluate the body at compile-time. Use the macro system instead if possible.", true) + SPECIALS.unquote = function(ast) + return compiler.assert(false, "tried to use unquote outside quote", ast) + end + doc_special("unquote", {"..."}, "Evaluate the argument even if it's in a quoted form.") + return {["current-global-names"] = current_global_names, ["get-function-metadata"] = get_function_metadata, ["load-code"] = load_code, ["macro-loaded"] = macro_loaded, ["macro-searchers"] = macro_searchers, ["make-compiler-env"] = make_compiler_env, ["make-searcher"] = make_searcher, ["search-module"] = search_module, ["wrap-env"] = wrap_env, doc = doc_2a} +end +package.preload["eca.nfnl.fennel.compiler"] = package.preload["eca.nfnl.fennel.compiler"] or function(...) + local _300_ = require("eca.nfnl.fennel.utils") + local utils = _300_ + local unpack = _300_["unpack"] + local parser = require("eca.nfnl.fennel.parser") + local friend = require("eca.nfnl.fennel.friend") + local view = require("eca.nfnl.fennel.view") + local scopes = {compiler = nil, global = nil, macro = nil} + local function make_scope(_3fparent) + local parent = (_3fparent or scopes.global) + local _301_ + if parent then + _301_ = ((parent.depth or 0) + 1) + else + _301_ = 0 + end + return {["gensym-base"] = setmetatable({}, {__index = (parent and parent["gensym-base"])}), autogensyms = setmetatable({}, {__index = (parent and parent.autogensyms)}), depth = _301_, gensyms = setmetatable({}, {__index = (parent and parent.gensyms)}), hashfn = (parent and parent.hashfn), includes = setmetatable({}, {__index = (parent and parent.includes)}), macros = setmetatable({}, {__index = (parent and parent.macros)}), manglings = setmetatable({}, {__index = (parent and parent.manglings)}), parent = parent, refedglobals = {}, specials = setmetatable({}, {__index = (parent and parent.specials)}), symmeta = setmetatable({}, {__index = (parent and parent.symmeta)}), unmanglings = setmetatable({}, {__index = (parent and parent.unmanglings)}), vararg = (parent and parent.vararg)} + end + local function assert_msg(ast, msg) + local ast_tbl = nil + if ("table" == type(ast)) then + ast_tbl = ast + else + ast_tbl = {} + end + local m = getmetatable(ast) + local filename = ((m and m.filename) or ast_tbl.filename or "unknown") + local line = ((m and m.line) or ast_tbl.line or "?") + local col = ((m and m.col) or ast_tbl.col or "?") + local target = tostring((utils["sym?"](ast_tbl[1]) or ast_tbl[1] or "()")) + return string.format("%s:%s:%s: Compile error in '%s': %s", filename, line, col, target, msg) + end + local function assert_compile(condition, msg, _3fast, _3ffallback_ast) + if not condition then + local _304_ = (utils.root.options or {}) + local error_pinpoint = _304_["error-pinpoint"] + local source = _304_["source"] + local unfriendly = _304_["unfriendly"] + local ast = nil + if next(utils["ast-source"](_3fast)) then + ast = _3fast + else + ast = (_3ffallback_ast or {}) + end + if (nil == utils.hook("assert-compile", condition, msg, ast, utils.root.reset)) then + utils.root.reset() + if unfriendly then + error(assert_msg(ast, msg), 0) + else + friend["assert-compile"](condition, msg, ast, source, {["error-pinpoint"] = error_pinpoint}) + end + end + end + return condition + end + scopes.global = make_scope() + scopes.global.vararg = true + scopes.compiler = make_scope(scopes.global) + scopes.macro = scopes.global + local serialize_string = nil + do + local subst_digits = {["\\10"] = "\\n", ["\\11"] = "\\v", ["\\12"] = "\\f", ["\\13"] = "\\r", ["\\7"] = "\\a", ["\\8"] = "\\b", ["\\9"] = "\\t"} + local function _309_(str) + local function _310_(_241, _242) + if (0 == (_241:len() % 2)) then + local _311_0 = subst_digits[_242] + if (_311_0 ~= nil) then + return (_241 .. _311_0) + else + return _311_0 + end + end + end + local function _314_(_241) + return ("\\" .. _241:byte()) + end + return string.format("%q", str):gsub("\\\n", "\\n"):gsub("(\\*)(\\%d%d?%d?)", _310_):gsub("[\127-\255]", _314_) + end + serialize_string = _309_ + end + local function global_mangling(str) + if utils["valid-lua-identifier?"](str) then + return str + else + local _316_ + do + local _315_0 = utils.root.options + if (nil ~= _315_0) then + _315_0 = _315_0["global-mangle"] + end + _316_ = _315_0 + end + if (_316_ == false) then + return ("_G[%q]"):format(str) + else + local function _318_(_241) + return string.format("_%02x", _241:byte()) + end + return ("__fnl_global__" .. str:gsub("[^%w]", _318_)) + end + end + end + local function global_unmangling(identifier) + local _320_0 = string.match(identifier, "^__fnl_global__(.*)$") + if (nil ~= _320_0) then + local rest = _320_0 + local _321_0 = nil + local function _322_(_241) + return string.char(tonumber(_241:sub(2), 16)) + end + _321_0 = rest:gsub("_[%da-f][%da-f]", _322_) + return _321_0 + else + local _ = _320_0 + return identifier + end + end + local function global_allowed_3f(name) + local allowed = nil + do + local _324_0 = utils.root.options + if (nil ~= _324_0) then + _324_0 = _324_0.allowedGlobals + end + allowed = _324_0 + end + return (not allowed or utils["member?"](name, allowed)) + end + local function unique_mangling(original, mangling, scope, append) + if scope.unmanglings[mangling] then + return unique_mangling(original, (original .. append), scope, (append + 1)) + else + return mangling + end + end + local function apply_deferred_scope_changes(scope, deferred_scope_changes, ast) + for raw, mangled in pairs(deferred_scope_changes.manglings) do + assert_compile(not scope.refedglobals[mangled], ("use of global " .. raw .. " is aliased by a local"), ast) + scope.manglings[raw] = mangled + end + for raw, symmeta in pairs(deferred_scope_changes.symmeta) do + scope.symmeta[raw] = symmeta + end + return nil + end + local function combine_parts(parts, scope) + local ret = (scope.manglings[parts[1]] or global_mangling(parts[1])) + for i = 2, #parts do + if utils["valid-lua-identifier?"](parts[i]) then + if (parts["multi-sym-method-call"] and (i == #parts)) then + ret = (ret .. ":" .. parts[i]) + else + ret = (ret .. "." .. parts[i]) + end + else + ret = (ret .. "[" .. serialize_string(parts[i]) .. "]") + end + end + return ret + end + local function root_scope(scope) + return ((utils.root and utils.root.scope) or (scope.parent and root_scope(scope.parent)) or scope) + end + local function next_append(root_scope_2a) + root_scope_2a["gensym-append"] = ((root_scope_2a["gensym-append"] or 0) + 1) + return ("_" .. root_scope_2a["gensym-append"] .. "_") + end + local function gensym(scope, _3fbase, _3fsuffix) + local root_scope_2a = root_scope(scope) + local mangling = ((_3fbase or "") .. next_append(root_scope_2a) .. (_3fsuffix or "")) + while scope.unmanglings[mangling] do + mangling = ((_3fbase or "") .. next_append(root_scope_2a) .. (_3fsuffix or "")) + end + if (_3fbase and (0 < #_3fbase)) then + scope["gensym-base"][mangling] = _3fbase + end + scope.gensyms[mangling] = true + return mangling + end + local function combine_auto_gensym(parts, first) + parts[1] = first + local last = table.remove(parts) + local last2 = table.remove(parts) + local last_joiner = ((parts["multi-sym-method-call"] and ":") or ".") + table.insert(parts, (last2 .. last_joiner .. last)) + return table.concat(parts, ".") + end + local function autogensym(base, scope) + local _330_0 = utils["multi-sym?"](base) + if (nil ~= _330_0) then + local parts = _330_0 + return combine_auto_gensym(parts, autogensym(parts[1], scope)) + else + local _ = _330_0 + local function _331_() + local mangling = gensym(scope, base:sub(1, -2), "auto") + scope.autogensyms[base] = mangling + return mangling + end + return (scope.autogensyms[base] or _331_()) + end + end + local function check_binding_valid(symbol, scope, ast, _3fopts) + local name = tostring(symbol) + local part1 = nil + do + local _333_0 = utils["multi-sym?"](symbol) + if ((_G.type(_333_0) == "table") and (nil ~= _333_0[1])) then + local p = _333_0[1] + part1 = p + else + part1 = nil + end + end + local macro_3f = nil + do + local _335_0 = _3fopts + if (nil ~= _335_0) then + _335_0 = _335_0["macro?"] + end + macro_3f = _335_0 + end + assert_compile(("&" ~= name:match("[&.:]")), "invalid character: &", symbol) + assert_compile(not name:find("^%."), "invalid character: .", symbol) + assert_compile(not (scope.specials[(part1 or name)] or (not macro_3f and scope.macros[(part1 or name)])), ("local %s was overshadowed by a special form or macro"):format(name), ast) + assert_compile((not macro_3f or not part1 or not scope.macros[part1]), "tried to set multisym macro on existing macro", ast) + return assert_compile(not utils["quoted?"](symbol), string.format("macro tried to bind %s without gensym", name), symbol) + end + local function declare_local(symbol, scope, ast, _3fvar_3f, _3fdeferred_scope_changes) + check_binding_valid(symbol, scope, ast) + assert_compile(not utils["multi-sym?"](symbol), ("unexpected multi symbol " .. tostring(symbol)), ast) + local str = tostring(symbol) + local raw = nil + if (utils["lua-keyword?"](str) or str:match("^%d")) then + raw = ("_" .. str) + else + raw = str + end + local mangling = nil + local function _338_(_241) + return string.format("_%02x", _241:byte()) + end + mangling = string.gsub(string.gsub(raw, "-", "_"), "[^%w_]", _338_) + local unique = unique_mangling(mangling, mangling, scope, 0) + scope.unmanglings[unique] = (scope["gensym-base"][str] or str) + do + local target = (_3fdeferred_scope_changes or scope) + target.manglings[str] = unique + target.symmeta[str] = {symbol = symbol, var = _3fvar_3f} + end + return unique + end + local function hashfn_arg_name(name, multi_sym_parts, scope) + if not scope.hashfn then + return nil + elseif (name == "$") then + return "$1" + elseif multi_sym_parts then + if (multi_sym_parts and (multi_sym_parts[1] == "$")) then + multi_sym_parts[1] = "$1" + end + return table.concat(multi_sym_parts, ".") + end + end + local function symbol_to_expression(symbol, scope, _3freference_3f) + utils.hook("symbol-to-expression", symbol, scope, _3freference_3f) + local name = symbol[1] + local multi_sym_parts = utils["multi-sym?"](name) + local name0 = (hashfn_arg_name(name, multi_sym_parts, scope) or name) + local parts = (multi_sym_parts or {name0}) + local etype = (((1 < #parts) and "expression") or "sym") + local local_3f = scope.manglings[parts[1]] + if (local_3f and scope.symmeta[parts[1]]) then + scope.symmeta[parts[1]]["used"] = true + symbol.referent = scope.symmeta[parts[1]].symbol + end + assert_compile(not scope.macros[parts[1]], "tried to reference a macro without calling it", symbol) + assert_compile((not scope.specials[parts[1]] or ("require" == parts[1])), "tried to reference a special form without calling it", symbol) + assert_compile((not _3freference_3f or local_3f or ("_ENV" == parts[1]) or global_allowed_3f(parts[1])), ("unknown identifier: " .. tostring(parts[1])), symbol) + local function _343_() + local _342_0 = utils.root.options + if (nil ~= _342_0) then + _342_0 = _342_0.allowedGlobals + end + return _342_0 + end + if (_343_() and not local_3f and scope.parent) then + scope.parent.refedglobals[parts[1]] = true + end + return utils.expr(combine_parts(parts, scope), etype) + end + local function emit(chunk, out, _3fast) + if (type(out) == "table") then + return table.insert(chunk, out) + else + return table.insert(chunk, {ast = _3fast, leaf = out}) + end + end + local function peephole(chunk) + if chunk.leaf then + return chunk + elseif ((3 <= #chunk) and (chunk[(#chunk - 2)].leaf == "do") and not chunk[(#chunk - 1)].leaf and (chunk[#chunk].leaf == "end")) then + local kid = peephole(chunk[(#chunk - 1)]) + local new_chunk = {ast = chunk.ast} + for i = 1, (#chunk - 3) do + table.insert(new_chunk, peephole(chunk[i])) + end + for i = 1, #kid do + table.insert(new_chunk, kid[i]) + end + return new_chunk + else + local tbl_17_ = {} + local i_18_ = #tbl_17_ + for _, x in ipairs(chunk) do + local val_19_ = peephole(x) + if (nil ~= val_19_) then + i_18_ = (i_18_ + 1) + tbl_17_[i_18_] = val_19_ + end + end + return tbl_17_ + end + end + local function flatten_chunk_correlated(main_chunk, options) + local function flatten(chunk, out, last_line, file) + local last_line0 = last_line + if chunk.leaf then + out[last_line0] = ((out[last_line0] or "") .. " " .. chunk.leaf) + else + for _, subchunk in ipairs(chunk) do + if (subchunk.leaf or next(subchunk)) then + local source = utils["ast-source"](subchunk.ast) + if (file == source.filename) then + last_line0 = math.max(last_line0, (source.line or 0)) + end + last_line0 = flatten(subchunk, out, last_line0, file) + end + end + end + return last_line0 + end + local out = {} + local last = flatten(main_chunk, out, 1, options.filename) + for i = 1, last do + if (out[i] == nil) then + out[i] = "" + end + end + return table.concat(out, "\n") + end + local function flatten_chunk(file_sourcemap, chunk, tab, depth) + if chunk.leaf then + local _353_ = utils["ast-source"](chunk.ast) + local endline = _353_["endline"] + local filename = _353_["filename"] + local line = _353_["line"] + if ("end" == chunk.leaf) then + table.insert(file_sourcemap, {filename, (endline or line)}) + else + table.insert(file_sourcemap, {filename, line}) + end + return chunk.leaf + else + local tab0 = nil + do + local _355_0 = tab + if (_355_0 == true) then + tab0 = " " + elseif (_355_0 == false) then + tab0 = "" + elseif (nil ~= _355_0) then + local tab1 = _355_0 + tab0 = tab1 + elseif (_355_0 == nil) then + tab0 = "" + else + tab0 = nil + end + end + local _357_ + do + local tbl_17_ = {} + local i_18_ = #tbl_17_ + for _, c in ipairs(chunk) do + local val_19_ = nil + if (c.leaf or next(c)) then + local sub = flatten_chunk(file_sourcemap, c, tab0, (depth + 1)) + if (0 < depth) then + val_19_ = (tab0 .. sub:gsub("\n", ("\n" .. tab0))) + else + val_19_ = sub + end + else + val_19_ = nil + end + if (nil ~= val_19_) then + i_18_ = (i_18_ + 1) + tbl_17_[i_18_] = val_19_ + end + end + _357_ = tbl_17_ + end + return table.concat(_357_, "\n") + end + end + local sourcemap = {} + local function make_short_src(source) + local source0 = source:gsub("\n", " ") + if (#source0 <= 49) then + return ("[fennel \"" .. source0 .. "\"]") + else + return ("[fennel \"" .. source0:sub(1, 46) .. "...\"]") + end + end + local function flatten(chunk, options) + local chunk0 = peephole(chunk) + local indent = (options.indent or " ") + if options.correlate then + return flatten_chunk_correlated(chunk0, options), {} + else + local file_sourcemap = {} + local src = flatten_chunk(file_sourcemap, chunk0, indent, 0) + file_sourcemap.short_src = (options.filename or make_short_src((options.source or src))) + if options.filename then + file_sourcemap.key = ("@" .. options.filename) + else + file_sourcemap.key = src + end + sourcemap[file_sourcemap.key] = file_sourcemap + return src, file_sourcemap + end + end + local function make_metadata() + local function _365_(self, tgt, _3fkey) + if self[tgt] then + if (nil ~= _3fkey) then + return self[tgt][_3fkey] + else + return self[tgt] + end + end + end + local function _368_(self, tgt, key, value) + self[tgt] = (self[tgt] or {}) + self[tgt][key] = value + return tgt + end + local function _369_(self, tgt, ...) + local kv_len = select("#", ...) + local kvs = {...} + if ((kv_len % 2) ~= 0) then + error("metadata:setall() expected even number of k/v pairs") + end + self[tgt] = (self[tgt] or {}) + for i = 1, kv_len, 2 do + self[tgt][kvs[i]] = kvs[(i + 1)] + end + return tgt + end + return setmetatable({}, {__index = {get = _365_, set = _368_, setall = _369_}, __mode = "k"}) + end + local function exprs1(exprs) + local _371_ + do + local tbl_17_ = {} + local i_18_ = #tbl_17_ + for _, e in ipairs(exprs) do + local val_19_ = tostring(e) + if (nil ~= val_19_) then + i_18_ = (i_18_ + 1) + tbl_17_[i_18_] = val_19_ + end + end + _371_ = tbl_17_ + end + return table.concat(_371_, ", ") + end + local function keep_side_effects(exprs, chunk, _3fstart, ast) + for j = (_3fstart or 1), #exprs do + local subexp = exprs[j] + if ((subexp.type == "expression") and (subexp[1] ~= "nil")) then + emit(chunk, ("do local _ = %s end"):format(tostring(subexp)), ast) + elseif (subexp.type == "statement") then + local code = tostring(subexp) + local disambiguated = nil + if (code:byte() == 40) then + disambiguated = ("do end " .. code) + else + disambiguated = code + end + emit(chunk, disambiguated, ast) + end + end + return nil + end + local function handle_compile_opts(exprs, parent, opts, _3fast) + if opts.nval then + local n = opts.nval + local len = #exprs + if (n ~= len) then + if (n < len) then + keep_side_effects(exprs, parent, (n + 1), _3fast) + for i = (n + 1), len do + exprs[i] = nil + end + else + for i = (#exprs + 1), n do + exprs[i] = utils.expr("nil", "literal") + end + end + end + end + if opts.tail then + emit(parent, string.format("return %s", exprs1(exprs)), _3fast) + end + if opts.target then + local result = exprs1(exprs) + local function _379_() + if (result == "") then + return "nil" + else + return result + end + end + emit(parent, string.format("%s = %s", opts.target, _379_()), _3fast) + end + if (opts.tail or opts.target) then + return {returned = true} + else + exprs["returned"] = true + return exprs + end + end + local function find_macro(ast, scope) + local macro_2a = nil + do + local _382_0 = utils["sym?"](ast[1]) + if (_382_0 ~= nil) then + local _383_0 = tostring(_382_0) + if (_383_0 ~= nil) then + macro_2a = scope.macros[_383_0] + else + macro_2a = _383_0 + end + else + macro_2a = _382_0 + end + end + local multi_sym_parts = utils["multi-sym?"](ast[1]) + if (not macro_2a and multi_sym_parts) then + local nested_macro = utils["get-in"](scope.macros, multi_sym_parts) + assert_compile((not scope.macros[multi_sym_parts[1]] or (type(nested_macro) == "function")), "macro not found in imported macro module", ast) + return nested_macro + else + return macro_2a + end + end + local function propagate_trace_info(_387_0, _index, node) + local _388_ = _387_0 + local byteend = _388_["byteend"] + local bytestart = _388_["bytestart"] + local col = _388_["col"] + local filename = _388_["filename"] + local line = _388_["line"] + if ("table" == type(node)) then + local src = nil + if getmetatable(node) then + src = utils["ast-source"](node) + else + local _389_0 = {} + setmetatable(node, _389_0) + src = _389_0 + end + if (filename ~= src.filename) then + src.filename, src.line, src.col, src["from-macro?"] = filename, line, col, true + src.bytestart, src.byteend = bytestart, byteend + end + end + return ("table" == type(node)) + end + local function quote_literal_nils(index, node, parent) + if (parent and utils["list?"](parent)) then + for i = 1, utils.maxn(parent) do + if (nil == parent[i]) then + parent[i] = utils.sym("nil") + end + end + end + return index, node, parent + end + local function built_in_3f(m) + local found_3f = false + for _, f in pairs(scopes.global.macros) do + if found_3f then break end + found_3f = (f == m) + end + return found_3f + end + local function macro_traceback(msg) + if utils["debug-on?"]() then + return debug.traceback(msg, 2) + else + local _396_ + do + local _395_0 = nil + do + local tbl_17_ = {} + local i_18_ = #tbl_17_ + for l in debug.traceback(msg, 2):gmatch("([^\n]+)") do + if l:find("function 'fennel.compiler.macroexpand'$") then break end + local val_19_ = l + if (nil ~= val_19_) then + i_18_ = (i_18_ + 1) + tbl_17_[i_18_] = val_19_ + end + end + _395_0 = tbl_17_ + end + table.remove(_395_0) + _396_ = _395_0 + end + return table.concat(_396_, "\n") + end + end + local function macroexpand_2a(ast, scope, _3fonce) + local _399_0 = nil + if utils["list?"](ast) then + _399_0 = find_macro(ast, scope) + else + _399_0 = nil + end + if (_399_0 == false) then + return ast + elseif (nil ~= _399_0) then + local macro_2a = _399_0 + local old_scope = scopes.macro + local _ = nil + scopes.macro = scope + _ = nil + local ok, transformed = nil, nil + local function _401_() + return macro_2a(unpack(ast, 2)) + end + local function _402_() + if built_in_3f(macro_2a) then + return tostring + else + return macro_traceback + end + end + ok, transformed = xpcall(_401_, _402_()) + local function _403_(...) + return propagate_trace_info(ast, quote_literal_nils(...)) + end + utils["walk-tree"](transformed, _403_) + scopes.macro = old_scope + assert_compile(ok, transformed, ast) + utils.hook("macroexpand", ast, transformed, scope) + if (_3fonce or not transformed) then + return transformed + else + return macroexpand_2a(transformed, scope) + end + else + local _ = _399_0 + return ast + end + end + local function compile_special(ast, scope, parent, opts, special) + local exprs = (special(ast, scope, parent, opts) or utils.expr("nil", "literal")) + local exprs0 = nil + if ("table" ~= type(exprs)) then + exprs0 = utils.expr(exprs, "expression") + else + exprs0 = exprs + end + local exprs2 = nil + if utils["expr?"](exprs0) then + exprs2 = {exprs0} + else + exprs2 = exprs0 + end + if not exprs2.returned then + return handle_compile_opts(exprs2, parent, opts, ast) + elseif (opts.tail or opts.target) then + return {returned = true} + else + return exprs2 + end + end + local function callable_3f(_409_0, ctype, callee) + local _410_ = _409_0 + local call_ast = _410_[1] + if ("literal" == ctype) then + return ("\"" == string.sub(callee, 1, 1)) + else + return (utils["sym?"](call_ast) or utils["list?"](call_ast)) + end + end + local function compile_function_call(ast, scope, parent, opts, compile1, len) + local _412_ = compile1(ast[1], scope, parent, {nval = 1})[1] + local callee = _412_[1] + local ctype = _412_["type"] + local fargs = {} + assert_compile(callable_3f(ast, ctype, callee), ("cannot call literal value " .. tostring(ast[1])), ast) + for i = 2, len do + local subexprs = nil + local _413_ + if (i ~= len) then + _413_ = 1 + else + _413_ = nil + end + subexprs = compile1(ast[i], scope, parent, {nval = _413_}) + table.insert(fargs, subexprs[1]) + if (i == len) then + for j = 2, #subexprs do + table.insert(fargs, subexprs[j]) + end + else + keep_side_effects(subexprs, parent, 2, ast[i]) + end + end + local pat = nil + if ("literal" == ctype) then + pat = "(%s)(%s)" + else + pat = "%s(%s)" + end + local call = string.format(pat, tostring(callee), exprs1(fargs)) + return handle_compile_opts({utils.expr(call, "statement")}, parent, opts, ast) + end + local function compile_call(ast, scope, parent, opts, compile1) + utils.hook("call", ast, scope) + local len = #ast + local first = ast[1] + local multi_sym_parts = utils["multi-sym?"](first) + local special = (utils["sym?"](first) and scope.specials[tostring(first)]) + assert_compile((0 < len), "expected a function, macro, or special to call", ast) + if special then + return compile_special(ast, scope, parent, opts, special) + elseif (multi_sym_parts and multi_sym_parts["multi-sym-method-call"]) then + local table_with_method = table.concat({unpack(multi_sym_parts, 1, (#multi_sym_parts - 1))}, ".") + local method_to_call = multi_sym_parts[#multi_sym_parts] + local new_ast = utils.list(utils.sym(":", ast), utils.sym(table_with_method, ast), method_to_call, select(2, unpack(ast))) + return compile1(new_ast, scope, parent, opts) + else + return compile_function_call(ast, scope, parent, opts, compile1, len) + end + end + local function compile_varg(ast, scope, parent, opts) + local _418_ + if scope.hashfn then + _418_ = "use $... in hashfn" + else + _418_ = "unexpected vararg" + end + assert_compile(scope.vararg, _418_, ast) + return handle_compile_opts({utils.expr("...", "varg")}, parent, opts, ast) + end + local function compile_sym(ast, scope, parent, opts) + local multi_sym_parts = utils["multi-sym?"](ast) + assert_compile(not (multi_sym_parts and multi_sym_parts["multi-sym-method-call"]), "multisym method calls may only be in call position", ast) + local e = nil + if (ast[1] == "nil") then + e = utils.expr("nil", "literal") + else + e = symbol_to_expression(ast, scope, true) + end + return handle_compile_opts({e}, parent, opts, ast) + end + local view_opts = nil + do + local nan = tostring((0 / 0)) + local _421_ + if (45 == nan:byte()) then + _421_ = "(0/0)" + else + _421_ = "(- (0/0))" + end + local _423_ + if (45 == nan:byte()) then + _423_ = "(- (0/0))" + else + _423_ = "(0/0)" + end + view_opts = {["negative-infinity"] = "(-1/0)", ["negative-nan"] = _421_, infinity = "(1/0)", nan = _423_} + end + local function serialize_scalar(ast) + local _425_0 = type(ast) + if (_425_0 == "nil") then + return "nil" + elseif (_425_0 == "boolean") then + return tostring(ast) + elseif (_425_0 == "string") then + return serialize_string(ast) + elseif (_425_0 == "number") then + return view(ast, view_opts) + end + end + local function compile_scalar(ast, _scope, parent, opts) + return handle_compile_opts({utils.expr(serialize_scalar(ast), "literal")}, parent, opts) + end + local function compile_table(ast, scope, parent, opts, compile1) + local function escape_key(k) + if ((type(k) == "string") and utils["valid-lua-identifier?"](k)) then + return k + else + local _427_ = compile1(k, scope, parent, {nval = 1}) + local compiled = _427_[1] + return ("[" .. tostring(compiled) .. "]") + end + end + local keys = {} + local buffer = nil + do + local tbl_17_ = {} + local i_18_ = #tbl_17_ + for i, elem in ipairs(ast) do + local val_19_ = nil + do + local nval = ((nil ~= ast[(i + 1)]) and 1) + keys[i] = true + val_19_ = exprs1(compile1(elem, scope, parent, {nval = nval})) + end + if (nil ~= val_19_) then + i_18_ = (i_18_ + 1) + tbl_17_[i_18_] = val_19_ + end + end + buffer = tbl_17_ + end + do + local tbl_17_ = buffer + local i_18_ = #tbl_17_ + for k in utils.stablepairs(ast) do + local val_19_ = nil + if not keys[k] then + local _430_ = compile1(ast[k], scope, parent, {nval = 1}) + local v = _430_[1] + val_19_ = string.format("%s = %s", escape_key(k), tostring(v)) + else + val_19_ = nil + end + if (nil ~= val_19_) then + i_18_ = (i_18_ + 1) + tbl_17_[i_18_] = val_19_ + end + end + end + return handle_compile_opts({utils.expr(("{" .. table.concat(buffer, ", ") .. "}"), "expression")}, parent, opts, ast) + end + local function compile1(ast, scope, parent, _3fopts) + local opts = (_3fopts or {}) + local ast0 = macroexpand_2a(ast, scope) + if utils["list?"](ast0) then + return compile_call(ast0, scope, parent, opts, compile1) + elseif utils["varg?"](ast0) then + return compile_varg(ast0, scope, parent, opts) + elseif utils["sym?"](ast0) then + return compile_sym(ast0, scope, parent, opts) + elseif (type(ast0) == "table") then + return compile_table(ast0, scope, parent, opts, compile1) + elseif ((type(ast0) == "nil") or (type(ast0) == "boolean") or (type(ast0) == "number") or (type(ast0) == "string")) then + return compile_scalar(ast0, scope, parent, opts) + else + return assert_compile(false, ("could not compile value of type " .. type(ast0)), ast0) + end + end + local function destructure(to, from, ast, scope, parent, opts) + local opts0 = (opts or {}) + local _434_ = opts0 + local declaration = _434_["declaration"] + local forceglobal = _434_["forceglobal"] + local forceset = _434_["forceset"] + local isvar = _434_["isvar"] + local symtype = _434_["symtype"] + local symtype0 = ("_" .. (symtype or "dst")) + local setter = nil + if declaration then + setter = "local %s = %s" + else + setter = "%s = %s" + end + local deferred_scope_changes = {manglings = {}, symmeta = {}} + local function getname(symbol, ast0) + local raw = symbol[1] + assert_compile(not (opts0.nomulti and utils["multi-sym?"](raw)), ("unexpected multi symbol " .. raw), ast0) + if declaration then + return declare_local(symbol, scope, symbol, isvar, deferred_scope_changes) + else + local parts = (utils["multi-sym?"](raw) or {raw}) + local _436_ = parts + local first = _436_[1] + local meta = scope.symmeta[first] + assert_compile(not raw:find(":"), "cannot set method sym", symbol) + if ((#parts == 1) and not forceset) then + assert_compile(not (forceglobal and meta), string.format("global %s conflicts with local", tostring(symbol)), symbol) + assert_compile(not (meta and not meta.var), ("expected var " .. raw), symbol) + end + assert_compile((meta or not opts0.noundef or (scope.hashfn and ("$" == first)) or global_allowed_3f(first)), ("expected local " .. first), symbol) + if forceglobal then + assert_compile(not scope.symmeta[scope.unmanglings[raw]], ("global " .. raw .. " conflicts with local"), symbol) + scope.manglings[raw] = global_mangling(raw) + scope.unmanglings[global_mangling(raw)] = raw + local _439_ + do + local _438_0 = utils.root.options + if (nil ~= _438_0) then + _438_0 = _438_0.allowedGlobals + end + _439_ = _438_0 + end + if _439_ then + local _442_ + do + local _441_0 = utils.root.options + if (nil ~= _441_0) then + _441_0 = _441_0.allowedGlobals + end + _442_ = _441_0 + end + table.insert(_442_, raw) + end + end + return symbol_to_expression(symbol, scope)[1] + end + end + local function compile_top_target(targets) + local plen = #parent + local target = table.concat(targets, ", ") + local plast = parent[#parent] + local ret = compile1(from, scope, parent, {target = target}) + if declaration then + for pi = plen, #parent do + if (parent[pi] == plast) then + plen = pi + end + end + if ((#parent == (plen + 1)) and parent[#parent].leaf) then + parent[#parent]["leaf"] = ("local " .. parent[#parent].leaf) + else + table.insert(parent, (plen + 1), {ast = ast, leaf = ("local " .. target)}) + end + end + return ret + end + local function destructure_sym(left, rightexprs, up1, _3ftop_3f) + local lname = getname(left, up1) + check_binding_valid(left, scope, left) + if _3ftop_3f then + return compile_top_target({lname}) + else + return emit(parent, setter:format(lname, exprs1(rightexprs)), left) + end + end + local function destructure_close(left, up1) + local target = string.format("local %s ", getname(left, up1)) + return compile1(from, scope, parent, {target = target}) + end + local function dynamic_set_target(_451_0) + local _452_ = _451_0 + local _ = _452_[1] + local target = _452_[2] + local keys = {(table.unpack or unpack)(_452_, 3)} + assert_compile(utils["sym?"](target), "dynamic set needs symbol target", ast) + assert_compile(next(keys), "dynamic set needs at least one key", ast) + local keys0 = nil + do + local tbl_17_ = {} + local i_18_ = #tbl_17_ + for _0, k in ipairs(keys) do + local val_19_ = tostring(compile1(k, scope, parent, {nval = 1})[1]) + if (nil ~= val_19_) then + i_18_ = (i_18_ + 1) + tbl_17_[i_18_] = val_19_ + end + end + keys0 = tbl_17_ + end + return string.format("%s[%s]", tostring(symbol_to_expression(target, scope, true)), table.concat(keys0, "][")) + end + local function destructure_values(left, rightexprs, up1, destructure1, _3ftop_3f) + local left_names, tables = {}, {} + for i, name in ipairs(left) do + if utils["sym?"](name) then + table.insert(left_names, getname(name, up1)) + elseif utils["call-of?"](name, ".") then + table.insert(left_names, dynamic_set_target(name)) + else + local symname = gensym(scope, symtype0) + table.insert(left_names, symname) + tables[i] = {name, utils.expr(symname, "sym")} + end + end + assert_compile(left[1], "must provide at least one value", left) + if _3ftop_3f then + compile_top_target(left_names) + elseif utils["expr?"](rightexprs) then + emit(parent, setter:format(table.concat(left_names, ","), exprs1(rightexprs)), left) + else + local names = table.concat(left_names, ",") + local target = nil + if declaration then + target = ("local " .. names) + else + target = names + end + emit(parent, compile1(rightexprs, scope, parent, {target = target}), left) + end + for _, pair in utils.stablepairs(tables) do + destructure1(pair[1], {pair[2]}, left) + end + return nil + end + local unpack_fn = "function (t, k)\n return ((getmetatable(t) or {}).__fennelrest\n or function (t, k) return {(table.unpack or unpack)(t, k)} end)(t, k)\n end" + local unpack_ks = "function (t, e)\n local rest = {}\n for k, v in pairs(t) do\n if not e[k] then rest[k] = v end\n end\n return rest\n end" + local function destructure_kv_rest(s, v, left, excluded_keys, destructure1) + local exclude_str = nil + local _457_ + do + local tbl_17_ = {} + local i_18_ = #tbl_17_ + for _, k in ipairs(excluded_keys) do + local val_19_ = string.format("[%s] = true", serialize_string(k)) + if (nil ~= val_19_) then + i_18_ = (i_18_ + 1) + tbl_17_[i_18_] = val_19_ + end + end + _457_ = tbl_17_ + end + exclude_str = table.concat(_457_, ", ") + local subexpr = utils.expr(string.format(string.gsub(("(" .. unpack_ks .. ")(%s, {%s})"), "\n%s*", " "), s, exclude_str), "expression") + return destructure1(v, {subexpr}, left) + end + local function destructure_rest(s, k, left, destructure1) + local unpack_str = ("(" .. unpack_fn .. ")(%s, %s)") + local formatted = string.format(string.gsub(unpack_str, "\n%s*", " "), s, k) + local subexpr = utils.expr(formatted, "expression") + local function _459_() + local next_symbol = left[(k + 2)] + return ((nil == next_symbol) or utils["sym?"](next_symbol, "&as")) + end + assert_compile((utils["sequence?"](left) and _459_()), "expected rest argument before last parameter", left) + return destructure1(left[(k + 1)], {subexpr}, left) + end + local function optimize_table_destructure_3f(left, right) + local function _460_() + local all = next(left) + for _, d in ipairs(left) do + if not all then break end + all = ((utils["sym?"](d) and not tostring(d):find("^&")) or (utils["list?"](d) and utils["sym?"](d[1], "."))) + end + return all + end + return (utils["sequence?"](left) and utils["sequence?"](right) and _460_()) + end + local function destructure_table(left, rightexprs, top_3f, destructure1, up1) + assert_compile((("table" == type(rightexprs)) and not utils["sym?"](rightexprs, "nil")), "could not destructure literal", left) + if optimize_table_destructure_3f(left, rightexprs) then + return destructure_values(utils.list(unpack(left)), utils.list(utils.sym("values"), unpack(rightexprs)), up1, destructure1) + else + local right = nil + do + local _461_0 = nil + if top_3f then + _461_0 = exprs1(compile1(from, scope, parent)) + else + _461_0 = exprs1(rightexprs) + end + if (_461_0 == "") then + right = "nil" + elseif (nil ~= _461_0) then + local right0 = _461_0 + right = right0 + else + right = nil + end + end + local s = nil + if utils["sym?"](rightexprs) then + s = right + else + s = gensym(scope, symtype0) + end + local excluded_keys = {} + if not utils["sym?"](rightexprs) then + emit(parent, string.format("local %s = %s", s, right), left) + end + for k, v in utils.stablepairs(left) do + if not (("number" == type(k)) and tostring(left[(k - 1)]):find("^&")) then + if utils["sym?"](k, "&") then + destructure_kv_rest(s, v, left, excluded_keys, destructure1) + elseif utils["sym?"](v, "&") then + destructure_rest(s, k, left, destructure1) + elseif utils["sym?"](k, "&as") then + destructure_sym(v, {utils.expr(tostring(s))}, left) + elseif (utils["sequence?"](left) and utils["sym?"](v, "&as")) then + local _, next_sym, trailing = select(k, unpack(left)) + assert_compile((nil == trailing), "expected &as argument before last parameter", left) + destructure_sym(next_sym, {utils.expr(tostring(s))}, left) + else + local subexpr = nil + if ((type(k) == "string") and utils["valid-lua-identifier?"](k)) then + subexpr = ("%s.%s"):format(s, k) + else + local key = serialize_scalar(k) + assert_compile(key, "expected key to be a literal", key) + subexpr = ("%s[%s]"):format(s, key) + end + if (type(k) == "string") then + table.insert(excluded_keys, k) + end + destructure1(v, utils.expr(subexpr, "expression"), left) + end + end + end + return nil + end + end + local function destructure1(left, rightexprs, up1, top_3f) + if (utils["sym?"](left) and left["to-be-closed"]) then + destructure_close(left, up1) + elseif (utils["sym?"](left) and (left[1] ~= "nil")) then + destructure_sym(left, rightexprs, up1, top_3f) + elseif utils["table?"](left) then + destructure_table(left, rightexprs, top_3f, destructure1, up1) + elseif utils["call-of?"](left, ".") then + destructure_values({left}, rightexprs, up1, destructure1) + elseif utils["list?"](left) then + assert_compile(top_3f, "can't nest multi-value destructuring", left) + destructure_values(left, rightexprs, up1, destructure1, true) + else + assert_compile(false, ("unable to bind %s %s"):format(type(left), tostring(left)), up1[2], up1) + end + return (top_3f and {returned = true}) + end + local ret = destructure1(to, from, ast, true) + utils.hook("destructure", from, to, scope, opts0) + apply_deferred_scope_changes(scope, deferred_scope_changes, ast) + return ret + end + local function require_include(ast, scope, parent, opts) + opts.fallback = function(e, no_warn) + if not no_warn then + utils.warn(("include module not found, falling back to require: %s"):format(tostring(e)), ast) + end + return utils.expr(string.format("require(%s)", tostring(e)), "statement") + end + return scopes.global.specials.include(ast, scope, parent, opts) + end + local function with_open_2a(_473_0, scope, parent, opts) + local _474_ = _473_0 + local _ = _474_[1] + local bindings = _474_[2] + local ast = _474_ + assert_compile(utils["sequence?"](bindings), (bindings or ast[1])) + for i = 1, #bindings, 2 do + assert_compile(utils["sym?"](bindings[i]), "with-open only allows symbols in bindings") + bindings[i]["to-be-closed"] = true + end + return scope.specials.let(ast, scope, parent, opts) + end + local function compile_asts(asts, options) + local opts = utils.copy(options) + local scope = nil + if ("_COMPILER" == opts.scope) then + scope = scopes.compiler + elseif opts.scope then + scope = opts.scope + else + scope = make_scope(scopes.global) + end + local chunk = {} + if opts.requireAsInclude then + scope.specials.require = require_include + end + if opts.toBeClosed then + scope.macros["with-open"] = false + scope.specials["with-open"] = with_open_2a + end + if opts.assertAsRepl then + scope.macros.assert = scope.macros["assert-repl"] + end + if opts.lambdaAsFn then + scope.macros.lambda = false + scope.macros["\206\187"] = false + scope.specials.lambda = scope.specials.fn + scope.specials["\206\187"] = scope.specials.fn + end + local _480_ = utils.root + _480_["set-reset"](_480_) + utils.root.chunk, utils.root.scope, utils.root.options = chunk, scope, opts + for i = 1, #asts do + local exprs = compile1(asts[i], scope, chunk, {nval = (((i < #asts) and 0) or nil), tail = (i == #asts)}) + keep_side_effects(exprs, chunk, nil, asts[i]) + if (i == #asts) then + utils.hook("chunk", asts[i], scope) + end + end + utils.root.reset() + return flatten(chunk, opts) + end + local function compile_stream(stream, _3fopts) + local opts = (_3fopts or {}) + local asts = nil + do + local tbl_17_ = {} + local i_18_ = #tbl_17_ + for _, ast in parser.parser(stream, opts.filename, opts) do + local val_19_ = ast + if (nil ~= val_19_) then + i_18_ = (i_18_ + 1) + tbl_17_[i_18_] = val_19_ + end + end + asts = tbl_17_ + end + return compile_asts(asts, opts) + end + local function compile_string(str, _3fopts) + return compile_stream(parser["string-stream"](str, _3fopts), _3fopts) + end + local function compile(from, _3fopts) + local _483_0 = type(from) + if (_483_0 == "userdata") then + local function _484_() + local _485_0 = from:read(1) + if (nil ~= _485_0) then + return _485_0:byte() + else + return _485_0 + end + end + return compile_stream(_484_, _3fopts) + elseif (_483_0 == "function") then + return compile_stream(from, _3fopts) + else + local _ = _483_0 + return compile_asts({from}, _3fopts) + end + end + local function traceback_frame(info) + if ((info.what == "C") and info.name) then + return string.format("\9[C]: in function '%s'", info.name) + elseif (info.what == "C") then + return "\9[C]: in ?" + else + local remap = sourcemap[info.source] + if (remap and remap[info.currentline]) then + if ((remap[info.currentline][1] or "unknown") ~= "unknown") then + info.short_src = sourcemap[("@" .. remap[info.currentline][1])].short_src + else + info.short_src = remap.short_src + end + info.currentline = (remap[info.currentline][2] or -1) + end + if (info.what == "Lua") then + local function _490_() + if info.name then + return ("'" .. info.name .. "'") + else + return "?" + end + end + return string.format("\9%s:%d: in function %s", info.short_src, info.currentline, _490_()) + elseif (info.short_src == "(tail call)") then + return " (tail call)" + else + return string.format("\9%s:%d: in main chunk", info.short_src, info.currentline) + end + end + end + local function trace_adjust_msg(msg) + local function _493_(...) + local _494_0, _495_0, _496_0 = ... + if ((nil ~= _494_0) and (nil ~= _495_0) and (nil ~= _496_0)) then + local file = _494_0 + local line = _495_0 + local rest = _496_0 + local function _497_(...) + local _498_0 = ... + if ((_G.type(_498_0) == "table") and true and (nil ~= _498_0[2])) then + local _ = _498_0[1] + local newline = _498_0[2] + return string.format("%s:%s:%s", file, newline, rest) + else + local _ = _498_0 + return msg + end + end + local function _501_(...) + local _500_0 = sourcemap + if (nil ~= _500_0) then + _500_0 = _500_0[("@" .. file)] + end + if (nil ~= _500_0) then + _500_0 = _500_0[tonumber(line)] + end + return _500_0 + end + return _497_(_501_(...)) + else + local _ = _494_0 + return msg + end + end + return _493_(msg:match("^([^:]*):(%d+):(.*)")) + end + local lua_getinfo = (_G.debug and _G.debug.getinfo) + local function traceback(_3fmsg, _3fstart) + local _505_0 = type(_3fmsg) + if ((_505_0 == "nil") or (_505_0 == "string")) then + local msg = (_3fmsg or "") + if ((msg:find("^%g+:%d+:%d+: Compile error:.*") or msg:find("^%g+:%d+:%d+: Parse error:.*")) and not utils["debug-on?"]("trace")) then + return msg + else + local lines = {trace_adjust_msg(msg), "stack traceback:"} + for level = (_3fstart or 2), 999 do + if lines["done?"] then break end + local _506_0 = (lua_getinfo and lua_getinfo(level, "Sln")) + if (_506_0 == nil) then + lines["done?"] = true + elseif (nil ~= _506_0) then + local info = _506_0 + table.insert(lines, traceback_frame(info)) + end + end + return table.concat(lines, "\n") + end + else + local _ = _505_0 + return _3fmsg + end + end + local function getinfo(thread_or_level, ...) + local thread_or_level0 = nil + if ("number" == type(thread_or_level)) then + thread_or_level0 = (1 + thread_or_level) + else + thread_or_level0 = thread_or_level + end + local info = (lua_getinfo and lua_getinfo(thread_or_level0, ...)) + local mapped = (info and sourcemap[info.source]) + if mapped then + for _, key in ipairs({"currentline", "linedefined", "lastlinedefined"}) do + local mapped_value = nil + do + local _511_0 = mapped + if (nil ~= _511_0) then + _511_0 = _511_0[info[key]] + end + if (nil ~= _511_0) then + _511_0 = _511_0[2] + end + mapped_value = _511_0 + end + if (info[key] and mapped_value) then + info[key] = mapped_value + end + end + if info.activelines then + local tbl_14_ = {} + for line in pairs(info.activelines) do + local k_15_, v_16_ = mapped[line][2], true + if ((k_15_ ~= nil) and (v_16_ ~= nil)) then + tbl_14_[k_15_] = v_16_ + end + end + info.activelines = tbl_14_ + end + if (info.what == "Lua") then + info.what = "Fennel" + end + end + return info + end + local function mixed_concat(t, joiner) + local seen = {} + local ret, s = "", "" + for k, v in ipairs(t) do + table.insert(seen, k) + ret = (ret .. s .. v) + s = joiner + end + for k, v in utils.stablepairs(t) do + if not seen[k] then + ret = (ret .. s .. "[" .. k .. "]" .. "=" .. v) + s = joiner + end + end + return ret + end + local function do_quote(form, scope, parent, runtime_3f) + local function quote_all(form0, _3fdiscard_non_numbers) + local tbl_14_ = {} + for k, v in utils.stablepairs(form0) do + local k_15_, v_16_ = nil, nil + if (type(k) == "number") then + k_15_, v_16_ = k, do_quote(v, scope, parent, runtime_3f) + elseif not _3fdiscard_non_numbers then + k_15_, v_16_ = do_quote(k, scope, parent, runtime_3f), do_quote(v, scope, parent, runtime_3f) + else + k_15_, v_16_ = nil + end + if ((k_15_ ~= nil) and (v_16_ ~= nil)) then + tbl_14_[k_15_] = v_16_ + end + end + return tbl_14_ + end + if utils["varg?"](form) then + assert_compile(not runtime_3f, "quoted ... may only be used at compile time", form) + return "_VARARG" + elseif utils["sym?"](form) then + local filename = nil + if form.filename then + filename = string.format("%q", form.filename) + else + filename = "nil" + end + local symstr = tostring(form) + assert_compile(not runtime_3f, "symbols may only be used at compile time", form) + if (symstr:find("#$") or symstr:find("#[:.]")) then + return string.format("_G.sym('%s', {filename=%s, line=%s})", autogensym(symstr, scope), filename, (form.line or "nil")) + else + return string.format("_G.sym('%s', {quoted=true, filename=%s, line=%s})", symstr, filename, (form.line or "nil")) + end + elseif utils["call-of?"](form, "unquote") then + local res = unpack(compile1(form[2], scope, parent)) + return res[1] + elseif utils["list?"](form) then + local mapped = quote_all(form, true) + local filename = nil + if form.filename then + filename = string.format("%q", form.filename) + else + filename = "nil" + end + assert_compile(not runtime_3f, "lists may only be used at compile time", form) + return string.format(("setmetatable({filename=%s, line=%s, bytestart=%s, %s}" .. ", getmetatable(_G.list()))"), filename, (form.line or "nil"), (form.bytestart or "nil"), mixed_concat(mapped, ", ")) + elseif utils["sequence?"](form) then + local mapped_str = mixed_concat(quote_all(form), ", ") + local source = getmetatable(form) + local filename = nil + if source.filename then + filename = ("%q"):format(source.filename) + else + filename = "nil" + end + if runtime_3f then + return string.format("{%s}", mapped_str) + else + return string.format("setmetatable({%s}, {filename=%s, line=%s, sequence=%s})", mapped_str, filename, (source.line or "nil"), "(getmetatable(_G.sequence()))['sequence']") + end + elseif (type(form) == "table") then + local source = getmetatable(form) + local filename = nil + if source.filename then + filename = string.format("%q", source.filename) + else + filename = "nil" + end + local function _528_() + if source then + return source.line + else + return "nil" + end + end + return string.format("setmetatable({%s}, {filename=%s, line=%s})", mixed_concat(quote_all(form), ", "), filename, _528_()) + elseif (type(form) == "string") then + return serialize_string(form) + else + return tostring(form) + end + end + return {["apply-deferred-scope-changes"] = apply_deferred_scope_changes, ["check-binding-valid"] = check_binding_valid, ["compile-stream"] = compile_stream, ["compile-string"] = compile_string, ["declare-local"] = declare_local, ["do-quote"] = do_quote, ["global-allowed?"] = global_allowed_3f, ["global-mangling"] = global_mangling, ["global-unmangling"] = global_unmangling, ["keep-side-effects"] = keep_side_effects, ["make-scope"] = make_scope, ["require-include"] = require_include, ["symbol-to-expression"] = symbol_to_expression, assert = assert_compile, autogensym = autogensym, compile = compile, compile1 = compile1, destructure = destructure, emit = emit, gensym = gensym, getinfo = getinfo, macroexpand = macroexpand_2a, metadata = make_metadata(), scopes = scopes, sourcemap = sourcemap, traceback = traceback} +end +package.preload["eca.nfnl.fennel.friend"] = package.preload["eca.nfnl.fennel.friend"] or function(...) + local _195_ = require("eca.nfnl.fennel.utils") + local utils = _195_ + local unpack = _195_["unpack"] + local utf8_ok_3f, utf8 = pcall(require, "utf8") + local suggestions = {} + local function pal(k, v) + suggestions[k] = v + return nil + end + pal("$ and $... in hashfn are mutually exclusive", {"modifying the hashfn so it only contains $... or $, $1, $2, $3, etc"}) + pal("can't introduce (.*) here", {"declaring the local at the top-level"}) + pal("can't start multisym segment with a digit", {"removing the digit", "adding a non-digit before the digit"}) + pal("cannot call literal value", {"checking for typos", "checking for a missing function name", "making sure to use prefix operators, not infix"}) + pal("could not compile value of type ", {"debugging the macro you're calling to return a list or table"}) + pal("could not read number (.*)", {"removing the non-digit character", "beginning the identifier with a non-digit if it is not meant to be a number"}) + pal("expected a function.* to call", {"removing the empty parentheses", "using square brackets if you want an empty table"}) + pal("expected at least one pattern/body pair", {"adding a pattern and a body to execute when the pattern matches"}) + pal("expected binding and iterator", {"making sure you haven't omitted a local name or iterator"}) + pal("expected binding sequence", {"placing a table here in square brackets containing identifiers to bind"}) + pal("expected body expression", {"putting some code in the body of this form after the bindings"}) + pal("expected each macro to be function", {"ensuring that the value for each key in your macros table contains a function", "avoid defining nested macro tables"}) + pal("expected even number of name/value bindings", {"finding where the identifier or value is missing"}) + pal("expected even number of pattern/body pairs", {"checking that every pattern has a body to go with it", "adding _ before the final body"}) + pal("expected even number of values in table literal", {"removing a key", "adding a value"}) + pal("expected key to be a literal", {"using . instead of destructuring", "checking for typos"}) + pal("expected local", {"looking for a typo", "looking for a local which is used out of its scope"}) + pal("expected macros to be table", {"ensuring your macro definitions return a table"}) + pal("expected parameters", {"adding function parameters as a list of identifiers in brackets"}) + pal("expected range to include start and stop", {"adding missing arguments"}) + pal("expected rest argument before last parameter", {"moving & to right before the final identifier when destructuring"}) + pal("expected symbol for function parameter: (.*)", {"changing %s to an identifier instead of a literal value"}) + pal("expected var (.*)", {"declaring %s using var instead of let/local", "introducing a new local instead of changing the value of %s"}) + pal("expected vararg as last parameter", {"moving the \"...\" to the end of the parameter list"}) + pal("expected whitespace before opening delimiter", {"adding whitespace"}) + pal("global (.*) conflicts with local", {"renaming local %s"}) + pal("invalid character: (.)", {"deleting or replacing %s", "avoiding reserved characters like \", \\, ', ~, ;, @, `, and comma"}) + pal("local (.*) was overshadowed by a special form or macro", {"renaming local %s"}) + pal("macro not found in macro module", {"checking the keys of the imported macro module's returned table"}) + pal("macro tried to bind (.*) without gensym", {"changing to %s# when introducing identifiers inside macros"}) + pal("malformed multisym", {"ensuring each period or colon is not followed by another period or colon"}) + pal("may only be used at compile time", {"moving this to inside a macro if you need to manipulate symbols/lists", "using square brackets instead of parens to construct a table"}) + pal("method must be last component", {"using a period instead of a colon for field access", "removing segments after the colon", "making the method call, then looking up the field on the result"}) + pal("mismatched closing delimiter (.), expected (.)", {"replacing %s with %s", "deleting %s", "adding matching opening delimiter earlier"}) + pal("missing subject", {"adding an item to operate on"}) + pal("multisym method calls may only be in call position", {"using a period instead of a colon to reference a table's fields", "putting parens around this"}) + pal("tried to reference a macro without calling it", {"renaming the macro so as not to conflict with locals"}) + pal("tried to reference a special form without calling it", {"making sure to use prefix operators, not infix", "wrapping the special in a function if you need it to be first class"}) + pal("tried to use unquote outside quote", {"moving the form to inside a quoted form", "removing the comma"}) + pal("tried to use vararg with operator", {"accumulating over the operands"}) + pal("unable to bind (.*)", {"replacing the %s with an identifier"}) + pal("unexpected arguments", {"removing an argument", "checking for typos"}) + pal("unexpected closing delimiter (.)", {"deleting %s", "adding matching opening delimiter earlier"}) + pal("unexpected iterator clause", {"removing an argument", "checking for typos"}) + pal("unexpected multi symbol (.*)", {"removing periods or colons from %s"}) + pal("unexpected vararg", {"putting \"...\" at the end of the fn parameters if the vararg was intended"}) + pal("unknown identifier: (.*)", {"looking to see if there's a typo", "using the _G table instead, eg. _G.%s if you really want a global", "moving this code to somewhere that %s is in scope", "binding %s as a local in the scope of this code"}) + pal("unused local (.*)", {"renaming the local to _%s if it is meant to be unused", "fixing a typo so %s is used", "disabling the linter which checks for unused locals"}) + pal("use of global (.*) is aliased by a local", {"renaming local %s", "refer to the global using _G.%s instead of directly"}) + local function suggest(msg) + local s = nil + for pat, sug in pairs(suggestions) do + if s then break end + local matches = {msg:match(pat)} + if next(matches) then + local tbl_17_ = {} + local i_18_ = #tbl_17_ + for _, s0 in ipairs(sug) do + local val_19_ = s0:format(unpack(matches)) + if (nil ~= val_19_) then + i_18_ = (i_18_ + 1) + tbl_17_[i_18_] = val_19_ + end + end + s = tbl_17_ + else + s = nil + end + end + return s + end + local function read_line(filename, line, _3fsource) + if _3fsource then + local matcher = string.gmatch((_3fsource .. "\n"), "(.-)(\13?\n)") + for _ = 2, line do + matcher() + end + return matcher() + else + local f = assert(_G.io.open(filename)) + local function close_handlers_10_(ok_11_, ...) + f:close() + if ok_11_ then + return ... + else + return error(..., 0) + end + end + local function _199_() + for _ = 2, line do + f:read() + end + return f:read() + end + return close_handlers_10_(_G.xpcall(_199_, (package.loaded.fennel or debug).traceback)) + end + end + local function sub(str, start, _end) + if ((_end < start) or (#str < start)) then + return "" + elseif utf8_ok_3f then + return string.sub(str, utf8.offset(str, start), ((utf8.offset(str, (_end + 1)) or (utf8.len(str) + 1)) - 1)) + else + return string.sub(str, start, math.min(_end, str:len())) + end + end + local function highlight_line(codeline, col, _3fendcol, _202_0) + local _203_ = _202_0 + local error_pinpoint = _203_["error-pinpoint"] + if ((false == error_pinpoint) or (os and os.getenv and os.getenv("NO_COLOR"))) then + return codeline + else + local endcol = (_3fendcol or col) + local eol = nil + if utf8_ok_3f then + eol = utf8.len(codeline) + else + eol = string.len(codeline) + end + local _205_ = (error_pinpoint or {"\27[7m", "\27[0m"}) + local open = _205_[1] + local close = _205_[2] + return (sub(codeline, 1, col) .. open .. sub(codeline, (col + 1), (endcol + 1)) .. close .. sub(codeline, (endcol + 2), eol)) + end + end + local function friendly_msg(msg, _207_0, _3fsource, _3fopts) + local _208_ = _207_0 + local col = _208_["col"] + local endcol = _208_["endcol"] + local endline = _208_["endline"] + local filename = _208_["filename"] + local line = _208_["line"] + local ok, codeline = pcall(read_line, filename, line, _3fsource) + local endcol0 = nil + if (ok and codeline and (line ~= endline)) then + endcol0 = #codeline + else + endcol0 = endcol + end + local out = {msg, ""} + if (ok and codeline) then + if col then + table.insert(out, highlight_line(codeline, col, endcol0, (_3fopts or {}))) + else + table.insert(out, codeline) + end + end + for _, suggestion in ipairs((suggest(msg) or {})) do + table.insert(out, ("* Try %s."):format(suggestion)) + end + return table.concat(out, "\n") + end + local function assert_compile(condition, msg, ast, _3fsource, _3fopts) + if not condition then + local _212_ = utils["ast-source"](ast) + local col = _212_["col"] + local filename = _212_["filename"] + local line = _212_["line"] + error(friendly_msg(("%s:%s:%s: Compile error: %s"):format((filename or "unknown"), (line or "?"), (col or "?"), msg), utils["ast-source"](ast), _3fsource, _3fopts), 0) + end + return condition + end + local function parse_error(msg, filename, line, col, endcol, source, opts) + return error(friendly_msg(("%s:%s:%s: Parse error: %s"):format(filename, line, col, msg), {col = col, endcol = endcol, endline = line, filename = filename, line = line}, source, opts), 0) + end + return {["assert-compile"] = assert_compile, ["parse-error"] = parse_error} +end +package.preload["eca.nfnl.fennel.parser"] = package.preload["eca.nfnl.fennel.parser"] or function(...) + local _194_ = require("eca.nfnl.fennel.utils") + local utils = _194_ + local unpack = _194_["unpack"] + local friend = require("eca.nfnl.fennel.friend") + local function granulate(getchunk) + local c, index, done_3f = "", 1, false + local function _214_(parser_state) + if not done_3f then + if (index <= #c) then + local b = c:byte(index) + index = (index + 1) + return b + else + local _215_0 = getchunk(parser_state) + if (nil ~= _215_0) then + local input = _215_0 + c, index = input, 2 + return c:byte() + else + local _ = _215_0 + done_3f = true + return nil + end + end + end + end + local function _219_() + c = "" + return nil + end + return _214_, _219_ + end + local function string_stream(str, _3foptions) + local str0 = str:gsub("^#!", ";;") + if _3foptions then + _3foptions.source = str0 + end + local index = 1 + local function _221_() + local r = str0:byte(index) + index = (index + 1) + return r + end + return _221_ + end + local delims = {[123] = 125, [125] = true, [40] = 41, [41] = true, [91] = 93, [93] = true} + local function sym_char_3f(b) + local b0 = nil + if ("number" == type(b)) then + b0 = b + else + b0 = string.byte(b) + end + return ((32 < b0) and not delims[b0] and (b0 ~= 127) and (b0 ~= 34) and (b0 ~= 39) and (b0 ~= 126) and (b0 ~= 59) and (b0 ~= 44) and (b0 ~= 64) and (b0 ~= 96)) + end + local prefixes = {[35] = "hashfn", [39] = "quote", [44] = "unquote", [96] = "quote"} + local nan, negative_nan = nil, nil + if (45 == string.byte(tostring((0 / 0)))) then + nan, negative_nan = ( - (0 / 0)), (0 / 0) + else + nan, negative_nan = (0 / 0), ( - (0 / 0)) + end + local function char_starter_3f(b) + return (((1 < b) and (b < 127)) or ((192 < b) and (b < 247))) + end + local escapes = {["'"] = "'", ["\""] = "\"", ["\\"] = "\\", ["\n"] = "\n", a = "\7", b = "\8", f = "\12", n = "\n", r = "\13", t = "\9", v = "\11"} + local function parser_fn(getbyte, filename, _224_0) + local _225_ = _224_0 + local options = _225_ + local comments = _225_["comments"] + local source = _225_["source"] + local unfriendly = _225_["unfriendly"] + local stack = {} + local line, byteindex, col, prev_col, lastb = 1, 0, 0, 0, nil + local function ungetb(ub) + if char_starter_3f(ub) then + col = (col - 1) + end + if (ub == 10) then + line, col = (line - 1), prev_col + end + byteindex = (byteindex - 1) + lastb = ub + return nil + end + local function getb() + local r = nil + if lastb then + r, lastb = lastb, nil + else + r = getbyte({["stack-size"] = #stack}) + end + if r then + byteindex = (byteindex + 1) + end + if (r and char_starter_3f(r)) then + col = (col + 1) + end + if (r == 10) then + line, col, prev_col = (line + 1), 0, col + end + return r + end + local function warn(...) + return (options.warn or utils.warn)(...) + end + local function whitespace_3f(b) + local function _233_() + local _232_0 = options.whitespace + if (nil ~= _232_0) then + _232_0 = _232_0[b] + end + return _232_0 + end + return ((b == 32) or ((9 <= b) and (b <= 13)) or _233_()) + end + local function parse_error(msg, _3fcol_adjust) + local endcol = (_3fcol_adjust and col) + local col0 = (col + (_3fcol_adjust or -1)) + if (nil == utils["hook-opts"]("parse-error", options, msg, filename, (line or "?"), col0, source, utils.root.reset)) then + utils.root.reset() + if unfriendly then + return error(string.format("%s:%s:%s: Parse error: %s", filename, (line or "?"), col0, msg), 0) + else + return friend["parse-error"](msg, filename, (line or "?"), col0, endcol, source, options) + end + end + end + local function parse_stream() + local whitespace_since_dispatch, done_3f, retval = true + local function set_source_fields(source0) + source0.byteend, source0.endcol, source0.endline = byteindex, (col - 1), line + return nil + end + local function dispatch(v, _3fsource, _3fraw) + whitespace_since_dispatch = false + local v0 = nil + do + local _237_0 = utils["hook-opts"]("parse-form", options, v, _3fsource, _3fraw, stack) + if (nil ~= _237_0) then + local hookv = _237_0 + v0 = hookv + else + local _ = _237_0 + v0 = v + end + end + local _239_0 = stack[#stack] + if (_239_0 == nil) then + retval, done_3f = v0, true + return nil + elseif ((_G.type(_239_0) == "table") and (nil ~= _239_0.prefix)) then + local prefix = _239_0.prefix + local source0 = nil + do + local _240_0 = table.remove(stack) + set_source_fields(_240_0) + source0 = _240_0 + end + local list = utils.list(utils.sym(prefix, source0), v0) + return dispatch(utils.copy(source0, list)) + elseif (nil ~= _239_0) then + local top = _239_0 + return table.insert(top, v0) + end + end + local function badend() + local closers = nil + do + local tbl_17_ = {} + local i_18_ = #tbl_17_ + for _, _242_0 in ipairs(stack) do + local _243_ = _242_0 + local closer = _243_["closer"] + local val_19_ = closer + if (nil ~= val_19_) then + i_18_ = (i_18_ + 1) + tbl_17_[i_18_] = val_19_ + end + end + closers = tbl_17_ + end + local _245_ + if (#stack == 1) then + _245_ = "" + else + _245_ = "s" + end + return parse_error(string.format("expected closing delimiter%s %s", _245_, string.char(unpack(closers))), 0) + end + local function skip_whitespace(b, close_table) + if (b and whitespace_3f(b)) then + whitespace_since_dispatch = true + return skip_whitespace(getb(), close_table) + elseif (not b and next(stack)) then + badend() + for i = #stack, 2, -1 do + close_table(stack[i].closer) + end + return stack[1].closer + else + return b + end + end + local function parse_comment(b, contents) + if (b and (10 ~= b)) then + local function _248_() + table.insert(contents, string.char(b)) + return contents + end + return parse_comment(getb(), _248_()) + elseif comments then + ungetb(10) + return dispatch(utils.comment(table.concat(contents), {filename = filename, line = line})) + end + end + local function open_table(b) + if not whitespace_since_dispatch then + parse_error(("expected whitespace before opening delimiter " .. string.char(b))) + end + return table.insert(stack, {bytestart = byteindex, closer = delims[b], col = (col - 1), filename = filename, line = line}) + end + local function close_list(list) + return dispatch(setmetatable(list, getmetatable(utils.list()))) + end + local function close_sequence(tbl) + local mt = getmetatable(utils.sequence()) + for k, v in pairs(tbl) do + if ("number" ~= type(k)) then + mt[k] = v + tbl[k] = nil + end + end + return dispatch(setmetatable(tbl, mt)) + end + local function add_comment_at(comments0, index, node) + local _252_0 = comments0[index] + if (nil ~= _252_0) then + local existing = _252_0 + return table.insert(existing, node) + else + local _ = _252_0 + comments0[index] = {node} + return nil + end + end + local function next_noncomment(tbl, i) + if utils["comment?"](tbl[i]) then + return next_noncomment(tbl, (i + 1)) + elseif utils["sym?"](tbl[i], ":") then + return tostring(tbl[(i + 1)]) + else + return tbl[i] + end + end + local function extract_comments(tbl) + local comments0 = {keys = {}, last = {}, values = {}} + while utils["comment?"](tbl[#tbl]) do + table.insert(comments0.last, 1, table.remove(tbl)) + end + local last_key_3f = false + for i, node in ipairs(tbl) do + if not utils["comment?"](node) then + last_key_3f = not last_key_3f + elseif last_key_3f then + add_comment_at(comments0.values, next_noncomment(tbl, i), node) + else + add_comment_at(comments0.keys, next_noncomment(tbl, i), node) + end + end + for i = #tbl, 1, -1 do + if utils["comment?"](tbl[i]) then + table.remove(tbl, i) + end + end + return comments0 + end + local function close_curly_table(tbl) + local comments0 = extract_comments(tbl) + local keys = {} + local val = {} + if ((#tbl % 2) ~= 0) then + byteindex = (byteindex - 1) + parse_error("expected even number of values in table literal") + end + setmetatable(val, tbl) + for i = 1, #tbl, 2 do + if (utils["sym?"](tbl[(i + 1)]) and utils["sym?"](tbl[i], ":")) then + tbl[i] = tostring(tbl[(i + 1)]) + end + val[tbl[i]] = tbl[(i + 1)] + table.insert(keys, tbl[i]) + end + tbl.comments = comments0 + tbl.keys = keys + return dispatch(val) + end + local function close_table(b) + local top = table.remove(stack) + if (top == nil) then + parse_error(("unexpected closing delimiter " .. string.char(b))) + end + if (top.closer and (top.closer ~= b)) then + parse_error(("mismatched closing delimiter " .. string.char(b) .. ", expected " .. string.char(top.closer))) + end + set_source_fields(top) + if (b == 41) then + return close_list(top) + elseif (b == 93) then + return close_sequence(top) + else + return close_curly_table(top) + end + end + local function bitrange(codepoint, low, high) + return (math.floor((codepoint / (2 ^ low))) % math.floor((2 ^ (high - low)))) + end + local function encode_utf8(codepoint_str) + local _262_0 = tonumber(codepoint_str:sub(4, -2), 16) + if (nil ~= _262_0) then + local codepoint = _262_0 + if _G.utf8 then + return _G.utf8.char(codepoint) + elseif ((0 <= codepoint) and (codepoint <= 127)) then + return string.char(codepoint) + elseif ((128 <= codepoint) and (codepoint <= 2047)) then + return string.char((192 + bitrange(codepoint, 6, 11)), (128 + bitrange(codepoint, 0, 6))) + elseif ((2048 <= codepoint) and (codepoint <= 65535)) then + return string.char((224 + bitrange(codepoint, 12, 16)), (128 + bitrange(codepoint, 6, 12)), (128 + bitrange(codepoint, 0, 6))) + elseif ((65536 <= codepoint) and (codepoint <= 2097151)) then + return string.char((240 + bitrange(codepoint, 18, 21)), (128 + bitrange(codepoint, 12, 18)), (128 + bitrange(codepoint, 6, 12)), (128 + bitrange(codepoint, 0, 6))) + elseif ((131072 <= codepoint) and (codepoint <= 67108863)) then + return string.char((248 + bitrange(codepoint, 24, 26)), (128 + bitrange(codepoint, 18, 24)), (128 + bitrange(codepoint, 12, 18)), (128 + bitrange(codepoint, 6, 12)), (128 + bitrange(codepoint, 0, 6))) + elseif ((4194304 <= codepoint) and (codepoint <= 2147483647)) then + return string.char((252 + bitrange(codepoint, 30, 31)), (128 + bitrange(codepoint, 24, 30)), (128 + bitrange(codepoint, 18, 24)), (128 + bitrange(codepoint, 12, 18)), (128 + bitrange(codepoint, 6, 12)), (128 + bitrange(codepoint, 0, 6))) + else + return parse_error(("utf8 value too large: " .. codepoint_str)) + end + else + local _ = _262_0 + return parse_error(("Illegal string: " .. codepoint_str)) + end + end + local function parse_string_loop(chars, b, state) + if b then + table.insert(chars, string.char(b)) + end + local state0 = nil + do + local _266_0 = {state, b} + if ((_G.type(_266_0) == "table") and (_266_0[1] == "base") and (_266_0[2] == 92)) then + state0 = "backslash" + elseif ((_G.type(_266_0) == "table") and (_266_0[1] == "base") and (_266_0[2] == 34)) then + state0 = "done" + else + local _ = _266_0 + state0 = "base" + end + end + if (b and (state0 ~= "done")) then + return parse_string_loop(chars, getb(), state0) + else + return b + end + end + local function expand_str(str) + local result = {} + local i = 1 + while (i <= #str) do + local add_to_i, add_to_result = nil, nil + do + local _269_0 = str:match("^[^\\]+", i) + if (nil ~= _269_0) then + local text = _269_0 + add_to_i, add_to_result = #text, text + else + local _ = _269_0 + local _270_0 = escapes[str:match("^\\(.?)", i)] + if (nil ~= _270_0) then + local escape = _270_0 + add_to_i, add_to_result = 2, escape + else + local _0 = _270_0 + if ("\\\13\n" == str:sub(i, (i + 2))) then + add_to_i, add_to_result = 3, "\13\n" + else + local _271_0 = str:match("^\\x(%x%x)", i) + if (nil ~= _271_0) then + local hex_code = _271_0 + add_to_i, add_to_result = 4, string.char(tonumber(hex_code, 16)) + else + local _1 = _271_0 + local _272_0 = str:match("^\\u{%x+}", i) + if (nil ~= _272_0) then + local unicode_escape = _272_0 + add_to_i, add_to_result = #unicode_escape, encode_utf8(unicode_escape) + else + local _2 = _272_0 + local _273_0, _274_0 = str:find("^\\z%s*", i) + if (true and (nil ~= _274_0)) then + local _3 = _273_0 + local j = _274_0 + add_to_i, add_to_result = ((j - i) + 1), "" + else + local _3 = _273_0 + local _275_0 = str:match("^\\(%d%d?%d?)", i) + if (nil ~= _275_0) then + local digits = _275_0 + local byte = tonumber(digits, 10) + if (255 < byte) then + parse_error("invalid decimal escape") + end + add_to_i, add_to_result = (#digits + 1), string.char(byte) + else + local _4 = _275_0 + add_to_i, add_to_result = parse_error("invalid escape sequence") + end + end + end + end + end + end + end + end + table.insert(result, add_to_result) + i = (i + add_to_i) + end + return table.concat(result) + end + local function parse_string(source0) + if not whitespace_since_dispatch then + warn("expected whitespace before string", nil, filename, line, (col - 1)) + end + table.insert(stack, {closer = 34}) + local chars = {"\""} + if not parse_string_loop(chars, getb(), "base") then + badend() + end + table.remove(stack) + local raw = table.concat(chars) + local expanded = expand_str(raw:sub(2, -2)) + return dispatch(expanded, source0, raw) + end + local function parse_prefix(b) + table.insert(stack, {bytestart = byteindex, col = (col - 1), filename = filename, line = line, prefix = prefixes[b]}) + local nextb = getb() + local trailing_whitespace_3f = (whitespace_3f(nextb) or (true == delims[nextb])) + if (trailing_whitespace_3f and (b ~= 35)) then + parse_error("invalid whitespace after quoting prefix") + end + ungetb(nextb) + if (trailing_whitespace_3f and (b == 35)) then + local source0 = table.remove(stack) + set_source_fields(source0) + return dispatch(utils.sym("#", source0)) + end + end + local function parse_sym_loop(chars, b) + if (b and sym_char_3f(b)) then + table.insert(chars, string.char(b)) + return parse_sym_loop(chars, getb()) + else + if b then + ungetb(b) + end + return chars + end + end + local function parse_number(rawstr, source0) + local trimmed = (not rawstr:find("^_") and rawstr:gsub("_", "")) + if ((trimmed == "nan") or (trimmed == "-nan")) then + return false + elseif rawstr:match("^%d") then + dispatch((tonumber(trimmed) or parse_error(("could not read number \"" .. rawstr .. "\""), ( - #rawstr))), source0, rawstr) + return true + else + local _290_0 = tonumber(trimmed) + if (nil ~= _290_0) then + local x = _290_0 + dispatch(x, source0, rawstr) + return true + else + local _ = _290_0 + return false + end + end + end + local function check_malformed_sym(rawstr) + local function col_adjust(pat) + return (rawstr:find(pat) - utils.len(rawstr) - 1) + end + if (rawstr:match("^~") and (rawstr ~= "~=")) then + parse_error("invalid character: ~") + elseif (rawstr:match("[%.:][%.:]") and (rawstr ~= "..") and (rawstr ~= "$...")) then + parse_error(("malformed multisym: " .. rawstr), col_adjust("[%.:][%.:]")) + elseif ((rawstr ~= ":") and rawstr:match(":$")) then + parse_error(("malformed multisym: " .. rawstr), col_adjust(":$")) + elseif rawstr:match(":.+[%.:]") then + parse_error(("method must be last component of multisym: " .. rawstr), col_adjust(":.+[%.:]")) + end + return rawstr + end + local function parse_sym(b) + local source0 = {bytestart = byteindex, col = (col - 1), filename = filename, line = line} + local rawstr = table.concat(parse_sym_loop({string.char(b)}, getb())) + set_source_fields(source0) + if not whitespace_since_dispatch then + warn("expected whitespace before token", nil, filename, line, (col - utils.len(rawstr))) + end + if (rawstr == "true") then + return dispatch(true, source0) + elseif (rawstr == "false") then + return dispatch(false, source0) + elseif (rawstr == "...") then + return dispatch(utils.varg(source0)) + elseif ((rawstr == ".inf") or (rawstr == "+.inf")) then + return dispatch((1 / 0), source0, rawstr) + elseif (rawstr == "-.inf") then + return dispatch((-1 / 0), source0, rawstr) + elseif ((rawstr == ".nan") or (rawstr == "+.nan")) then + return dispatch(nan, source0, rawstr) + elseif (rawstr == "-.nan") then + return dispatch(negative_nan, source0, rawstr) + elseif rawstr:match("^:.+$") then + return dispatch(rawstr:sub(2), source0, rawstr) + elseif not parse_number(rawstr, source0) then + return dispatch(utils.sym(check_malformed_sym(rawstr), source0)) + end + end + local function parse_loop(b) + if not b then + elseif (b == 59) then + parse_comment(getb(), {";"}) + elseif (type(delims[b]) == "number") then + open_table(b) + elseif delims[b] then + close_table(b) + elseif (b == 34) then + parse_string({bytestart = byteindex, col = col, filename = filename, line = line}) + elseif prefixes[b] then + parse_prefix(b) + elseif (sym_char_3f(b) or (b == string.byte("~"))) then + parse_sym(b) + elseif not utils["hook-opts"]("illegal-char", options, b, getb, ungetb, dispatch) then + parse_error(("invalid character: " .. string.char(b))) + end + if not b then + return nil + elseif done_3f then + return true, retval + else + return parse_loop(skip_whitespace(getb(), close_table)) + end + end + return parse_loop(skip_whitespace(getb(), close_table)) + end + local function _298_() + stack, line, byteindex, col, lastb = {}, 1, 0, 0, ((lastb ~= 10) and lastb) + return nil + end + return parse_stream, _298_ + end + local function parser(stream_or_string, _3ffilename, _3foptions) + local filename = (_3ffilename or "unknown") + local options = (_3foptions or utils.root.options or {}) + assert(("string" == type(filename)), "expected filename as second argument to parser") + if ("string" == type(stream_or_string)) then + return parser_fn(string_stream(stream_or_string, options), filename, options) + else + return parser_fn(stream_or_string, filename, options) + end + end + return {["string-stream"] = string_stream, ["sym-char?"] = sym_char_3f, granulate = granulate, parser = parser} +end +local utils = nil +package.preload["eca.nfnl.fennel.view"] = package.preload["eca.nfnl.fennel.view"] or function(...) + local type_order = {["function"] = 5, boolean = 2, number = 1, string = 3, table = 4, thread = 7, userdata = 6} + local default_opts = {["detect-cycles?"] = true, ["empty-as-sequence?"] = false, ["escape-newlines?"] = false, ["line-length"] = 80, ["max-sparse-gap"] = 1, ["metamethod?"] = true, ["one-line?"] = false, ["prefer-colon?"] = false, ["utf8?"] = true, depth = 128} + local lua_pairs = pairs + local lua_ipairs = ipairs + local function pairs(t) + local _1_0 = getmetatable(t) + if ((_G.type(_1_0) == "table") and (nil ~= _1_0.__pairs)) then + local p = _1_0.__pairs + return p(t) + else + local _ = _1_0 + return lua_pairs(t) + end + end + local function ipairs(t) + local _3_0 = getmetatable(t) + if ((_G.type(_3_0) == "table") and (nil ~= _3_0.__ipairs)) then + local i = _3_0.__ipairs + return i(t) + else + local _ = _3_0 + return lua_ipairs(t) + end + end + local function length_2a(t) + local _5_0 = getmetatable(t) + if ((_G.type(_5_0) == "table") and (nil ~= _5_0.__len)) then + local l = _5_0.__len + return l(t) + else + local _ = _5_0 + return #t + end + end + local function get_default(key) + local _7_0 = default_opts[key] + if (_7_0 == nil) then + return error(("option '%s' doesn't have a default value, use the :after key to set it"):format(tostring(key))) + elseif (nil ~= _7_0) then + local v = _7_0 + return v + end + end + local function getopt(options, key) + local _9_0 = options[key] + if ((_G.type(_9_0) == "table") and (nil ~= _9_0.once)) then + local val_2a = _9_0.once + return val_2a + else + local _3fval = _9_0 + return _3fval + end + end + local function normalize_opts(options) + local tbl_14_ = {} + for k, v in pairs(options) do + local k_15_, v_16_ = nil, nil + local function _12_() + local _11_0 = v + if ((_G.type(_11_0) == "table") and (nil ~= _11_0.after)) then + local val = _11_0.after + return val + else + local function _13_() + return v.once + end + if ((_G.type(_11_0) == "table") and _13_()) then + return get_default(k) + else + local _ = _11_0 + return v + end + end + end + k_15_, v_16_ = k, _12_() + if ((k_15_ ~= nil) and (v_16_ ~= nil)) then + tbl_14_[k_15_] = v_16_ + end + end + return tbl_14_ + end + local function sort_keys(_16_0, _18_0) + local _17_ = _16_0 + local a = _17_[1] + local _19_ = _18_0 + local b = _19_[1] + local ta = type(a) + local tb = type(b) + if ((ta == tb) and ((ta == "string") or (ta == "number"))) then + return (a < b) + else + local dta = type_order[ta] + local dtb = type_order[tb] + if (dta and dtb) then + return (dta < dtb) + elseif dta then + return true + elseif dtb then + return false + else + return (ta < tb) + end + end + end + local function max_index_gap(kv) + local gap = 0 + if (0 < length_2a(kv)) then + local i = 0 + for _, _22_0 in ipairs(kv) do + local _23_ = _22_0 + local k = _23_[1] + if (gap < (k - i)) then + gap = (k - i) + end + i = k + end + end + return gap + end + local function fill_gaps(kv) + local missing_indexes = {} + local i = 0 + for _, _26_0 in ipairs(kv) do + local _27_ = _26_0 + local j = _27_[1] + i = (i + 1) + while (i < j) do + table.insert(missing_indexes, i) + i = (i + 1) + end + end + for _, k in ipairs(missing_indexes) do + table.insert(kv, k, {k}) + end + return nil + end + local function table_kv_pairs(t, options) + if (("number" ~= type(options["max-sparse-gap"])) or (options["max-sparse-gap"] ~= math.floor(options["max-sparse-gap"]))) then + error(("max-sparse-gap must be an integer: got '%s'"):format(tostring(options["max-sparse-gap"]))) + end + local assoc_3f = false + local kv = {} + local insert = table.insert + for k, v in pairs(t) do + if (("number" ~= type(k)) or (k < 1) or (k ~= math.floor(k))) then + assoc_3f = true + end + insert(kv, {k, v}) + end + table.sort(kv, sort_keys) + if not assoc_3f then + if (options["max-sparse-gap"] < max_index_gap(kv)) then + assoc_3f = true + else + fill_gaps(kv) + end + end + if (length_2a(kv) == 0) then + return kv, "empty" + else + local function _32_() + if assoc_3f then + return "table" + else + return "seq" + end + end + return kv, _32_() + end + end + local function count_table_appearances(t, appearances) + if (type(t) == "table") then + if not appearances[t] then + appearances[t] = 1 + for k, v in pairs(t) do + count_table_appearances(k, appearances) + count_table_appearances(v, appearances) + end + else + appearances[t] = ((appearances[t] or 0) + 1) + end + end + return appearances + end + local function save_table(t, seen) + local seen0 = (seen or {len = 0}) + local id = (seen0.len + 1) + if not seen0[t] then + seen0[t] = id + seen0.len = id + end + return seen0 + end + local function detect_cycle(t, seen) + if ("table" == type(t)) then + seen[t] = true + local res = nil + for k, v in pairs(t) do + if res then break end + res = (seen[k] or detect_cycle(k, seen) or seen[v] or detect_cycle(v, seen)) + end + return res + end + end + local function visible_cycle_3f(t, options) + return (getopt(options, "detect-cycles?") and detect_cycle(t, {}) and save_table(t, options.seen) and (1 < (options.appearances[t] or 0))) + end + local function table_indent(indent, id) + local opener_length = nil + if id then + opener_length = (length_2a(tostring(id)) + 2) + else + opener_length = 1 + end + return (indent + opener_length) + end + local pp = nil + local function concat_table_lines(elements, options, multiline_3f, indent, table_type, prefix, last_comment_3f) + local indent_str = ("\n" .. string.rep(" ", indent)) + local open = nil + local function _39_() + if ("seq" == table_type) then + return "[" + else + return "{" + end + end + open = ((prefix or "") .. _39_()) + local close = nil + if ("seq" == table_type) then + close = "]" + else + close = "}" + end + local oneline = (open .. table.concat(elements, " ") .. close) + if (not getopt(options, "one-line?") and (multiline_3f or (options["line-length"] < (indent + length_2a(oneline))) or last_comment_3f)) then + local function _41_() + if last_comment_3f then + return indent_str + else + return "" + end + end + return (open .. table.concat(elements, indent_str) .. _41_() .. close) + else + return oneline + end + end + local function comment_3f(x) + if ("table" == type(x)) then + local fst = x[1] + return (("string" == type(fst)) and (nil ~= fst:find("^;"))) + else + return false + end + end + local function pp_associative(t, kv, options, indent) + local multiline_3f = false + local id = options.seen[t] + if (options.depth <= options.level) then + return "{...}" + elseif (id and getopt(options, "detect-cycles?")) then + return ("@" .. id .. "{...}") + else + local visible_cycle_3f0 = visible_cycle_3f(t, options) + local id0 = (visible_cycle_3f0 and options.seen[t]) + local indent0 = table_indent(indent, id0) + local prefix = nil + if visible_cycle_3f0 then + prefix = ("@" .. id0) + else + prefix = "" + end + local items = nil + do + local options0 = normalize_opts(options) + local tbl_17_ = {} + local i_18_ = #tbl_17_ + for _, _45_0 in ipairs(kv) do + local _46_ = _45_0 + local k = _46_[1] + local v = _46_[2] + local val_19_ = nil + do + local k0 = pp(k, options0, (indent0 + 1), true) + local v0 = pp(v, options0, indent0) + multiline_3f = (multiline_3f or k0:find("\n") or v0:find("\n") or (options0["line-length"] < length_2a((k0 .. " " .. v0)))) + val_19_ = {k0, v0} + end + if (nil ~= val_19_) then + i_18_ = (i_18_ + 1) + tbl_17_[i_18_] = val_19_ + end + end + items = tbl_17_ + end + local lines = nil + do + local lines0 = {} + for _, _48_0 in ipairs(items) do + local _49_ = _48_0 + local k = _49_[1] + local v = _49_[2] + if multiline_3f then + table.insert(lines0, k) + table.insert(lines0, v) + lines0 = lines0 + else + table.insert(lines0, (k .. " " .. v)) + lines0 = lines0 + end + end + lines = lines0 + end + return concat_table_lines(lines, options, multiline_3f, indent0, "table", prefix, false) + end + end + local function pp_sequence(t, kv, options, indent) + local multiline_3f = false + local id = options.seen[t] + if (options.depth <= options.level) then + return "[...]" + elseif (id and getopt(options, "detect-cycles?")) then + return ("@" .. id .. "[...]") + else + local visible_cycle_3f0 = visible_cycle_3f(t, options) + local id0 = (visible_cycle_3f0 and options.seen[t]) + local indent0 = table_indent(indent, id0) + local prefix = nil + if visible_cycle_3f0 then + prefix = ("@" .. id0) + else + prefix = "" + end + local last_comment_3f = comment_3f(t[#t]) + local items = nil + do + local options0 = normalize_opts(options) + local tbl_17_ = {} + local i_18_ = #tbl_17_ + for _, _53_0 in ipairs(kv) do + local _54_ = _53_0 + local _0 = _54_[1] + local v = _54_[2] + local val_19_ = nil + do + local v0 = pp(v, options0, indent0) + multiline_3f = (multiline_3f or v0:find("\n") or v0:find("^;")) + val_19_ = v0 + end + if (nil ~= val_19_) then + i_18_ = (i_18_ + 1) + tbl_17_[i_18_] = val_19_ + end + end + items = tbl_17_ + end + return concat_table_lines(items, options, multiline_3f, indent0, "seq", prefix, last_comment_3f) + end + end + local function concat_lines(lines, options, indent, force_multi_line_3f) + if (length_2a(lines) == 0) then + if getopt(options, "empty-as-sequence?") then + return "[]" + else + return "{}" + end + else + local oneline = nil + local _58_ + do + local tbl_17_ = {} + local i_18_ = #tbl_17_ + for _, line in ipairs(lines) do + local val_19_ = line:gsub("^%s+", "") + if (nil ~= val_19_) then + i_18_ = (i_18_ + 1) + tbl_17_[i_18_] = val_19_ + end + end + _58_ = tbl_17_ + end + oneline = table.concat(_58_, " ") + if (not getopt(options, "one-line?") and (force_multi_line_3f or oneline:find("\n") or (options["line-length"] < (indent + length_2a(oneline))))) then + return table.concat(lines, ("\n" .. string.rep(" ", indent))) + else + return oneline + end + end + end + local function pp_metamethod(t, metamethod, options, indent) + if (options.depth <= options.level) then + if getopt(options, "empty-as-sequence?") then + return "[...]" + else + return "{...}" + end + else + local _ = nil + local function _63_(_241) + return visible_cycle_3f(_241, options) + end + options["visible-cycle?"] = _63_ + _ = nil + local lines, force_multi_line_3f = nil, nil + do + local options0 = normalize_opts(options) + lines, force_multi_line_3f = metamethod(t, pp, options0, indent) + end + options["visible-cycle?"] = nil + local _64_0 = type(lines) + if (_64_0 == "string") then + return lines + elseif (_64_0 == "table") then + return concat_lines(lines, options, indent, force_multi_line_3f) + else + local _0 = _64_0 + return error("__fennelview metamethod must return a table of lines") + end + end + end + local function pp_table(x, options, indent) + options.level = (options.level + 1) + local x0 = nil + do + local _67_0 = nil + if getopt(options, "metamethod?") then + local _68_0 = x + if (nil ~= _68_0) then + local _69_0 = getmetatable(_68_0) + if (nil ~= _69_0) then + _67_0 = _69_0.__fennelview + else + _67_0 = _69_0 + end + else + _67_0 = _68_0 + end + else + _67_0 = nil + end + if (nil ~= _67_0) then + local metamethod = _67_0 + x0 = pp_metamethod(x, metamethod, options, indent) + else + local _ = _67_0 + local _73_0, _74_0 = table_kv_pairs(x, options) + if (true and (_74_0 == "empty")) then + local _0 = _73_0 + if getopt(options, "empty-as-sequence?") then + x0 = "[]" + else + x0 = "{}" + end + elseif ((nil ~= _73_0) and (_74_0 == "table")) then + local kv = _73_0 + x0 = pp_associative(x, kv, options, indent) + elseif ((nil ~= _73_0) and (_74_0 == "seq")) then + local kv = _73_0 + x0 = pp_sequence(x, kv, options, indent) + else + x0 = nil + end + end + end + options.level = (options.level - 1) + return x0 + end + local function exponential_notation(n, fallback) + local s = nil + for i = 0, 99 do + if s then break end + local s0 = string.format(("%." .. i .. "e"), n) + if (n == tonumber(s0)) then + local exp = s0:match("e%+?(%d+)$") + if (exp and (14 < tonumber(exp))) then + s = s0 + else + s = fallback + end + else + s = nil + end + end + return s + end + local inf_str = tostring((1 / 0)) + local neg_inf_str = tostring((-1 / 0)) + local math_type = math.type + local function integer__3estring(n, options) + local s1 = tostring(n) + if (math_type and ("integer" == math_type(n))) then + return s1 + elseif (s1 == inf_str) then + return (options.infinity or ".inf") + elseif (s1 == neg_inf_str) then + return (options["negative-infinity"] or "-.inf") + elseif (s1 == string.format("%.0f", n)) then + return s1 + else + return (exponential_notation(n, s1) or s1) + end + end + local function number__3estring(n, options) + local val = nil + if (n ~= n) then + if (45 == string.byte(tostring(n))) then + val = (options["negative-nan"] or "-.nan") + else + val = (options.nan or ".nan") + end + elseif (math.floor(n) == n) then + val = integer__3estring(n, options) + else + val = tostring(n) + end + local _83_0 = string.gsub(val, ",", ".") + return _83_0 + end + local function colon_string_3f(s) + return s:find("^[-%w?^_!$%&*+./|<=>]+$") + end + local utf8_inits = {{["max-byte"] = 127, ["max-code"] = 127, ["min-byte"] = 0, ["min-code"] = 0, len = 1}, {["max-byte"] = 223, ["max-code"] = 2047, ["min-byte"] = 192, ["min-code"] = 128, len = 2}, {["max-byte"] = 239, ["max-code"] = 65535, ["min-byte"] = 224, ["min-code"] = 2048, len = 3}, {["max-byte"] = 247, ["max-code"] = 1114111, ["min-byte"] = 240, ["min-code"] = 65536, len = 4}} + local function default_byte_escape(byte, _options) + return ("\\%03d"):format(byte) + end + local function utf8_escape(str, options) + local function validate_utf8(str0, index) + local inits = utf8_inits + local byte = string.byte(str0, index) + local init = nil + do + local ret = nil + for _, init0 in ipairs(inits) do + if ret then break end + ret = (byte and (function(_84_,_85_,_86_) return (_84_ <= _85_) and (_85_ <= _86_) end)(init0["min-byte"],byte,init0["max-byte"]) and init0) + end + init = ret + end + local code = nil + local function _87_() + local code0 = nil + if init then + code0 = (byte - init["min-byte"]) + else + code0 = nil + end + for i = (index + 1), (index + init.len + -1) do + local byte0 = string.byte(str0, i) + code0 = (byte0 and code0 and ((128 <= byte0) and (byte0 <= 191)) and ((code0 * 64) + (byte0 - 128))) + end + return code0 + end + code = (init and _87_()) + if (code and (function(_89_,_90_,_91_) return (_89_ <= _90_) and (_90_ <= _91_) end)(init["min-code"],code,init["max-code"]) and not ((55296 <= code) and (code <= 57343))) then + return init.len + end + end + local index = 1 + local output = {} + local byte_escape = (getopt(options, "byte-escape") or default_byte_escape) + while (index <= #str) do + local nexti = (string.find(str, "[\128-\255]", index) or (#str + 1)) + local len = validate_utf8(str, nexti) + table.insert(output, string.sub(str, index, (nexti + (len or 0) + -1))) + if (not len and (nexti <= #str)) then + table.insert(output, byte_escape(str:byte(nexti), options)) + end + if len then + index = (nexti + len) + else + index = (nexti + 1) + end + end + return table.concat(output) + end + local function pp_string(str, options, indent) + local len = length_2a(str) + local esc_newline_3f = ((len < 2) or (getopt(options, "escape-newlines?") and (len < (options["line-length"] - indent)))) + local byte_escape = (getopt(options, "byte-escape") or default_byte_escape) + local escs = nil + local _95_ + if esc_newline_3f then + _95_ = "\\n" + else + _95_ = "\n" + end + local function _97_(_241, _242) + return byte_escape(_242:byte(), options) + end + escs = setmetatable({["\""] = "\\\"", ["\11"] = "\\v", ["\12"] = "\\f", ["\13"] = "\\r", ["\7"] = "\\a", ["\8"] = "\\b", ["\9"] = "\\t", ["\\"] = "\\\\", ["\n"] = _95_}, {__index = _97_}) + local str0 = ("\"" .. str:gsub("[%c\\\"]", escs) .. "\"") + if getopt(options, "utf8?") then + return utf8_escape(str0, options) + else + return str0 + end + end + local function make_options(t, _3foptions) + local defaults = nil + do + local tbl_14_ = {} + for k, v in pairs(default_opts) do + local k_15_, v_16_ = k, v + if ((k_15_ ~= nil) and (v_16_ ~= nil)) then + tbl_14_[k_15_] = v_16_ + end + end + defaults = tbl_14_ + end + local overrides = {appearances = count_table_appearances(t, {}), level = 0, seen = {len = 0}} + for k, v in pairs((_3foptions or {})) do + defaults[k] = v + end + for k, v in pairs(overrides) do + defaults[k] = v + end + return defaults + end + local function _100_(x, options, indent, colon_3f) + local indent0 = (indent or 0) + local options0 = (options or make_options(x)) + local x0 = nil + if options0.preprocess then + x0 = options0.preprocess(x, options0) + else + x0 = x + end + local tv = type(x0) + local function _103_() + local _102_0 = getmetatable(x0) + if ((_G.type(_102_0) == "table") and true) then + local __fennelview = _102_0.__fennelview + return __fennelview + end + end + if ((tv == "table") or ((tv == "userdata") and _103_())) then + return pp_table(x0, options0, indent0) + elseif (tv == "number") then + return number__3estring(x0, options0) + else + local function _105_() + if (colon_3f ~= nil) then + return colon_3f + elseif ("function" == type(options0["prefer-colon?"])) then + return options0["prefer-colon?"](x0) + else + return getopt(options0, "prefer-colon?") + end + end + if ((tv == "string") and colon_string_3f(x0) and _105_()) then + return (":" .. x0) + elseif (tv == "string") then + return pp_string(x0, options0, indent0) + elseif ((tv == "boolean") or (tv == "nil")) then + return tostring(x0) + else + return ("#<" .. tostring(x0) .. ">") + end + end + end + pp = _100_ + local function _view(x, _3foptions) + return pp(x, make_options(x, _3foptions), 0) + end + return _view +end +package.preload["eca.nfnl.fennel.utils"] = package.preload["eca.nfnl.fennel.utils"] or function(...) + local view = require("eca.nfnl.fennel.view") + local version = "1.6.1" + local unpack = (table.unpack or _G.unpack) + local pack = nil + local function _107_(...) + local _108_0 = {...} + _108_0["n"] = select("#", ...) + return _108_0 + end + pack = (table.pack or _107_) + local maxn = nil + local function _109_(_241) + local max = 0 + for k in pairs(_241) do + if (("number" == type(k)) and (max < k)) then + max = k + else + max = max + end + end + return max + end + maxn = (table.maxn or _109_) + local function luajit_vm_3f() + return ((nil ~= _G.jit) and (type(_G.jit) == "table") and (nil ~= _G.jit.on) and (nil ~= _G.jit.off) and (type(_G.jit.version_num) == "number")) + end + local function luajit_vm_version() + local jit_os = nil + if (_G.jit.os == "OSX") then + jit_os = "macOS" + else + jit_os = _G.jit.os + end + return (_G.jit.version .. " " .. jit_os .. "/" .. _G.jit.arch) + end + local function fengari_vm_3f() + return ((nil ~= _G.fengari) and (type(_G.fengari) == "table") and (nil ~= _G.fengari.VERSION) and (type(_G.fengari.VERSION_NUM) == "number")) + end + local function fengari_vm_version() + return (_G.fengari.RELEASE .. " (" .. _VERSION .. ")") + end + local function lua_vm_version() + if luajit_vm_3f() then + return luajit_vm_version() + elseif fengari_vm_3f() then + return fengari_vm_version() + else + return ("PUC " .. _VERSION) + end + end + local function runtime_version(_3fas_table) + if _3fas_table then + return {fennel = version, lua = lua_vm_version()} + else + return ("Fennel " .. version .. " on " .. lua_vm_version()) + end + end + local len = nil + do + local _114_0, _115_0 = pcall(require, "utf8") + if ((_114_0 == true) and (nil ~= _115_0)) then + local utf8 = _115_0 + len = utf8.len + else + local _ = _114_0 + len = string.len + end + end + local kv_order = {boolean = 2, number = 1, string = 3, table = 4} + local function kv_compare(a, b) + local _117_0, _118_0 = type(a), type(b) + if (((_117_0 == "number") and (_118_0 == "number")) or ((_117_0 == "string") and (_118_0 == "string"))) then + return (a < b) + else + local function _119_() + local a_t = _117_0 + local b_t = _118_0 + return (a_t ~= b_t) + end + if (((nil ~= _117_0) and (nil ~= _118_0)) and _119_()) then + local a_t = _117_0 + local b_t = _118_0 + return ((kv_order[a_t] or 5) < (kv_order[b_t] or 5)) + else + local _ = _117_0 + return (tostring(a) < tostring(b)) + end + end + end + local function add_stable_keys(succ, prev_key, src, _3fpred) + local first = prev_key + local last = nil + do + local prev = prev_key + for _, k in ipairs(src) do + if ((prev == k) or (succ[k] ~= nil) or (_3fpred and not _3fpred(k))) then + prev = prev + else + if (first == nil) then + first = k + prev = k + elseif (prev ~= nil) then + succ[prev] = k + prev = k + else + prev = k + end + end + end + last = prev + end + return succ, last, first + end + local function stablepairs(t) + local mt_keys = nil + do + local _123_0 = getmetatable(t) + if (nil ~= _123_0) then + _123_0 = _123_0.keys + end + mt_keys = _123_0 + end + local succ, prev, first_mt = nil, nil, nil + local function _125_(_241) + return t[_241] + end + succ, prev, first_mt = add_stable_keys({}, nil, (mt_keys or {}), _125_) + local pairs_keys = nil + do + local _126_0 = nil + do + local tbl_17_ = {} + local i_18_ = #tbl_17_ + for k in pairs(t) do + local val_19_ = k + if (nil ~= val_19_) then + i_18_ = (i_18_ + 1) + tbl_17_[i_18_] = val_19_ + end + end + _126_0 = tbl_17_ + end + table.sort(_126_0, kv_compare) + pairs_keys = _126_0 + end + local succ0, _, first_after_mt = add_stable_keys(succ, prev, pairs_keys) + local first = nil + if (first_mt == nil) then + first = first_after_mt + else + first = first_mt + end + local function stablenext(tbl, key) + local _129_0 = nil + if (key == nil) then + _129_0 = first + else + _129_0 = succ0[key] + end + if (nil ~= _129_0) then + local next_key = _129_0 + local _131_0 = tbl[next_key] + if (_131_0 ~= nil) then + return next_key, _131_0 + else + return _131_0 + end + end + end + return stablenext, t, nil + end + local function get_in(tbl, path) + if (nil ~= path[1]) then + local t = tbl + for _, k in ipairs(path) do + if (nil == t) then break end + if (type(t) == "table") then + t = t[k] + else + t = nil + end + end + return t + end + end + local function copy(_3ffrom, _3fto) + local tbl_14_ = (_3fto or {}) + for k, v in pairs((_3ffrom or {})) do + local k_15_, v_16_ = k, v + if ((k_15_ ~= nil) and (v_16_ ~= nil)) then + tbl_14_[k_15_] = v_16_ + end + end + return tbl_14_ + end + local function member_3f(x, tbl, _3fn) + local _137_0 = tbl[(_3fn or 1)] + if (_137_0 == x) then + return true + elseif (_137_0 == nil) then + return nil + else + local _ = _137_0 + return member_3f(x, tbl, ((_3fn or 1) + 1)) + end + end + local function every_3f(t, predicate) + local result = true + for _, item in ipairs(t) do + if not result then break end + result = predicate(item) + end + return result + end + local function allpairs(tbl) + assert((type(tbl) == "table"), "allpairs expects a table") + local t = tbl + local seen = {} + local function allpairs_next(_, _3fstate) + local next_state, value = next(t, _3fstate) + if seen[next_state] then + return allpairs_next(nil, next_state) + elseif next_state then + seen[next_state] = true + return next_state, value + else + local _139_0 = getmetatable(t) + if ((_G.type(_139_0) == "table") and true) then + local __index = _139_0.__index + if ("table" == type(__index)) then + t = __index + return allpairs_next(t) + end + end + end + end + return allpairs_next + end + local function deref(self) + return self[1] + end + local function list__3estring(self, _3fview, _3foptions, _3findent) + local viewed = nil + do + local tbl_17_ = {} + local i_18_ = #tbl_17_ + for i = 1, maxn(self) do + local val_19_ = nil + if _3fview then + val_19_ = _3fview(self[i], _3foptions, _3findent) + else + val_19_ = view(self[i]) + end + if (nil ~= val_19_) then + i_18_ = (i_18_ + 1) + tbl_17_[i_18_] = val_19_ + end + end + viewed = tbl_17_ + end + return ("(" .. table.concat(viewed, " ") .. ")") + end + local function sym_3d(a, b) + return ((deref(a) == deref(b)) and (getmetatable(a) == getmetatable(b))) + end + local function sym_3c(a, b) + return (a[1] < tostring(b)) + end + local symbol_mt = {"SYMBOL", __eq = sym_3d, __fennelview = deref, __lt = sym_3c, __tostring = deref} + local expr_mt = nil + local function _145_(x) + return tostring(deref(x)) + end + expr_mt = {"EXPR", __tostring = _145_} + local list_mt = {"LIST", __fennelview = list__3estring, __tostring = list__3estring} + local comment_mt = nil + local function _146_(_241) + return _241 + end + comment_mt = {"COMMENT", __eq = sym_3d, __fennelview = _146_, __lt = sym_3c, __tostring = deref} + local sequence_marker = {"SEQUENCE"} + local varg_mt = {"VARARG", __fennelview = deref, __tostring = deref} + local getenv = nil + local function _147_() + return nil + end + getenv = ((os and os.getenv) or _147_) + local function debug_on_3f(_3fflag) + local dbg = getenv("FENNEL_DEBUG") + if (_3fflag == nil) then + return (nil ~= dbg) + else + return (dbg and dbg:find(_3fflag)) + end + end + local function list(...) + return setmetatable({...}, list_mt) + end + local function sym(str, _3fsource) + assert((type(str) == "string"), ("sym expects a string as the first argument, received " .. type(str))) + local _149_ + do + local tbl_14_ = {str} + for k, v in pairs((_3fsource or {})) do + local k_15_, v_16_ = nil, nil + if (type(k) == "string") then + k_15_, v_16_ = k, v + else + k_15_, v_16_ = nil + end + if ((k_15_ ~= nil) and (v_16_ ~= nil)) then + tbl_14_[k_15_] = v_16_ + end + end + _149_ = tbl_14_ + end + return setmetatable(_149_, symbol_mt) + end + local function sequence(...) + local function _152_(seq, view0, inspector, indent) + local opts = nil + do + inspector["empty-as-sequence?"] = {after = inspector["empty-as-sequence?"], once = true} + inspector["metamethod?"] = {after = inspector["metamethod?"], once = false} + opts = inspector + end + return view0(seq, opts, indent) + end + return setmetatable({...}, {__fennelview = _152_, sequence = sequence_marker}) + end + local function expr(strcode, etype) + return setmetatable({strcode, type = etype}, expr_mt) + end + local function comment_2a(contents, _3fsource) + local _153_ = (_3fsource or {}) + local filename = _153_["filename"] + local line = _153_["line"] + return setmetatable({contents, filename = filename, line = line}, comment_mt) + end + local function varg(_3fsource) + local _154_ + do + local tbl_14_ = {"..."} + for k, v in pairs((_3fsource or {})) do + local k_15_, v_16_ = nil, nil + if (type(k) == "string") then + k_15_, v_16_ = k, v + else + k_15_, v_16_ = nil + end + if ((k_15_ ~= nil) and (v_16_ ~= nil)) then + tbl_14_[k_15_] = v_16_ + end + end + _154_ = tbl_14_ + end + return setmetatable(_154_, varg_mt) + end + local function expr_3f(x) + return ((type(x) == "table") and (getmetatable(x) == expr_mt) and x) + end + local function varg_3f(x) + return ((type(x) == "table") and (getmetatable(x) == varg_mt) and x) + end + local function list_3f(x) + return ((type(x) == "table") and (getmetatable(x) == list_mt) and x) + end + local function sym_3f(x, _3fname) + return ((type(x) == "table") and (getmetatable(x) == symbol_mt) and ((nil == _3fname) or (x[1] == _3fname)) and x) + end + local function sequence_3f(x) + local mt = ((type(x) == "table") and getmetatable(x)) + return (mt and (mt.sequence == sequence_marker) and x) + end + local function comment_3f(x) + return ((type(x) == "table") and (getmetatable(x) == comment_mt) and x) + end + local function table_3f(x) + return ((type(x) == "table") and not varg_3f(x) and (getmetatable(x) ~= list_mt) and (getmetatable(x) ~= symbol_mt) and not comment_3f(x) and x) + end + local function kv_table_3f(t) + if table_3f(t) then + local nxt, t0, k = pairs(t) + local len0 = #t0 + local next_state = nil + if (0 == len0) then + next_state = k + else + next_state = len0 + end + return ((nil ~= nxt(t0, next_state)) and t0) + end + end + local function string_3f(x) + if (type(x) == "string") then + return x + else + return false + end + end + local function multi_sym_3f(str) + if sym_3f(str) then + return multi_sym_3f(tostring(str)) + elseif (type(str) ~= "string") then + return false + else + local function _160_() + local parts = {} + for part in str:gmatch("[^%.%:]+[%.%:]?") do + local last_char = part:sub(-1) + if (last_char == ":") then + parts["multi-sym-method-call"] = true + end + if ((last_char == ":") or (last_char == ".")) then + parts[(#parts + 1)] = part:sub(1, -2) + else + parts[(#parts + 1)] = part + end + end + return (next(parts) and parts) + end + return ((str:match("%.") or str:match(":")) and not str:match("%.%.") and (str:byte() ~= string.byte(".")) and (str:byte() ~= string.byte(":")) and (str:byte(-1) ~= string.byte(".")) and (str:byte(-1) ~= string.byte(":")) and _160_()) + end + end + local function call_of_3f(ast, callee) + return (list_3f(ast) and sym_3f(ast[1], callee)) + end + local function quoted_3f(symbol) + return symbol.quoted + end + local function idempotent_expr_3f(x) + local t = type(x) + return ((t == "string") or (t == "number") or (t == "boolean") or (sym_3f(x) and not multi_sym_3f(x))) + end + local function walk_tree(root, f, _3fcustom_iterator) + local function walk(iterfn, parent, idx, node) + if (f(idx, node, parent) and not sym_3f(node)) then + for k, v in iterfn(node) do + walk(iterfn, node, k, v) + end + return nil + end + end + walk((_3fcustom_iterator or pairs), nil, nil, root) + return root + end + local root = nil + local function _165_() + end + root = {chunk = nil, options = nil, reset = _165_, scope = nil} + root["set-reset"] = function(_166_0) + local _167_ = _166_0 + local chunk = _167_["chunk"] + local options = _167_["options"] + local reset = _167_["reset"] + local scope = _167_["scope"] + root.reset = function() + root.chunk, root.scope, root.options, root.reset = chunk, scope, options, reset + return nil + end + return root.reset + end + local lua_keywords = {["and"] = true, ["break"] = true, ["do"] = true, ["else"] = true, ["elseif"] = true, ["end"] = true, ["false"] = true, ["for"] = true, ["function"] = true, ["goto"] = true, ["if"] = true, ["in"] = true, ["local"] = true, ["nil"] = true, ["not"] = true, ["or"] = true, ["repeat"] = true, ["return"] = true, ["then"] = true, ["true"] = true, ["until"] = true, ["while"] = true} + local function lua_keyword_3f(str) + local function _169_() + local _168_0 = root.options + if (nil ~= _168_0) then + _168_0 = _168_0.keywords + end + if (nil ~= _168_0) then + _168_0 = _168_0[str] + end + return _168_0 + end + return (lua_keywords[str] or _169_()) + end + local function valid_lua_identifier_3f(str) + return (str:match("^[%a_][%w_]*$") and not lua_keyword_3f(str)) + end + local propagated_options = {"allowedGlobals", "indent", "correlate", "useMetadata", "env", "compiler-env", "compilerEnv"} + local function propagate_options(options, subopts) + local tbl_14_ = subopts + for _, name in ipairs(propagated_options) do + local k_15_, v_16_ = name, options[name] + if ((k_15_ ~= nil) and (v_16_ ~= nil)) then + tbl_14_[k_15_] = v_16_ + end + end + return tbl_14_ + end + local function ast_source(ast) + if (table_3f(ast) or sequence_3f(ast)) then + return (getmetatable(ast) or {}) + elseif ("table" == type(ast)) then + return ast + else + return {} + end + end + local function warn(msg, _3fast, _3ffilename, _3fline, _3fcol) + local _174_0 = nil + do + local _175_0 = root.options + if (nil ~= _175_0) then + _175_0 = _175_0.warn + end + _174_0 = _175_0 + end + if (nil ~= _174_0) then + local opt_warn = _174_0 + return opt_warn(msg, _3fast, _3ffilename, _3fline, _3fcol) + else + local _ = _174_0 + if (_G.io and _G.io.stderr) then + local loc = nil + do + local _177_0 = ast_source(_3fast) + if ((_G.type(_177_0) == "table") and (nil ~= _177_0.col) and (nil ~= _177_0.filename) and (nil ~= _177_0.line)) then + local col = _177_0.col + local filename = _177_0.filename + local line = _177_0.line + loc = (filename .. ":" .. line .. ":" .. col .. ": ") + else + local _0 = _177_0 + if (_3ffilename and _3fline and _3fcol) then + loc = (_3ffilename .. ":" .. _3fline .. ":" .. _3fcol .. ": ") + else + loc = "" + end + end + end + return (_G.io.stderr):write(("--WARNING: %s%s\n"):format(loc, msg)) + end + end + end + local warned = {} + local function check_plugin_version(_182_0) + local _183_ = _182_0 + local plugin = _183_ + local name = _183_["name"] + local versions = _183_["versions"] + if (not member_3f(version:gsub("-dev", ""), (versions or {})) and not (string_3f(versions) and version:find(versions)) and not warned[plugin]) then + warned[plugin] = true + return warn(string.format("plugin %s does not support Fennel version %s", (name or "unknown"), version)) + end + end + local function hook_opts(event, _3foptions, ...) + local plugins = nil + local function _186_(...) + local _185_0 = _3foptions + if (nil ~= _185_0) then + _185_0 = _185_0.plugins + end + return _185_0 + end + local function _189_(...) + local _188_0 = root.options + if (nil ~= _188_0) then + _188_0 = _188_0.plugins + end + return _188_0 + end + plugins = (_186_(...) or _189_(...)) + if plugins then + local result = nil + for _, plugin in ipairs(plugins) do + if (nil ~= result) then break end + check_plugin_version(plugin) + local _191_0 = plugin[event] + if (nil ~= _191_0) then + local f = _191_0 + result = f(...) + else + result = nil + end + end + return result + end + end + local function hook(event, ...) + return hook_opts(event, root.options, ...) + end + return {["ast-source"] = ast_source, ["call-of?"] = call_of_3f, ["comment?"] = comment_3f, ["debug-on?"] = debug_on_3f, ["every?"] = every_3f, ["expr?"] = expr_3f, ["fennel-module"] = nil, ["get-in"] = get_in, ["hook-opts"] = hook_opts, ["idempotent-expr?"] = idempotent_expr_3f, ["kv-table?"] = kv_table_3f, ["list?"] = list_3f, ["lua-keyword?"] = lua_keyword_3f, ["macro-path"] = table.concat({"./?.fnlm", "./?/init.fnlm", "./?.fnl", "./?/init-macros.fnl", "./?/init.fnl", getenv("FENNEL_MACRO_PATH")}, ";"), ["member?"] = member_3f, ["multi-sym?"] = multi_sym_3f, ["propagate-options"] = propagate_options, ["quoted?"] = quoted_3f, ["runtime-version"] = runtime_version, ["sequence?"] = sequence_3f, ["string?"] = string_3f, ["sym?"] = sym_3f, ["table?"] = table_3f, ["valid-lua-identifier?"] = valid_lua_identifier_3f, ["varg?"] = varg_3f, ["walk-tree"] = walk_tree, allpairs = allpairs, comment = comment_2a, copy = copy, expr = expr, hook = hook, len = len, list = list, maxn = maxn, pack = pack, path = table.concat({"./?.fnl", "./?/init.fnl", getenv("FENNEL_PATH")}, ";"), root = root, sequence = sequence, stablepairs = stablepairs, sym = sym, unpack = unpack, varg = varg, version = version, warn = warn} +end +utils = require("eca.nfnl.fennel.utils") +local parser = require("eca.nfnl.fennel.parser") +local compiler = require("eca.nfnl.fennel.compiler") +local specials = require("eca.nfnl.fennel.specials") +local repl = require("eca.nfnl.fennel.repl") +local view = require("eca.nfnl.fennel.view") +local function eval_env(env, opts) + if (env == "_COMPILER") then + local env0 = specials["make-compiler-env"](nil, compiler.scopes.compiler, {}, opts) + do + local tbl_14_ = env0 + for k, v in pairs((opts["extra-env"] or {})) do + local k_15_, v_16_ = k, v + if ((k_15_ ~= nil) and (v_16_ ~= nil)) then + tbl_14_[k_15_] = v_16_ + end + end + end + if (opts.allowedGlobals == nil) then + opts.allowedGlobals = specials["current-global-names"](env0) + end + return specials["wrap-env"](env0) + else + return (env and specials["wrap-env"](env)) + end +end +local function eval_opts(options, str) + local opts = utils.copy(options) + if (opts.allowedGlobals == nil) then + opts.allowedGlobals = specials["current-global-names"](opts.env) + end + if (not opts.filename and not opts.source) then + opts.source = str + end + if (opts.env == "_COMPILER") then + opts.scope = compiler["make-scope"](compiler.scopes.compiler) + end + return opts +end +local function eval(str, _3foptions, ...) + local opts = eval_opts(_3foptions, str) + local env = eval_env(opts.env, opts) + local lua_source = compiler["compile-string"](str, opts) + local loader = nil + local function _910_(...) + if opts.filename then + return ("@" .. opts.filename) + else + return str + end + end + loader = specials["load-code"](lua_source, env, _910_(...)) + opts.filename = nil + return loader(...) +end +local function dofile_2a(filename, _3foptions, ...) + local opts = utils.copy(_3foptions) + local f = assert(io.open(filename, "rb")) + local source = assert(f:read("*all"), ("Could not read " .. filename)) + f:close() + opts.filename = filename + return eval(source, opts, ...) +end +local function syntax() + local body_3f = {"when", "with-open", "collect", "icollect", "fcollect", "lambda", "\206\187", "macro", "match", "match-try", "case", "case-try", "accumulate", "faccumulate", "doto"} + local binding_3f = {"collect", "icollect", "fcollect", "each", "for", "let", "with-open", "accumulate", "faccumulate"} + local define_3f = {"fn", "lambda", "\206\187", "var", "local", "macro", "macros", "global"} + local deprecated = {"~=", "#", "global", "require-macros", "pick-args"} + local out = {} + for k, v in pairs(compiler.scopes.global.specials) do + local metadata = (compiler.metadata[v] or {}) + out[k] = {["binding-form?"] = utils["member?"](k, binding_3f), ["body-form?"] = metadata["fnl/body-form?"], ["define?"] = utils["member?"](k, define_3f), ["deprecated?"] = utils["member?"](k, deprecated), ["special?"] = true} + end + for k in pairs(compiler.scopes.global.macros) do + out[k] = {["binding-form?"] = utils["member?"](k, binding_3f), ["body-form?"] = utils["member?"](k, body_3f), ["define?"] = utils["member?"](k, define_3f), ["macro?"] = true} + end + for k, v in pairs(_G) do + local _911_0 = type(v) + if (_911_0 == "function") then + out[k] = {["function?"] = true, ["global?"] = true} + elseif (_911_0 == "table") then + if not k:find("^_") then + for k2, v2 in pairs(v) do + if ("function" == type(v2)) then + out[(k .. "." .. k2)] = {["function?"] = true, ["global?"] = true} + end + end + out[k] = {["global?"] = true} + end + end + end + return out +end +local mod = {["ast-source"] = utils["ast-source"], ["comment?"] = utils["comment?"], ["compile-stream"] = compiler["compile-stream"], ["compile-string"] = compiler["compile-string"], ["list?"] = utils["list?"], ["load-code"] = specials["load-code"], ["macro-loaded"] = specials["macro-loaded"], ["macro-path"] = utils["macro-path"], ["macro-searchers"] = specials["macro-searchers"], ["make-searcher"] = specials["make-searcher"], ["multi-sym?"] = utils["multi-sym?"], ["runtime-version"] = utils["runtime-version"], ["search-module"] = specials["search-module"], ["sequence?"] = utils["sequence?"], ["string-stream"] = parser["string-stream"], ["sym-char?"] = parser["sym-char?"], ["sym?"] = utils["sym?"], ["table?"] = utils["table?"], ["varg?"] = utils["varg?"], comment = utils.comment, compile = compiler.compile, compile1 = compiler.compile1, compileStream = compiler["compile-stream"], compileString = compiler["compile-string"], doc = specials.doc, dofile = dofile_2a, eval = eval, gensym = compiler.gensym, getinfo = compiler.getinfo, granulate = parser.granulate, list = utils.list, loadCode = specials["load-code"], macroLoaded = specials["macro-loaded"], macroPath = utils["macro-path"], macroSearchers = specials["macro-searchers"], makeSearcher = specials["make-searcher"], make_searcher = specials["make-searcher"], mangle = compiler["global-mangling"], metadata = compiler.metadata, parser = parser.parser, path = utils.path, repl = repl, runtimeVersion = utils["runtime-version"], scope = compiler["make-scope"], searchModule = specials["search-module"], searcher = specials["make-searcher"](), sequence = utils.sequence, stringStream = parser["string-stream"], sym = utils.sym, syntax = syntax, traceback = compiler.traceback, unmangle = compiler["global-unmangling"], varg = utils.varg, version = utils.version, view = view} +mod.install = function(_3fopts) + table.insert((package.searchers or package.loaders), specials["make-searcher"](_3fopts)) + return mod +end +utils["fennel-module"] = mod +local function load_macros(src, env) + local chunk = assert(specials["load-code"](src, env)) + for k, v in pairs(chunk(utils, specials["get-function-metadata"])) do + compiler.scopes.global.macros[k] = v + end + return nil +end +do + local env = specials["make-compiler-env"](nil, compiler.scopes.compiler, {}) + load_macros([===[local utils, get_function_metadata = ... + local function copy(t) + local out = {} + for _, v in ipairs(t) do + table.insert(out, v) + end + return setmetatable(out, getmetatable(t)) + end + utils['fennel-module'].metadata:setall(copy, "fnl/arglist", {"t"}) + local function __3e_2a(val, ...) + local x = val + for _, e in ipairs({...}) do + local elt = nil + if _G["list?"](e) then + elt = copy(e) + else + elt = list(e) + end + table.insert(elt, 2, x) + x = elt + end + return x + end + utils['fennel-module'].metadata:setall(__3e_2a, "fnl/arglist", {"val", "..."}, "fnl/docstring", "Thread-first macro.\nTake the first value and splice it into the second form as its first argument.\nThe value of the second form is spliced into the first arg of the third, etc.") + local function __3e_3e_2a(val, ...) + local x = val + for _, e in ipairs({...}) do + local elt = nil + if _G["list?"](e) then + elt = copy(e) + else + elt = list(e) + end + table.insert(elt, x) + x = elt + end + return x + end + utils['fennel-module'].metadata:setall(__3e_3e_2a, "fnl/arglist", {"val", "..."}, "fnl/docstring", "Thread-last macro.\nSame as ->, except splices the value into the last position of each form\nrather than the first.") + local function __3f_3e_2a(val, _3fe, ...) + if (nil == _3fe) then + return val + elseif not utils["idempotent-expr?"](val) then + return setmetatable({filename="src/fennel/macros.fnl", line=43, bytestart=1272, sym('let', nil, {quoted=true, filename="src/fennel/macros.fnl", line=43}), setmetatable({sym('tmp_3_', nil, {filename="src/fennel/macros.fnl", line=43}), val}, {filename="src/fennel/macros.fnl", line=43}), setmetatable({filename="src/fennel/macros.fnl", line=44, bytestart=1297, sym('-?>', nil, {quoted=true, filename="src/fennel/macros.fnl", line=44}), sym('tmp_3_', nil, {filename="src/fennel/macros.fnl", line=44}), _3fe, ...}, getmetatable(list()))}, getmetatable(list())) + else + local call = nil + if _G["list?"](_3fe) then + call = copy(_3fe) + else + call = list(_3fe) + end + table.insert(call, 2, val) + return setmetatable({filename="src/fennel/macros.fnl", line=47, bytestart=1415, sym('if', nil, {quoted=true, filename="src/fennel/macros.fnl", line=47}), setmetatable({filename="src/fennel/macros.fnl", line=47, bytestart=1419, sym('not=', nil, {quoted=true, filename="src/fennel/macros.fnl", line=47}), sym('nil', nil, {quoted=true, filename="src/fennel/macros.fnl", line=47}), val}, getmetatable(list())), __3f_3e_2a(call, ...)}, getmetatable(list())) + end + end + utils['fennel-module'].metadata:setall(__3f_3e_2a, "fnl/arglist", {"val", "?e", "..."}, "fnl/docstring", "Nil-safe thread-first macro.\nSame as -> except will short-circuit with nil when it encounters a nil value.") + local function __3f_3e_3e_2a(val, _3fe, ...) + if (nil == _3fe) then + return val + elseif not utils["idempotent-expr?"](val) then + return setmetatable({filename="src/fennel/macros.fnl", line=57, bytestart=1725, sym('let', nil, {quoted=true, filename="src/fennel/macros.fnl", line=57}), setmetatable({sym('tmp_6_', nil, {filename="src/fennel/macros.fnl", line=57}), val}, {filename="src/fennel/macros.fnl", line=57}), setmetatable({filename="src/fennel/macros.fnl", line=58, bytestart=1750, sym('-?>>', nil, {quoted=true, filename="src/fennel/macros.fnl", line=58}), sym('tmp_6_', nil, {filename="src/fennel/macros.fnl", line=58}), _3fe, ...}, getmetatable(list()))}, getmetatable(list())) + else + local call = nil + if _G["list?"](_3fe) then + call = copy(_3fe) + else + call = list(_3fe) + end + table.insert(call, val) + return setmetatable({filename="src/fennel/macros.fnl", line=61, bytestart=1867, sym('if', nil, {quoted=true, filename="src/fennel/macros.fnl", line=61}), setmetatable({filename="src/fennel/macros.fnl", line=61, bytestart=1871, sym('not=', nil, {quoted=true, filename="src/fennel/macros.fnl", line=61}), val, sym('nil', nil, {quoted=true, filename="src/fennel/macros.fnl", line=61})}, getmetatable(list())), __3f_3e_3e_2a(call, ...)}, getmetatable(list())) + end + end + utils['fennel-module'].metadata:setall(__3f_3e_3e_2a, "fnl/arglist", {"val", "?e", "..."}, "fnl/docstring", "Nil-safe thread-last macro.\nSame as ->> except will short-circuit with nil when it encounters a nil value.") + local function _3fdot(tbl, ...) + local head = gensym("t") + local lookups = setmetatable({filename="src/fennel/macros.fnl", line=69, bytestart=2122, sym('do', nil, {quoted=true, filename="src/fennel/macros.fnl", line=69}), setmetatable({filename="src/fennel/macros.fnl", line=70, bytestart=2145, sym('var', nil, {quoted=true, filename="src/fennel/macros.fnl", line=70}), head, tbl}, getmetatable(list())), head}, getmetatable(list())) + for i, k in ipairs({...}) do + table.insert(lookups, (i + 2), setmetatable({filename="src/fennel/macros.fnl", line=76, bytestart=2433, sym('if', nil, {quoted=true, filename="src/fennel/macros.fnl", line=76}), setmetatable({filename="src/fennel/macros.fnl", line=76, bytestart=2437, sym('not=', nil, {quoted=true, filename="src/fennel/macros.fnl", line=76}), sym('nil', nil, {quoted=true, filename="src/fennel/macros.fnl", line=76}), head}, getmetatable(list())), setmetatable({filename="src/fennel/macros.fnl", line=76, bytestart=2454, sym('set', nil, {quoted=true, filename="src/fennel/macros.fnl", line=76}), head, setmetatable({filename="src/fennel/macros.fnl", line=76, bytestart=2465, sym('.', nil, {quoted=true, filename="src/fennel/macros.fnl", line=76}), head, k}, getmetatable(list()))}, getmetatable(list()))}, getmetatable(list()))) + end + return lookups + end + utils['fennel-module'].metadata:setall(_3fdot, "fnl/arglist", {"tbl", "..."}, "fnl/docstring", "Nil-safe table look up.\nSame as . (dot), except will short-circuit with nil when it encounters\na nil value in any of subsequent keys.") + local function doto_2a(val, ...) + assert((val ~= nil), "missing subject") + if not utils["idempotent-expr?"](val) then + return setmetatable({filename="src/fennel/macros.fnl", line=83, bytestart=2683, sym('let', nil, {quoted=true, filename="src/fennel/macros.fnl", line=83}), setmetatable({sym('tmp_9_', nil, {filename="src/fennel/macros.fnl", line=83}), val}, {filename="src/fennel/macros.fnl", line=83}), setmetatable({filename="src/fennel/macros.fnl", line=84, bytestart=2707, sym('doto', nil, {quoted=true, filename="src/fennel/macros.fnl", line=84}), sym('tmp_9_', nil, {filename="src/fennel/macros.fnl", line=84}), ...}, getmetatable(list()))}, getmetatable(list())) + else + local form = setmetatable({filename="src/fennel/macros.fnl", line=85, bytestart=2741, sym('do', nil, {quoted=true, filename="src/fennel/macros.fnl", line=85})}, getmetatable(list())) + for _, elt in ipairs({...}) do + local elt0 = nil + if _G["list?"](elt) then + elt0 = copy(elt) + else + elt0 = list(elt) + end + table.insert(elt0, 2, val) + table.insert(form, elt0) + end + table.insert(form, val) + return form + end + end + utils['fennel-module'].metadata:setall(doto_2a, "fnl/arglist", {"val", "..."}, "fnl/docstring", "Evaluate val and splice it into the first argument of subsequent forms.") + local function when_2a(condition, body1, ...) + assert(body1, "expected body") + return setmetatable({filename="src/fennel/macros.fnl", line=96, bytestart=3090, sym('if', nil, {quoted=true, filename="src/fennel/macros.fnl", line=96}), condition, setmetatable({filename="src/fennel/macros.fnl", line=97, bytestart=3112, sym('do', nil, {quoted=true, filename="src/fennel/macros.fnl", line=97}), body1, ...}, getmetatable(list()))}, getmetatable(list())) + end + utils['fennel-module'].metadata:setall(when_2a, "fnl/arglist", {"condition", "body1", "..."}, "fnl/docstring", "Evaluate body for side-effects only when condition is truthy.") + local function with_open_2a(closable_bindings, ...) + local vararg_3f = _G["get-scope"]().vararg + local bodyfn = nil + if vararg_3f then + bodyfn = setmetatable({filename="src/fennel/macros.fnl", line=107, bytestart=3481, sym('fn', nil, {quoted=true, filename="src/fennel/macros.fnl", line=107}), setmetatable({_VARARG}, {filename="src/fennel/macros.fnl", line=107}), ...}, getmetatable(list())) + else + bodyfn = setmetatable({filename="src/fennel/macros.fnl", line=108, bytestart=3517, sym('fn', nil, {quoted=true, filename="src/fennel/macros.fnl", line=108}), setmetatable({}, {filename="src/fennel/macros.fnl", line=108}), ...}, getmetatable(list())) + end + local closer = setmetatable({filename="src/fennel/macros.fnl", line=109, bytestart=3547, sym('fn', nil, {quoted=true, filename="src/fennel/macros.fnl", line=109}), sym('close-handlers_13_', nil, {filename="src/fennel/macros.fnl", line=109}), setmetatable({sym('ok_14_', nil, {filename="src/fennel/macros.fnl", line=109}), _VARARG}, {filename="src/fennel/macros.fnl", line=109}), setmetatable({filename="src/fennel/macros.fnl", line=110, bytestart=3595, sym('if', nil, {quoted=true, filename="src/fennel/macros.fnl", line=110}), sym('ok_14_', nil, {filename="src/fennel/macros.fnl", line=110}), _VARARG, setmetatable({filename="src/fennel/macros.fnl", line=110, bytestart=3607, sym('error', nil, {quoted=true, filename="src/fennel/macros.fnl", line=110}), _VARARG, 0}, getmetatable(list()))}, getmetatable(list()))}, getmetatable(list())) + local traceback = setmetatable({filename="src/fennel/macros.fnl", line=111, bytestart=3642, sym('.', nil, {quoted=true, filename="src/fennel/macros.fnl", line=111}), setmetatable({filename="src/fennel/macros.fnl", line=111, bytestart=3645, sym('or', nil, {quoted=true, filename="src/fennel/macros.fnl", line=111}), setmetatable({filename="src/fennel/macros.fnl", line=111, bytestart=3649, sym('?.', nil, {quoted=true, filename="src/fennel/macros.fnl", line=111}), sym('_G', nil, {quoted=true, filename="src/fennel/macros.fnl", line=111}), "package", "loaded", _G["fennel-module-name"]()}, getmetatable(list())), sym('_G.debug', nil, {quoted=true, filename="src/fennel/macros.fnl", line=112}), setmetatable({["traceback"]=setmetatable({filename=nil, line=nil, bytestart=nil, sym('hashfn', nil, {quoted=true, filename=nil, line=nil}), ""}, getmetatable(list()))}, {filename="src/fennel/macros.fnl", line=112})}, getmetatable(list())), "traceback"}, getmetatable(list())) + for i = 1, #closable_bindings, 2 do + assert(_G["sym?"](closable_bindings[i]), "with-open only allows symbols in bindings") + table.insert(closer, 4, setmetatable({filename="src/fennel/macros.fnl", line=116, bytestart=3940, sym(':', nil, {quoted=true, filename="src/fennel/macros.fnl", line=116}), closable_bindings[i], "close"}, getmetatable(list()))) + end + local function _18_(...) + if vararg_3f then + return setmetatable({filename="src/fennel/macros.fnl", line=122, bytestart=4147, sym('let', nil, {quoted=true, filename="src/fennel/macros.fnl", line=122}), setmetatable({sym('args_15_', nil, {filename="src/fennel/macros.fnl", line=122}), setmetatable({_VARARG}, {filename="src/fennel/macros.fnl", line=122}), sym('n_16_', nil, {filename="src/fennel/macros.fnl", line=123}), setmetatable({filename="src/fennel/macros.fnl", line=123, bytestart=4188, sym('select', nil, {quoted=true, filename="src/fennel/macros.fnl", line=123}), "#", _VARARG}, getmetatable(list())), sym('unpack_17_', nil, {filename="src/fennel/macros.fnl", line=124}), setmetatable({filename="src/fennel/macros.fnl", line=124, bytestart=4232, sym('or', nil, {quoted=true, filename="src/fennel/macros.fnl", line=124}), sym('_G.unpack', nil, {quoted=true, filename="src/fennel/macros.fnl", line=124}), sym('_G.table.unpack', nil, {quoted=true, filename="src/fennel/macros.fnl", line=124})}, getmetatable(list()))}, {filename="src/fennel/macros.fnl", line=122}), setmetatable({filename="src/fennel/macros.fnl", line=125, bytestart=4280, sym('_G.xpcall', nil, {quoted=true, filename="src/fennel/macros.fnl", line=125}), setmetatable({filename=nil, line=nil, bytestart=nil, sym('hashfn', nil, {quoted=true, filename=nil, line=nil}), setmetatable({filename="src/fennel/macros.fnl", line=125, bytestart=4292, bodyfn, setmetatable({filename="src/fennel/macros.fnl", line=125, bytestart=4301, sym('unpack_17_', nil, {filename="src/fennel/macros.fnl", line=125}), sym('args_15_', nil, {filename="src/fennel/macros.fnl", line=125}), 1, sym('n_16_', nil, {filename="src/fennel/macros.fnl", line=125})}, getmetatable(list()))}, getmetatable(list()))}, getmetatable(list())), traceback}, getmetatable(list()))}, getmetatable(list())) + else + return setmetatable({filename="src/fennel/macros.fnl", line=126, bytestart=4350, sym('_G.xpcall', nil, {quoted=true, filename="src/fennel/macros.fnl", line=126}), bodyfn, traceback}, getmetatable(list())) + end + end + return setmetatable({filename="src/fennel/macros.fnl", line=117, bytestart=3983, sym('let', nil, {quoted=true, filename="src/fennel/macros.fnl", line=117}), closable_bindings, closer, setmetatable({filename="src/fennel/macros.fnl", line=119, bytestart=4029, sym('close-handlers_13_', nil, {filename="src/fennel/macros.fnl", line=119}), _18_(...)}, getmetatable(list()))}, getmetatable(list())) + end + utils['fennel-module'].metadata:setall(with_open_2a, "fnl/arglist", {"closable-bindings", "..."}, "fnl/docstring", "Like `let`, but invokes (v:close) on each binding after evaluating the body.\nThe body is evaluated inside `xpcall` so that bound values will be closed upon\nencountering an error before propagating it.") + local function extract_into(iter_tbl, iter_out) + local into, found_3f = {} + for i = #iter_tbl, 2, -1 do + local item = iter_tbl[i] + if (_G["sym?"](item, "&into") or ("into" == item)) then + assert(not found_3f, "expected only one &into clause") + found_3f = true + into = iter_tbl[(i + 1)] + table.remove(iter_out, i) + table.remove(iter_out, i) + end + end + assert((not found_3f or _G["sym?"](into) or _G["table?"](into) or _G["list?"](into)), "expected table, function call, or symbol in &into clause") + return (found_3f and into), iter_out + end + utils['fennel-module'].metadata:setall(extract_into, "fnl/arglist", {"iter-tbl", "iter-out"}) + local function collect_2a(iter_tbl, key_expr, value_expr, ...) + do local _ = {["fnl/arglist"] = {{key, value, _G["*iterator-values"]}, _G["values-tuple"]}} end + assert((_G["sequence?"](iter_tbl) and (2 <= #iter_tbl)), "expected iterator binding table") + assert((nil ~= key_expr), "expected key and value expression") + assert((nil == ...), "expected 1 or 2 body expressions; wrap multiple expressions with do") + assert((value_expr or _G["list?"](key_expr)), "need key and value") + local kv_expr = nil + if (nil == value_expr) then + kv_expr = key_expr + else + kv_expr = setmetatable({filename="src/fennel/macros.fnl", line=174, bytestart=6326, sym('values', nil, {quoted=true, filename="src/fennel/macros.fnl", line=174}), key_expr, value_expr}, getmetatable(list())) + end + local into, intoless_iter = extract_into(iter_tbl, copy(iter_tbl)) + return setmetatable({filename="src/fennel/macros.fnl", line=176, bytestart=6433, sym('let', nil, {quoted=true, filename="src/fennel/macros.fnl", line=176}), setmetatable({sym('tbl_21_', nil, {filename="src/fennel/macros.fnl", line=176}), (into or {})}, {filename="src/fennel/macros.fnl", line=176}), setmetatable({filename="src/fennel/macros.fnl", line=177, bytestart=6466, sym('each', nil, {quoted=true, filename="src/fennel/macros.fnl", line=177}), intoless_iter, setmetatable({filename="src/fennel/macros.fnl", line=178, bytestart=6496, sym('let', nil, {quoted=true, filename="src/fennel/macros.fnl", line=178}), setmetatable({setmetatable({filename="src/fennel/macros.fnl", line=178, bytestart=6502, sym('k_22_', nil, {filename="src/fennel/macros.fnl", line=178}), sym('v_23_', nil, {filename="src/fennel/macros.fnl", line=178})}, getmetatable(list())), kv_expr}, {filename="src/fennel/macros.fnl", line=178}), setmetatable({filename="src/fennel/macros.fnl", line=179, bytestart=6531, sym('if', nil, {quoted=true, filename="src/fennel/macros.fnl", line=179}), setmetatable({filename="src/fennel/macros.fnl", line=179, bytestart=6535, sym('and', nil, {quoted=true, filename="src/fennel/macros.fnl", line=179}), setmetatable({filename="src/fennel/macros.fnl", line=179, bytestart=6540, sym('not=', nil, {quoted=true, filename="src/fennel/macros.fnl", line=179}), sym('k_22_', nil, {filename="src/fennel/macros.fnl", line=179}), sym('nil', nil, {quoted=true, filename="src/fennel/macros.fnl", line=179})}, getmetatable(list())), setmetatable({filename="src/fennel/macros.fnl", line=179, bytestart=6554, sym('not=', nil, {quoted=true, filename="src/fennel/macros.fnl", line=179}), sym('v_23_', nil, {filename="src/fennel/macros.fnl", line=179}), sym('nil', nil, {quoted=true, filename="src/fennel/macros.fnl", line=179})}, getmetatable(list()))}, getmetatable(list())), setmetatable({filename="src/fennel/macros.fnl", line=180, bytestart=6582, sym('tset', nil, {quoted=true, filename="src/fennel/macros.fnl", line=180}), sym('tbl_21_', nil, {filename="src/fennel/macros.fnl", line=180}), sym('k_22_', nil, {filename="src/fennel/macros.fnl", line=180}), sym('v_23_', nil, {filename="src/fennel/macros.fnl", line=180})}, getmetatable(list()))}, getmetatable(list()))}, getmetatable(list()))}, getmetatable(list())), sym('tbl_21_', nil, {filename="src/fennel/macros.fnl", line=181})}, getmetatable(list())) + end + utils['fennel-module'].metadata:setall(collect_2a, "fnl/arglist", {"iter-tbl", "key-expr", "value-expr", "..."}, "fnl/docstring", "Return a table made by running an iterator and evaluating an expression that\nreturns key-value pairs to be inserted sequentially into the table. This can\nbe thought of as a table comprehension. The body should provide two expressions\n(used as key and value) or nil, which causes it to be omitted.\n\nFor example,\n (collect [k v (pairs {:apple \"red\" :orange \"orange\"})]\n (values v k))\nreturns\n {:red \"apple\" :orange \"orange\"}\n\nSupports an &into clause after the iterator to put results in an existing table.\nSupports early termination with an &until clause.\n\nSupports two separate body forms instead of one to bind the key and value\nseparately.\n\nFor example,\n (collect [k v (pairs {:apple \"red\" :orange \"orange\"})]\n (.. v \" fruit\")\n (.. k \"-color\"))\nreturns\n {:red-color \"apple fruit\" :orange-color \"orange fruit\"}") + local function seq_collect(how, iter_tbl, value_expr, ...) + assert((nil ~= value_expr), "expected table value expression") + assert((nil == ...), "expected exactly one body expression. Wrap multiple expressions in do") + local into, intoless_iter = extract_into(iter_tbl, copy(iter_tbl)) + if into then + return setmetatable({filename="src/fennel/macros.fnl", line=193, bytestart=7116, sym('let', nil, {quoted=true, filename="src/fennel/macros.fnl", line=193}), setmetatable({sym('tbl_24_', nil, {filename="src/fennel/macros.fnl", line=193}), into}, {filename="src/fennel/macros.fnl", line=193}), setmetatable({filename="src/fennel/macros.fnl", line=194, bytestart=7145, how, intoless_iter, setmetatable({filename="src/fennel/macros.fnl", line=194, bytestart=7166, sym('let', nil, {quoted=true, filename="src/fennel/macros.fnl", line=194}), setmetatable({sym('val_25_', nil, {filename="src/fennel/macros.fnl", line=194}), value_expr}, {filename="src/fennel/macros.fnl", line=194}), setmetatable({filename="src/fennel/macros.fnl", line=195, bytestart=7224, sym('table.insert', nil, {quoted=true, filename="src/fennel/macros.fnl", line=195}), sym('tbl_24_', nil, {filename="src/fennel/macros.fnl", line=195}), sym('val_25_', nil, {filename="src/fennel/macros.fnl", line=195})}, getmetatable(list()))}, getmetatable(list()))}, getmetatable(list())), sym('tbl_24_', nil, {filename="src/fennel/macros.fnl", line=196})}, getmetatable(list())) + else + return setmetatable({filename="src/fennel/macros.fnl", line=200, bytestart=7500, sym('let', nil, {quoted=true, filename="src/fennel/macros.fnl", line=200}), setmetatable({sym('tbl_26_', nil, {filename="src/fennel/macros.fnl", line=200}), setmetatable({}, {filename="src/fennel/macros.fnl", line=200})}, {filename="src/fennel/macros.fnl", line=200}), setmetatable({filename="src/fennel/macros.fnl", line=201, bytestart=7526, sym('var', nil, {quoted=true, filename="src/fennel/macros.fnl", line=201}), sym('i_27_', nil, {filename="src/fennel/macros.fnl", line=201}), 0}, getmetatable(list())), setmetatable({filename="src/fennel/macros.fnl", line=202, bytestart=7548, how, iter_tbl, setmetatable({filename="src/fennel/macros.fnl", line=203, bytestart=7581, sym('let', nil, {quoted=true, filename="src/fennel/macros.fnl", line=203}), setmetatable({sym('val_28_', nil, {filename="src/fennel/macros.fnl", line=203}), value_expr}, {filename="src/fennel/macros.fnl", line=203}), setmetatable({filename="src/fennel/macros.fnl", line=204, bytestart=7624, sym('when', nil, {quoted=true, filename="src/fennel/macros.fnl", line=204}), setmetatable({filename="src/fennel/macros.fnl", line=204, bytestart=7630, sym('not=', nil, {quoted=true, filename="src/fennel/macros.fnl", line=204}), sym('nil', nil, {quoted=true, filename="src/fennel/macros.fnl", line=204}), sym('val_28_', nil, {filename="src/fennel/macros.fnl", line=204})}, getmetatable(list())), setmetatable({filename="src/fennel/macros.fnl", line=205, bytestart=7667, sym('set', nil, {quoted=true, filename="src/fennel/macros.fnl", line=205}), sym('i_27_', nil, {filename="src/fennel/macros.fnl", line=205}), setmetatable({filename="src/fennel/macros.fnl", line=205, bytestart=7675, sym('+', nil, {quoted=true, filename="src/fennel/macros.fnl", line=205}), sym('i_27_', nil, {filename="src/fennel/macros.fnl", line=205}), 1}, getmetatable(list()))}, getmetatable(list())), setmetatable({filename="src/fennel/macros.fnl", line=206, bytestart=7706, sym('tset', nil, {quoted=true, filename="src/fennel/macros.fnl", line=206}), sym('tbl_26_', nil, {filename="src/fennel/macros.fnl", line=206}), sym('i_27_', nil, {filename="src/fennel/macros.fnl", line=206}), sym('val_28_', nil, {filename="src/fennel/macros.fnl", line=206})}, getmetatable(list()))}, getmetatable(list()))}, getmetatable(list()))}, getmetatable(list())), sym('tbl_26_', nil, {filename="src/fennel/macros.fnl", line=207})}, getmetatable(list())) + end + end + utils['fennel-module'].metadata:setall(seq_collect, "fnl/arglist", {"how", "iter-tbl", "value-expr", "..."}, "fnl/docstring", "Common part between icollect and fcollect for producing sequential tables.\n\nIteration code only differs in using the for or each keyword, the rest\nof the generated code is identical.") + local function icollect_2a(iter_tbl, value_expr, ...) + do local _ = {["fnl/arglist"] = {{index, value, _G["*iterator-values"]}, value_expr}} end + assert((_G["sequence?"](iter_tbl) and (2 <= #iter_tbl)), "expected iterator binding table") + return seq_collect(sym('each', nil, {quoted=true, filename="src/fennel/macros.fnl", line=227}), iter_tbl, value_expr, ...) + end + utils['fennel-module'].metadata:setall(icollect_2a, "fnl/arglist", {"iter-tbl", "value-expr", "..."}, "fnl/docstring", "Return a sequential table made by running an iterator and evaluating an\nexpression that returns values to be inserted sequentially into the table.\nThis can be thought of as a table comprehension. If the body evaluates to nil\nthat element is omitted.\n\nFor example,\n (icollect [_ v (ipairs [1 2 3 4 5])]\n (when (not= v 3)\n (* v v)))\nreturns\n [1 4 16 25]\n\nSupports an &into clause after the iterator to put results in an existing table.\nSupports early termination with an &until clause.") + local function fcollect_2a(iter_tbl, value_expr, ...) + do local _ = {["fnl/arglist"] = {{index, start, stop, _G["?step"]}, value_expr}} end + assert((_G["sequence?"](iter_tbl) and (2 < #iter_tbl)), "expected range binding table") + return seq_collect(sym('for', nil, {quoted=true, filename="src/fennel/macros.fnl", line=247}), iter_tbl, value_expr, ...) + end + utils['fennel-module'].metadata:setall(fcollect_2a, "fnl/arglist", {"iter-tbl", "value-expr", "..."}, "fnl/docstring", "Return a sequential table made by advancing a range as specified by\nfor, and evaluating an expression that returns values to be inserted\nsequentially into the table. This can be thought of as a range\ncomprehension. If the body evaluates to nil that element is omitted.\n\nFor example,\n (fcollect [i 1 10 2]\n (when (not= i 3)\n (* i i)))\nreturns\n [1 25 49 81]\n\nSupports an &into clause after the range to put results in an existing table.\nSupports early termination with an &until clause.") + local function accumulate_impl(for_3f, iter_tbl, body, ...) + assert((_G["sequence?"](iter_tbl) and (4 <= #iter_tbl)), "expected initial value and iterator binding table") + assert((nil ~= body), "expected body expression") + assert((nil == ...), "expected exactly one body expression. Wrap multiple expressions with do") + local _30_ = iter_tbl + local accum_var = _30_[1] + local accum_init = _30_[2] + local iter = nil + local function _31_(...) + if for_3f then + return "for" + else + return "each" + end + end + iter = sym(_31_(...)) + local function _32_(...) + if _G["list?"](accum_var) then + return list(sym("values"), unpack(accum_var)) + else + return accum_var + end + end + return setmetatable({filename="src/fennel/macros.fnl", line=257, bytestart=9697, sym('do', nil, {quoted=true, filename="src/fennel/macros.fnl", line=257}), setmetatable({filename="src/fennel/macros.fnl", line=258, bytestart=9708, sym('var', nil, {quoted=true, filename="src/fennel/macros.fnl", line=258}), accum_var, accum_init}, getmetatable(list())), setmetatable({filename="src/fennel/macros.fnl", line=259, bytestart=9744, iter, {unpack(iter_tbl, 3)}, setmetatable({filename="src/fennel/macros.fnl", line=260, bytestart=9788, sym('set', nil, {quoted=true, filename="src/fennel/macros.fnl", line=260}), accum_var, body}, getmetatable(list()))}, getmetatable(list())), _32_(...)}, getmetatable(list())) + end + utils['fennel-module'].metadata:setall(accumulate_impl, "fnl/arglist", {"for?", "iter-tbl", "body", "..."}) + local function accumulate_2a(iter_tbl, body, ...) + do local _ = {["fnl/arglist"] = {{accumulator, _G["initial-value"], key, value, _G["*iterator-values"]}, _G["value-expr"]}} end + return accumulate_impl(false, iter_tbl, body, ...) + end + utils['fennel-module'].metadata:setall(accumulate_2a, "fnl/arglist", {"iter-tbl", "body", "..."}, "fnl/docstring", "Accumulation macro.\n\nIt takes a binding table and an expression as its arguments. In the binding\ntable, the first form starts out bound to the second value, which is an initial\naccumulator. The rest are an iterator binding table in the format `each` takes.\n\nIt runs through the iterator in each step of which the given expression is\nevaluated, and the accumulator is set to the value of the expression. It\neventually returns the final value of the accumulator.\n\nFor example,\n (accumulate [total 0\n _ n (pairs {:apple 2 :orange 3})]\n (+ total n))\nreturns 5") + local function faccumulate_2a(iter_tbl, body, ...) + do local _ = {["fnl/arglist"] = {{accumulator, _G["initial-value"], index, start, stop, _G["?step"]}, _G["value-expr"]}} end + return accumulate_impl(true, iter_tbl, body, ...) + end + utils['fennel-module'].metadata:setall(faccumulate_2a, "fnl/arglist", {"iter-tbl", "body", "..."}, "fnl/docstring", "Identical to accumulate, but after the accumulator the binding table is the\nsame as `for` instead of `each`. Like collect to fcollect, will iterate over a\nnumerical range like `for` rather than an iterator.") + local function partial_2a(f, ...) + assert(f, "expected a function to partially apply") + local bindings = {} + local args = {} + for _, arg in ipairs({...}) do + if utils["idempotent-expr?"](arg) then + table.insert(args, arg) + else + local name = gensym("partial") + table.insert(bindings, name) + table.insert(bindings, arg) + table.insert(args, name) + end + end + local body = list(f, unpack(args)) + table.insert(body, _VARARG) + if (nil == bindings[1]) then + return setmetatable({filename="src/fennel/macros.fnl", line=307, bytestart=11654, sym('fn', nil, {quoted=true, filename="src/fennel/macros.fnl", line=307}), setmetatable({_VARARG}, {filename="src/fennel/macros.fnl", line=307}), body}, getmetatable(list())) + else + return setmetatable({filename="src/fennel/macros.fnl", line=308, bytestart=11687, sym('let', nil, {quoted=true, filename="src/fennel/macros.fnl", line=308}), bindings, setmetatable({filename="src/fennel/macros.fnl", line=309, bytestart=11715, sym('fn', nil, {quoted=true, filename="src/fennel/macros.fnl", line=309}), setmetatable({_VARARG}, {filename="src/fennel/macros.fnl", line=309}), body}, getmetatable(list()))}, getmetatable(list())) + end + end + utils['fennel-module'].metadata:setall(partial_2a, "fnl/arglist", {"f", "..."}, "fnl/docstring", "Return a function with all arguments partially applied to f.") + local function pick_args_2a(n, f) + if (_G.io and _G.io.stderr) then + do end (_G.io.stderr):write("-- WARNING: pick-args is deprecated and will be removed in the future.\n") + end + local bindings = {} + for i = 1, n do + bindings[i] = gensym("pick") + end + return setmetatable({filename="src/fennel/macros.fnl", line=318, bytestart=12060, sym('fn', nil, {quoted=true, filename="src/fennel/macros.fnl", line=318}), bindings, setmetatable({filename="src/fennel/macros.fnl", line=318, bytestart=12074, f, unpack(bindings)}, getmetatable(list()))}, getmetatable(list())) + end + utils['fennel-module'].metadata:setall(pick_args_2a, "fnl/arglist", {"n", "f"}, "fnl/docstring", "Create a function of arity n that applies its arguments to f. Deprecated.") + local function lambda_2a(...) + local args = {...} + local args_len = #args + local has_internal_name_3f = _G["sym?"](args[1]) + local arglist = nil + if has_internal_name_3f then + arglist = args[2] + else + arglist = args[1] + end + local metadata_position = nil + if has_internal_name_3f then + metadata_position = 3 + else + metadata_position = 2 + end + local _, check_position = get_function_metadata({"lambda", ...}, arglist, metadata_position) + local empty_body_3f = (args_len < check_position) + local function check_21(a) + if _G["table?"](a) then + for _0, a0 in pairs(a) do + check_21(a0) + end + return nil + else + local _38_ + do + local as = tostring(a) + local as1 = as:sub(1, 1) + _38_ = not (("_" == as1) or ("?" == as1) or ("&" == as) or ("..." == as) or ("&as" == as)) + end + if _38_ then + return table.insert(args, check_position, setmetatable({filename="src/fennel/macros.fnl", line=339, bytestart=13009, sym('when', nil, {quoted=true, filename="src/fennel/macros.fnl", line=339}), setmetatable({filename="src/fennel/macros.fnl", line=339, bytestart=13015, sym('=', nil, {quoted=true, filename="src/fennel/macros.fnl", line=339}), sym('nil', nil, {quoted=true, filename="src/fennel/macros.fnl", line=339}), a}, getmetatable(list())), setmetatable({filename="src/fennel/macros.fnl", line=340, bytestart=13053, sym('_G.error', nil, {quoted=true, filename="src/fennel/macros.fnl", line=340}), ("Missing argument %s on %s:%s"):format(tostring(a), (a.filename or "unknown"), (a.line or "?")), 2}, getmetatable(list()))}, getmetatable(list()))) + end + end + end + utils['fennel-module'].metadata:setall(check_21, "fnl/arglist", {"a"}) + assert(("table" == type(arglist)), "expected arg list") + for _0, a in ipairs(arglist) do + check_21(a) + end + if empty_body_3f then + table.insert(args, sym("nil")) + end + return setmetatable({filename="src/fennel/macros.fnl", line=348, bytestart=13453, sym('fn', nil, {quoted=true, filename="src/fennel/macros.fnl", line=348}), unpack(args)}, getmetatable(list())) + end + utils['fennel-module'].metadata:setall(lambda_2a, "fnl/arglist", {"..."}, "fnl/docstring", "Function literal with nil-checked arguments.\nLike `fn`, but will throw an exception if a declared argument is passed in as\nnil, unless that argument's name begins with a question mark.") + local function macro_2a(name, ...) + assert(_G["sym?"](name), "expected symbol for macro name") + local args = {...} + return setmetatable({filename="src/fennel/macros.fnl", line=354, bytestart=13605, sym('macros', nil, {quoted=true, filename="src/fennel/macros.fnl", line=354}), setmetatable({[tostring(name)]=setmetatable({filename="src/fennel/macros.fnl", line=354, bytestart=13631, sym('fn', nil, {quoted=true, filename="src/fennel/macros.fnl", line=354}), unpack(args)}, getmetatable(list()))}, {filename="src/fennel/macros.fnl", line=354})}, getmetatable(list())) + end + utils['fennel-module'].metadata:setall(macro_2a, "fnl/arglist", {"name", "..."}, "fnl/docstring", "Define a single macro.") + local function macrodebug_2a(form, return_3f) + local handle = nil + if return_3f then + handle = sym('do', nil, {quoted=true, filename="src/fennel/macros.fnl", line=359}) + else + handle = sym('print', nil, {quoted=true, filename="src/fennel/macros.fnl", line=359}) + end + return setmetatable({filename="src/fennel/macros.fnl", line=362, bytestart=14027, handle, view(macroexpand(form), {["detect-cycles?"] = false})}, getmetatable(list())) + end + utils['fennel-module'].metadata:setall(macrodebug_2a, "fnl/arglist", {"form", "return?"}, "fnl/docstring", "Print the resulting form after performing macroexpansion.\nWith a second argument, returns expanded form as a string instead of printing.") + local function import_macros_2a(binding1, module_name1, ...) + assert((binding1 and module_name1 and (0 == (select("#", ...) % 2))), "expected even number of binding/modulename pairs") + for i = 1, select("#", binding1, module_name1, ...), 2 do + local binding, modname = select(i, binding1, module_name1, ...) + local scope = _G["get-scope"]() + local expr = setmetatable({filename="src/fennel/macros.fnl", line=381, bytestart=15181, sym('import-macros', nil, {quoted=true, filename="src/fennel/macros.fnl", line=381}), modname}, getmetatable(list())) + local filename = nil + if _G["list?"](modname) then + filename = modname[1].filename + else + filename = "unknown" + end + local _ = nil + expr.filename = filename + _ = nil + local macros_2a = _SPECIALS["require-macros"](expr, scope, {}, binding) + if _G["sym?"](binding) then + scope.macros[binding[1]] = macros_2a + elseif _G["table?"](binding) then + for macro_name, _43_0 in pairs(binding) do + local _44_ = _43_0 + local import_key = _44_[1] + assert(("function" == type(macros_2a[macro_name])), ("macro " .. macro_name .. " not found in module " .. tostring(modname))) + scope.macros[import_key] = macros_2a[macro_name] + end + end + end + return nil + end + utils['fennel-module'].metadata:setall(import_macros_2a, "fnl/arglist", {"binding1", "module-name1", "..."}, "fnl/docstring", "Bind a table of macros from each macro module according to a binding form.\nEach binding form can be either a symbol or a k/v destructuring table.\nExample:\n (import-macros mymacros :my-macros ; bind to symbol\n {:macro1 alias : macro2} :proj.macros) ; import by name") + local function assert_repl_2a(condition, ...) + do local _ = {["fnl/arglist"] = {condition, _G["?message"], ...}} end + local function add_locals(_46_0, locals) + local _47_ = _46_0 + local parent = _47_["parent"] + local symmeta = _47_["symmeta"] + for name in pairs(symmeta) do + locals[name] = sym(name) + end + if parent then + return add_locals(parent, locals) + else + return locals + end + end + utils['fennel-module'].metadata:setall(add_locals, "fnl/arglist", {"#", "locals"}) + return setmetatable({filename="src/fennel/macros.fnl", line=406, bytestart=16400, sym('let', nil, {quoted=true, filename="src/fennel/macros.fnl", line=406}), setmetatable({sym('unpack_49_', nil, {filename="src/fennel/macros.fnl", line=406}), setmetatable({filename="src/fennel/macros.fnl", line=406, bytestart=16414, sym('or', nil, {quoted=true, filename="src/fennel/macros.fnl", line=406}), sym('table.unpack', nil, {quoted=true, filename="src/fennel/macros.fnl", line=406}), sym('_G.unpack', nil, {quoted=true, filename="src/fennel/macros.fnl", line=406})}, getmetatable(list())), sym('pack_51_', nil, {filename="src/fennel/macros.fnl", line=407}), setmetatable({filename="src/fennel/macros.fnl", line=407, bytestart=16457, sym('or', nil, {quoted=true, filename="src/fennel/macros.fnl", line=407}), sym('table.pack', nil, {quoted=true, filename="src/fennel/macros.fnl", line=407}), setmetatable({filename=nil, line=nil, bytestart=nil, sym('hashfn', nil, {quoted=true, filename=nil, line=nil}), setmetatable({filename="src/fennel/macros.fnl", line=407, bytestart=16473, sym('doto', nil, {quoted=true, filename="src/fennel/macros.fnl", line=407}), setmetatable({sym('$...', nil, {quoted=true, filename="src/fennel/macros.fnl", line=407})}, {filename="src/fennel/macros.fnl", line=407}), setmetatable({filename="src/fennel/macros.fnl", line=407, bytestart=16486, sym('tset', nil, {quoted=true, filename="src/fennel/macros.fnl", line=407}), "n", setmetatable({filename="src/fennel/macros.fnl", line=407, bytestart=16495, sym('select', nil, {quoted=true, filename="src/fennel/macros.fnl", line=407}), "#", sym('$...', nil, {quoted=true, filename="src/fennel/macros.fnl", line=407})}, getmetatable(list()))}, getmetatable(list()))}, getmetatable(list()))}, getmetatable(list()))}, getmetatable(list())), sym('vals_50_', nil, {filename="src/fennel/macros.fnl", line=410}), setmetatable({filename="src/fennel/macros.fnl", line=410, bytestart=16668, sym('pack_51_', nil, {filename="src/fennel/macros.fnl", line=410}), condition, ...}, getmetatable(list())), sym('condition_52_', nil, {filename="src/fennel/macros.fnl", line=411}), setmetatable({filename="src/fennel/macros.fnl", line=411, bytestart=16712, sym('.', nil, {quoted=true, filename="src/fennel/macros.fnl", line=411}), sym('vals_50_', nil, {filename="src/fennel/macros.fnl", line=411}), 1}, getmetatable(list())), sym('message_53_', nil, {filename="src/fennel/macros.fnl", line=412}), setmetatable({filename="src/fennel/macros.fnl", line=412, bytestart=16742, sym('or', nil, {quoted=true, filename="src/fennel/macros.fnl", line=412}), setmetatable({filename="src/fennel/macros.fnl", line=412, bytestart=16746, sym('.', nil, {quoted=true, filename="src/fennel/macros.fnl", line=412}), sym('vals_50_', nil, {filename="src/fennel/macros.fnl", line=412}), 2}, getmetatable(list())), "assertion failed, entering repl."}, getmetatable(list()))}, {filename="src/fennel/macros.fnl", line=406}), setmetatable({filename="src/fennel/macros.fnl", line=413, bytestart=16800, sym('if', nil, {quoted=true, filename="src/fennel/macros.fnl", line=413}), setmetatable({filename="src/fennel/macros.fnl", line=413, bytestart=16804, sym('not', nil, {quoted=true, filename="src/fennel/macros.fnl", line=413}), sym('condition_52_', nil, {filename="src/fennel/macros.fnl", line=413})}, getmetatable(list())), setmetatable({filename="src/fennel/macros.fnl", line=414, bytestart=16830, sym('let', nil, {quoted=true, filename="src/fennel/macros.fnl", line=414}), setmetatable({sym('opts_54_', nil, {filename="src/fennel/macros.fnl", line=414}), setmetatable({["assert-repl?"]=true}, {filename="src/fennel/macros.fnl", line=414}), sym('fennel_55_', nil, {filename="src/fennel/macros.fnl", line=415}), setmetatable({filename="src/fennel/macros.fnl", line=415, bytestart=16886, sym('require', nil, {quoted=true, filename="src/fennel/macros.fnl", line=415}), _G["fennel-module-name"]()}, getmetatable(list())), sym('locals_56_', nil, {filename="src/fennel/macros.fnl", line=416}), add_locals(_G["get-scope"](), {})}, {filename="src/fennel/macros.fnl", line=414}), setmetatable({filename="src/fennel/macros.fnl", line=417, bytestart=16982, sym('set', nil, {quoted=true, filename="src/fennel/macros.fnl", line=417}), sym('opts_54_.message', nil, {filename="src/fennel/macros.fnl", line=417}), setmetatable({filename="src/fennel/macros.fnl", line=417, bytestart=17001, sym('fennel_55_.traceback', nil, {filename="src/fennel/macros.fnl", line=417}), sym('message_53_', nil, {filename="src/fennel/macros.fnl", line=417})}, getmetatable(list()))}, getmetatable(list())), setmetatable({filename="src/fennel/macros.fnl", line=418, bytestart=17042, sym('each', nil, {quoted=true, filename="src/fennel/macros.fnl", line=418}), setmetatable({sym('k_57_', nil, {filename="src/fennel/macros.fnl", line=418}), sym('v_58_', nil, {filename="src/fennel/macros.fnl", line=418}), setmetatable({filename="src/fennel/macros.fnl", line=418, bytestart=17055, sym('pairs', nil, {quoted=true, filename="src/fennel/macros.fnl", line=418}), sym('_G', nil, {quoted=true, filename="src/fennel/macros.fnl", line=418})}, getmetatable(list()))}, {filename="src/fennel/macros.fnl", line=418}), setmetatable({filename="src/fennel/macros.fnl", line=419, bytestart=17080, sym('when', nil, {quoted=true, filename="src/fennel/macros.fnl", line=419}), setmetatable({filename="src/fennel/macros.fnl", line=419, bytestart=17086, sym('=', nil, {quoted=true, filename="src/fennel/macros.fnl", line=419}), sym('nil', nil, {quoted=true, filename="src/fennel/macros.fnl", line=419}), setmetatable({filename="src/fennel/macros.fnl", line=419, bytestart=17093, sym('.', nil, {quoted=true, filename="src/fennel/macros.fnl", line=419}), sym('locals_56_', nil, {filename="src/fennel/macros.fnl", line=419}), sym('k_57_', nil, {filename="src/fennel/macros.fnl", line=419})}, getmetatable(list()))}, getmetatable(list())), setmetatable({filename="src/fennel/macros.fnl", line=419, bytestart=17109, sym('tset', nil, {quoted=true, filename="src/fennel/macros.fnl", line=419}), sym('locals_56_', nil, {filename="src/fennel/macros.fnl", line=419}), sym('k_57_', nil, {filename="src/fennel/macros.fnl", line=419}), sym('v_58_', nil, {filename="src/fennel/macros.fnl", line=419})}, getmetatable(list()))}, getmetatable(list()))}, getmetatable(list())), setmetatable({filename="src/fennel/macros.fnl", line=420, bytestart=17143, sym('set', nil, {quoted=true, filename="src/fennel/macros.fnl", line=420}), sym('opts_54_.env', nil, {filename="src/fennel/macros.fnl", line=420}), sym('locals_56_', nil, {filename="src/fennel/macros.fnl", line=420})}, getmetatable(list())), setmetatable({filename="src/fennel/macros.fnl", line=421, bytestart=17178, sym('_G.assert', nil, {quoted=true, filename="src/fennel/macros.fnl", line=421}), setmetatable({filename="src/fennel/macros.fnl", line=421, bytestart=17189, sym('fennel_55_.repl', nil, {filename="src/fennel/macros.fnl", line=421}), sym('opts_54_', nil, {filename="src/fennel/macros.fnl", line=421})}, getmetatable(list()))}, getmetatable(list()))}, getmetatable(list())), setmetatable({filename="src/fennel/macros.fnl", line=422, bytestart=17221, sym('values', nil, {quoted=true, filename="src/fennel/macros.fnl", line=422}), setmetatable({filename="src/fennel/macros.fnl", line=422, bytestart=17229, sym('unpack_49_', nil, {filename="src/fennel/macros.fnl", line=422}), sym('vals_50_', nil, {filename="src/fennel/macros.fnl", line=422}), 1, sym('vals_50_.n', nil, {filename="src/fennel/macros.fnl", line=422})}, getmetatable(list()))}, getmetatable(list()))}, getmetatable(list()))}, getmetatable(list())) + end + utils['fennel-module'].metadata:setall(assert_repl_2a, "fnl/arglist", {"condition", "..."}, "fnl/docstring", "Enter into a debug REPL and print the message when condition is false/nil.\nWorks as a drop-in replacement for Lua's `assert`.\nREPL `,return` command returns values to assert in place to continue execution.") + return {["->"] = __3e_2a, ["->>"] = __3e_3e_2a, ["-?>"] = __3f_3e_2a, ["-?>>"] = __3f_3e_3e_2a, ["?."] = _3fdot, ["\206\187"] = lambda_2a, ["assert-repl"] = assert_repl_2a, ["import-macros"] = import_macros_2a, ["pick-args"] = pick_args_2a, ["with-open"] = with_open_2a, accumulate = accumulate_2a, collect = collect_2a, doto = doto_2a, faccumulate = faccumulate_2a, fcollect = fcollect_2a, icollect = icollect_2a, lambda = lambda_2a, macro = macro_2a, macrodebug = macrodebug_2a, partial = partial_2a, when = when_2a} + ]===], env) + load_macros([===[local utils = ... + local function with(opts, k) + local _1_0 = utils.copy(opts) + _1_0[k] = true + return _1_0 + end + utils['fennel-module'].metadata:setall(with, "fnl/arglist", {"opts", "k"}) + local function without(opts, k) + local _2_0 = utils.copy(opts) + _2_0[k] = nil + return _2_0 + end + utils['fennel-module'].metadata:setall(without, "fnl/arglist", {"opts", "k"}) + local function case_values(vals, pattern, pins, case_pattern, opts) + local condition = setmetatable({filename="src/fennel/match.fnl", line=16, bytestart=372, sym('and', nil, {quoted=true, filename="src/fennel/match.fnl", line=16})}, getmetatable(list())) + local bindings = {} + for i, pat in ipairs(pattern) do + local subcondition, subbindings = case_pattern({vals[i]}, pat, pins, without(opts, "multival?")) + table.insert(condition, subcondition) + local tbl_17_ = bindings + local i_18_ = #tbl_17_ + for _, b in ipairs(subbindings) do + local val_19_ = b + if (nil ~= val_19_) then + i_18_ = (i_18_ + 1) + tbl_17_[i_18_] = val_19_ + end + end + end + return condition, bindings + end + utils['fennel-module'].metadata:setall(case_values, "fnl/arglist", {"vals", "pattern", "pins", "case-pattern", "opts"}) + local function case_table(val, pattern, pins, case_pattern, opts, _3ftop) + local condition = nil + if ("table" == _3ftop) then + condition = setmetatable({filename="src/fennel/match.fnl", line=26, bytestart=833, sym('and', nil, {quoted=true, filename="src/fennel/match.fnl", line=26})}, getmetatable(list())) + else + condition = setmetatable({filename="src/fennel/match.fnl", line=26, bytestart=840, sym('and', nil, {quoted=true, filename="src/fennel/match.fnl", line=26}), setmetatable({filename="src/fennel/match.fnl", line=26, bytestart=845, sym('=', nil, {quoted=true, filename="src/fennel/match.fnl", line=26}), setmetatable({filename="src/fennel/match.fnl", line=26, bytestart=848, sym('_G.type', nil, {quoted=true, filename="src/fennel/match.fnl", line=26}), val}, getmetatable(list())), "table"}, getmetatable(list()))}, getmetatable(list())) + end + local bindings = {} + for k, pat in pairs(pattern) do + if _G["sym?"](pat, "&") then + local rest_pat = pattern[(k + 1)] + local rest_val = setmetatable({filename="src/fennel/match.fnl", line=31, bytestart=1023, sym('select', nil, {quoted=true, filename="src/fennel/match.fnl", line=31}), k, setmetatable({filename="src/fennel/match.fnl", line=31, bytestart=1034, setmetatable({filename="src/fennel/match.fnl", line=31, bytestart=1035, sym('or', nil, {quoted=true, filename="src/fennel/match.fnl", line=31}), sym('table.unpack', nil, {quoted=true, filename="src/fennel/match.fnl", line=31}), sym('_G.unpack', nil, {quoted=true, filename="src/fennel/match.fnl", line=31})}, getmetatable(list())), val}, getmetatable(list()))}, getmetatable(list())) + local subcondition = case_table(setmetatable({filename="src/fennel/match.fnl", line=32, bytestart=1112, sym('pick-values', nil, {quoted=true, filename="src/fennel/match.fnl", line=32}), 1, rest_val}, getmetatable(list())), rest_pat, pins, case_pattern, without(opts, "multival?")) + if not _G["sym?"](rest_pat) then + table.insert(condition, subcondition) + end + assert((nil == pattern[(k + 2)]), "expected & rest argument before last parameter") + table.insert(bindings, rest_pat) + table.insert(bindings, {rest_val}) + elseif _G["sym?"](k, "&as") then + table.insert(bindings, pat) + table.insert(bindings, val) + elseif (("number" == type(k)) and _G["sym?"](pat, "&as")) then + assert((nil == pattern[(k + 2)]), "expected &as argument before last parameter") + table.insert(bindings, pattern[(k + 1)]) + table.insert(bindings, val) + elseif (("number" ~= type(k)) or (not _G["sym?"](pattern[(k - 1)], "&as") and not _G["sym?"](pattern[(k - 1)], "&"))) then + local subval = setmetatable({filename="src/fennel/match.fnl", line=54, bytestart=2238, sym('.', nil, {quoted=true, filename="src/fennel/match.fnl", line=54}), val, k}, getmetatable(list())) + local subcondition, subbindings = case_pattern({subval}, pat, pins, without(opts, "multival?")) + table.insert(condition, subcondition) + local tbl_17_ = bindings + local i_18_ = #tbl_17_ + for _, b in ipairs(subbindings) do + local val_19_ = b + if (nil ~= val_19_) then + i_18_ = (i_18_ + 1) + tbl_17_[i_18_] = val_19_ + end + end + end + end + return condition, bindings + end + utils['fennel-module'].metadata:setall(case_table, "fnl/arglist", {"val", "pattern", "pins", "case-pattern", "opts", "?top"}) + local function case_guard(vals, condition, guards, pins, case_pattern, opts) + if guards[1] then + local pcondition, bindings = case_pattern(vals, condition, pins, opts) + local condition0 = setmetatable({filename="src/fennel/match.fnl", line=65, bytestart=2798, sym('and', nil, {quoted=true, filename="src/fennel/match.fnl", line=65}), unpack(guards)}, getmetatable(list())) + return setmetatable({filename="src/fennel/match.fnl", line=66, bytestart=2838, sym('and', nil, {quoted=true, filename="src/fennel/match.fnl", line=66}), pcondition, setmetatable({filename="src/fennel/match.fnl", line=67, bytestart=2876, sym('let', nil, {quoted=true, filename="src/fennel/match.fnl", line=67}), bindings, condition0}, getmetatable(list()))}, getmetatable(list())), bindings + else + return case_pattern(vals, condition, pins, opts) + end + end + utils['fennel-module'].metadata:setall(case_guard, "fnl/arglist", {"vals", "condition", "guards", "pins", "case-pattern", "opts"}) + local function bound_symbols_in_pattern(pattern) + if _G["list?"](pattern) then + if (_G["sym?"](pattern[1], "where") or _G["sym?"](pattern[1], "=")) then + return bound_symbols_in_pattern(pattern[2]) + elseif _G["sym?"](pattern[2], "?") then + return bound_symbols_in_pattern(pattern[1]) + else + local result = {} + for _, child_pattern in ipairs(pattern) do + local tbl_14_ = result + for name, symbol in pairs(bound_symbols_in_pattern(child_pattern)) do + local k_15_, v_16_ = name, symbol + if ((k_15_ ~= nil) and (v_16_ ~= nil)) then + tbl_14_[k_15_] = v_16_ + end + end + end + return result + end + elseif _G["sym?"](pattern) then + local symname = tostring(pattern) + if ((symname ~= "or") and (symname ~= "nil") and not symname:find("^&")) then + return {[symname] = pattern} + else + return {} + end + elseif (type(pattern) == "table") then + local result = {} + for key_pattern, value_pattern in pairs(pattern) do + do + local tbl_14_ = result + for name, symbol in pairs(bound_symbols_in_pattern(key_pattern)) do + local k_15_, v_16_ = name, symbol + if ((k_15_ ~= nil) and (v_16_ ~= nil)) then + tbl_14_[k_15_] = v_16_ + end + end + end + local tbl_14_ = result + for name, symbol in pairs(bound_symbols_in_pattern(value_pattern)) do + local k_15_, v_16_ = name, symbol + if ((k_15_ ~= nil) and (v_16_ ~= nil)) then + tbl_14_[k_15_] = v_16_ + end + end + end + return result + else + return {} + end + end + utils['fennel-module'].metadata:setall(bound_symbols_in_pattern, "fnl/arglist", {"pattern"}, "fnl/docstring", "gives the set of symbols pattern will bind") + local function bound_symbols_in_every_pattern(pattern_list, infer_pin_3f) + local _3fsymbols = nil + do + local _3fsymbols0 = nil + for _, pattern in ipairs(pattern_list) do + local in_pattern = bound_symbols_in_pattern(pattern) + if _3fsymbols0 then + for name in pairs(_3fsymbols0) do + if not in_pattern[name] then + _3fsymbols0[name] = nil + end + end + _3fsymbols0 = _3fsymbols0 + else + _3fsymbols0 = in_pattern + end + end + _3fsymbols = _3fsymbols0 + end + local tbl_17_ = {} + local i_18_ = #tbl_17_ + for _, symbol in pairs((_3fsymbols or {})) do + local val_19_ = nil + if not (infer_pin_3f and _G["in-scope?"](symbol)) then + val_19_ = symbol + else + val_19_ = nil + end + if (nil ~= val_19_) then + i_18_ = (i_18_ + 1) + tbl_17_[i_18_] = val_19_ + end + end + return tbl_17_ + end + utils['fennel-module'].metadata:setall(bound_symbols_in_every_pattern, "fnl/arglist", {"pattern-list", "infer-pin?"}, "fnl/docstring", "gives a list of symbols that are bound by every pattern in the list") + local function case_or(vals, pattern, guards, pins, case_pattern, opts) + local pattern0 = {unpack(pattern, 2)} + local bindings = bound_symbols_in_every_pattern(pattern0, opts["infer-pin?"]) + if (nil == bindings[1]) then + local condition = nil + do + local tbl_17_ = setmetatable({filename="src/fennel/match.fnl", line=122, bytestart=5212, sym('or', nil, {quoted=true, filename="src/fennel/match.fnl", line=122})}, getmetatable(list())) + local i_18_ = #tbl_17_ + for _, subpattern in ipairs(pattern0) do + local val_19_ = case_pattern(vals, subpattern, pins, opts) + if (nil ~= val_19_) then + i_18_ = (i_18_ + 1) + tbl_17_[i_18_] = val_19_ + end + end + condition = tbl_17_ + end + local _20_ + if guards[1] then + _20_ = setmetatable({filename="src/fennel/match.fnl", line=125, bytestart=5345, sym('and', nil, {quoted=true, filename="src/fennel/match.fnl", line=125}), condition, unpack(guards)}, getmetatable(list())) + else + _20_ = condition + end + return _20_, {} + else + local matched_3f = gensym("matched?") + local bindings_mangled = nil + do + local tbl_17_ = {} + local i_18_ = #tbl_17_ + for _, binding in ipairs(bindings) do + local val_19_ = gensym(tostring(binding)) + if (nil ~= val_19_) then + i_18_ = (i_18_ + 1) + tbl_17_[i_18_] = val_19_ + end + end + bindings_mangled = tbl_17_ + end + local pre_bindings = setmetatable({filename="src/fennel/match.fnl", line=132, bytestart=5720, sym('if', nil, {quoted=true, filename="src/fennel/match.fnl", line=132})}, getmetatable(list())) + for _, subpattern in ipairs(pattern0) do + local subcondition, subbindings = case_guard(vals, subpattern, guards, {}, case_pattern, opts) + table.insert(pre_bindings, subcondition) + table.insert(pre_bindings, setmetatable({filename="src/fennel/match.fnl", line=136, bytestart=5966, sym('let', nil, {quoted=true, filename="src/fennel/match.fnl", line=136}), subbindings, setmetatable({filename="src/fennel/match.fnl", line=137, bytestart=6026, sym('values', nil, {quoted=true, filename="src/fennel/match.fnl", line=137}), true, unpack(bindings)}, getmetatable(list()))}, getmetatable(list()))) + end + return matched_3f, {setmetatable({filename="src/fennel/match.fnl", line=139, bytestart=6106, unpack(bindings)}, getmetatable(list())), setmetatable({filename="src/fennel/match.fnl", line=139, bytestart=6128, sym('values', nil, {quoted=true, filename="src/fennel/match.fnl", line=139}), unpack(bindings_mangled)}, getmetatable(list()))}, {setmetatable({filename="src/fennel/match.fnl", line=140, bytestart=6183, matched_3f, unpack(bindings_mangled)}, getmetatable(list())), pre_bindings} + end + end + utils['fennel-module'].metadata:setall(case_or, "fnl/arglist", {"vals", "pattern", "guards", "pins", "case-pattern", "opts"}) + local function case_pattern(vals, pattern, pins, opts, _3ftop) + local _24_ = vals + local val = _24_[1] + if (_G["sym?"](pattern) and (_G["sym?"](pattern, "nil") or (opts["infer-pin?"] and _G["in-scope?"](pattern) and not _G["sym?"](pattern, "_")) or (opts["infer-pin?"] and _G["multi-sym?"](pattern) and _G["in-scope?"](_G["multi-sym?"](pattern)[1])))) then + return setmetatable({filename="src/fennel/match.fnl", line=174, bytestart=8070, sym('=', nil, {quoted=true, filename="src/fennel/match.fnl", line=174}), val, pattern}, getmetatable(list())), {} + elseif (_G["sym?"](pattern) and pins[tostring(pattern)]) then + return setmetatable({filename="src/fennel/match.fnl", line=177, bytestart=8208, sym('=', nil, {quoted=true, filename="src/fennel/match.fnl", line=177}), pins[tostring(pattern)], val}, getmetatable(list())), {} + elseif _G["sym?"](pattern) then + local wildcard_3f = tostring(pattern):find("^_") + if not wildcard_3f then + pins[tostring(pattern)] = val + end + local _26_ + if (wildcard_3f or string.find(tostring(pattern), "^?")) then + _26_ = true + else + _26_ = setmetatable({filename="src/fennel/match.fnl", line=183, bytestart=8531, sym('not=', nil, {quoted=true, filename="src/fennel/match.fnl", line=183}), sym("nil"), val}, getmetatable(list())) + end + return _26_, {pattern, val} + elseif (_G["list?"](pattern) and _G["sym?"](pattern[1], "=") and _G["sym?"](pattern[2])) then + local bind = pattern[2] + _G["assert-compile"]((2 == #pattern), "(=) should take only one argument", pattern) + _G["assert-compile"](not opts["infer-pin?"], "(=) cannot be used inside of match", pattern) + _G["assert-compile"](opts["in-where?"], "(=) must be used in (where) patterns", pattern) + _G["assert-compile"]((_G["sym?"](bind) and not _G["sym?"](bind, "nil")), "= has to bind to a symbol", bind) + return setmetatable({filename="src/fennel/match.fnl", line=194, bytestart=9165, sym('=', nil, {quoted=true, filename="src/fennel/match.fnl", line=194}), val, bind}, getmetatable(list())), {} + elseif (_G["list?"](pattern) and _G["sym?"](pattern[1], "where") and _G["list?"](pattern[2]) and _G["sym?"](pattern[2][1], "or")) then + _G["assert-compile"](_3ftop, "can't nest (where) pattern", pattern) + return case_or(vals, pattern[2], {unpack(pattern, 3)}, pins, case_pattern, with(opts, "in-where?")) + elseif (_G["list?"](pattern) and _G["sym?"](pattern[1], "where")) then + _G["assert-compile"](_3ftop, "can't nest (where) pattern", pattern) + return case_guard(vals, pattern[2], {unpack(pattern, 3)}, pins, case_pattern, with(opts, "in-where?")) + elseif (_G["list?"](pattern) and _G["sym?"](pattern[1], "or")) then + _G["assert-compile"](_3ftop, "can't nest (or) pattern", pattern) + _G["assert-compile"](false, "(or) must be used in (where) patterns", pattern) + return case_or(vals, pattern, {}, pins, case_pattern, opts) + elseif (_G["list?"](pattern) and _G["sym?"](pattern[2], "?")) then + _G["assert-compile"](opts["legacy-guard-allowed?"], "legacy guard clause not supported in case", pattern) + return case_guard(vals, pattern[1], {unpack(pattern, 3)}, pins, case_pattern, opts) + elseif _G["list?"](pattern) then + _G["assert-compile"](opts["multival?"], "can't nest multi-value destructuring", pattern) + return case_values(vals, pattern, pins, case_pattern, opts) + elseif (type(pattern) == "table") then + return case_table(val, pattern, pins, case_pattern, opts, _3ftop) + else + return setmetatable({filename="src/fennel/match.fnl", line=226, bytestart=10854, sym('=', nil, {quoted=true, filename="src/fennel/match.fnl", line=226}), val, pattern}, getmetatable(list())), {} + end + end + utils['fennel-module'].metadata:setall(case_pattern, "fnl/arglist", {"vals", "pattern", "pins", "opts", "?top"}, "fnl/docstring", "Take the AST of values and a single pattern and returns a condition\nto determine if it matches as well as a list of bindings to\nintroduce for the duration of the body if it does match.") + local function add_pre_bindings(out, pre_bindings) + if pre_bindings then + local tail = setmetatable({filename="src/fennel/match.fnl", line=235, bytestart=11252, sym('if', nil, {quoted=true, filename="src/fennel/match.fnl", line=235})}, getmetatable(list())) + table.insert(out, true) + table.insert(out, setmetatable({filename="src/fennel/match.fnl", line=237, bytestart=11317, sym('let', nil, {quoted=true, filename="src/fennel/match.fnl", line=237}), pre_bindings, tail}, getmetatable(list()))) + return tail + else + return out + end + end + utils['fennel-module'].metadata:setall(add_pre_bindings, "fnl/arglist", {"out", "pre-bindings"}, "fnl/docstring", "Decide when to switch from the current `if` AST to a new one") + local function case_condition(vals, clauses, match_3f, top_table_3f) + local root = setmetatable({filename="src/fennel/match.fnl", line=246, bytestart=11658, sym('if', nil, {quoted=true, filename="src/fennel/match.fnl", line=246})}, getmetatable(list())) + do + local out = root + for i = 1, #clauses, 2 do + local pattern = clauses[i] + local body = clauses[(i + 1)] + local condition, bindings, pre_bindings = nil, nil, nil + local function _30_() + if top_table_3f then + return "table" + else + return true + end + end + condition, bindings, pre_bindings = case_pattern(vals, pattern, {}, {["infer-pin?"] = match_3f, ["legacy-guard-allowed?"] = match_3f, ["multival?"] = true}, _30_()) + local out0 = add_pre_bindings(out, pre_bindings) + table.insert(out0, condition) + table.insert(out0, setmetatable({filename="src/fennel/match.fnl", line=259, bytestart=12387, sym('let', nil, {quoted=true, filename="src/fennel/match.fnl", line=259}), bindings, body}, getmetatable(list()))) + out = out0 + end + end + return root + end + utils['fennel-module'].metadata:setall(case_condition, "fnl/arglist", {"vals", "clauses", "match?", "top-table?"}, "fnl/docstring", "Construct the actual `if` AST for the given match values and clauses.") + local function count_case_multival(pattern) + if (_G["list?"](pattern) and _G["sym?"](pattern[2], "?")) then + return count_case_multival(pattern[1]) + elseif (_G["list?"](pattern) and _G["sym?"](pattern[1], "where")) then + return count_case_multival(pattern[2]) + elseif (_G["list?"](pattern) and _G["sym?"](pattern[1], "or")) then + local longest = 0 + for _, child_pattern in ipairs(pattern) do + longest = math.max(longest, count_case_multival(child_pattern)) + end + return longest + elseif _G["list?"](pattern) then + return #pattern + else + return 1 + end + end + utils['fennel-module'].metadata:setall(count_case_multival, "fnl/arglist", {"pattern"}, "fnl/docstring", "Identify the amount of multival values that a pattern requires.") + local function case_count_syms(clauses) + local patterns = nil + do + local tbl_17_ = {} + local i_18_ = #tbl_17_ + for i = 1, #clauses, 2 do + local val_19_ = clauses[i] + if (nil ~= val_19_) then + i_18_ = (i_18_ + 1) + tbl_17_[i_18_] = val_19_ + end + end + patterns = tbl_17_ + end + local longest = 0 + for _, pattern in ipairs(patterns) do + longest = math.max(longest, count_case_multival(pattern)) + end + return longest + end + utils['fennel-module'].metadata:setall(case_count_syms, "fnl/arglist", {"clauses"}, "fnl/docstring", "Find the length of the largest multi-valued clause") + local function maybe_optimize_table(val, clauses) + local _33_ + do + local all = _G["sequence?"](val) + for i = 1, #clauses, 2 do + if not all then break end + local function _34_() + local all2 = next(clauses[i]) + for _, d in ipairs(clauses[i]) do + if not all2 then break end + all2 = (all2 and (not _G["sym?"](d) or not tostring(d):find("^&"))) + end + return all2 + end + all = (_G["sequence?"](clauses[i]) and _34_()) + end + _33_ = all + end + if _33_ then + local function _35_() + local tbl_17_ = {} + local i_18_ = #tbl_17_ + for i = 1, #clauses do + local val_19_ = nil + if (1 == (i % 2)) then + val_19_ = list(unpack(clauses[i])) + else + val_19_ = clauses[i] + end + if (nil ~= val_19_) then + i_18_ = (i_18_ + 1) + tbl_17_[i_18_] = val_19_ + end + end + return tbl_17_ + end + return setmetatable({filename="src/fennel/match.fnl", line=291, bytestart=13670, sym('values', nil, {quoted=true, filename="src/fennel/match.fnl", line=291}), unpack(val)}, getmetatable(list())), _35_() + else + return val, clauses + end + end + utils['fennel-module'].metadata:setall(maybe_optimize_table, "fnl/arglist", {"val", "clauses"}) + local function case_impl(match_3f, init_val, ...) + assert((init_val ~= nil), "missing subject") + assert((0 == math.fmod(select("#", ...), 2)), "expected even number of pattern/body pairs") + assert((0 ~= select("#", ...)), "expected at least one pattern/body pair") + local val, clauses = maybe_optimize_table(init_val, {...}) + local vals_count = case_count_syms(clauses) + if ((vals_count == 1) and not _G["varg?"](val) and utils["idempotent-expr?"](val)) then + return case_condition(list(val), clauses, match_3f, _G["table?"](init_val)) + else + local vals = nil + do + local tbl_17_ = list() + local i_18_ = #tbl_17_ + for _ = 1, vals_count do + local val_19_ = gensym("case") + if (nil ~= val_19_) then + i_18_ = (i_18_ + 1) + tbl_17_[i_18_] = val_19_ + end + end + vals = tbl_17_ + end + return list(sym('let', nil, {quoted=true, filename="src/fennel/match.fnl", line=312}), {vals, val}, case_condition(vals, clauses, match_3f, _G["table?"](init_val))) + end + end + utils['fennel-module'].metadata:setall(case_impl, "fnl/arglist", {"match?", "init-val", "..."}, "fnl/docstring", "The shared implementation of case and match.") + local function case_2a(val, ...) + return case_impl(false, val, ...) + end + utils['fennel-module'].metadata:setall(case_2a, "fnl/arglist", {"val", "..."}, "fnl/docstring", "Perform pattern matching on val. See reference for details.\n\nSyntax:\n\n(case data-expression\n pattern body\n (where pattern guards*) body\n (where (or pattern patterns*) guards*) body)") + local function match_2a(val, ...) + return case_impl(true, val, ...) + end + utils['fennel-module'].metadata:setall(match_2a, "fnl/arglist", {"val", "..."}, "fnl/docstring", "Perform pattern matching on val, automatically pinning variables in scope.\n\nSyntax:\n\n(match expression\n pattern body\n (where pattern guards*) body\n (where (or pattern patterns*) guards*) body)") + local function case_try_step(how, expr, _else, pattern, body, ...) + if ((nil == pattern) and (pattern == body)) then + return expr + else + return setmetatable({filename="src/fennel/match.fnl", line=343, bytestart=15577, setmetatable({filename="src/fennel/match.fnl", line=343, bytestart=15578, sym('fn', nil, {quoted=true, filename="src/fennel/match.fnl", line=343}), setmetatable({_VARARG}, {filename="src/fennel/match.fnl", line=343}), setmetatable({filename="src/fennel/match.fnl", line=344, bytestart=15598, how, _VARARG, pattern, case_try_step(how, body, _else, ...), unpack(_else)}, getmetatable(list()))}, getmetatable(list())), expr}, getmetatable(list())) + end + end + utils['fennel-module'].metadata:setall(case_try_step, "fnl/arglist", {"how", "expr", "else", "pattern", "body", "..."}) + local function case_try_impl(how, expr, pattern, body, ...) + local clauses = {pattern, body, ...} + local last = clauses[#clauses] + local catch = nil + if (_G["list?"](last) and _G["sym?"](last[1], "catch")) then + local _42_ = table.remove(clauses) + local _ = _42_[1] + local e = {(table.unpack or unpack)(_42_, 2)} + catch = e + else + catch = {sym('__43_', nil, {filename="src/fennel/match.fnl", line=354}), _VARARG} + end + assert((0 == math.fmod(#clauses, 2)), "expected every pattern to have a body") + assert((0 == math.fmod(#catch, 2)), "expected every catch pattern to have a body") + return case_try_step(how, expr, catch, unpack(clauses)) + end + utils['fennel-module'].metadata:setall(case_try_impl, "fnl/arglist", {"how", "expr", "pattern", "body", "..."}) + local function case_try_2a(expr, pattern, body, ...) + return case_try_impl(sym('case', nil, {quoted=true, filename="src/fennel/match.fnl", line=372}), expr, pattern, body, ...) + end + utils['fennel-module'].metadata:setall(case_try_2a, "fnl/arglist", {"expr", "pattern", "body", "..."}, "fnl/docstring", "Perform chained pattern matching for a sequence of steps which might fail.\n\nThe values from the initial expression are matched against the first pattern.\nIf they match, the first body is evaluated and its values are matched against\nthe second pattern, etc.\n\nIf there is a (catch pat1 body1 pat2 body2 ...) form at the end, any mismatch\nfrom the steps will be tried against these patterns in sequence as a fallback\njust like a normal match. If there is no catch, the mismatched values will be\nreturned as the value of the entire expression.") + local function match_try_2a(expr, pattern, body, ...) + return case_try_impl(sym('match', nil, {quoted=true, filename="src/fennel/match.fnl", line=385}), expr, pattern, body, ...) + end + utils['fennel-module'].metadata:setall(match_try_2a, "fnl/arglist", {"expr", "pattern", "body", "..."}, "fnl/docstring", "Perform chained pattern matching for a sequence of steps which might fail.\n\nThe values from the initial expression are matched against the first pattern.\nIf they match, the first body is evaluated and its values are matched against\nthe second pattern, etc.\n\nIf there is a (catch pat1 body1 pat2 body2 ...) form at the end, any mismatch\nfrom the steps will be tried against these patterns in sequence as a fallback\njust like a normal match. If there is no catch, the mismatched values will be\nreturned as the value of the entire expression.") + return {["case-try"] = case_try_2a, ["match-try"] = match_try_2a, case = case_2a, match = match_2a} + ]===], env) +end +return mod diff --git a/lua/eca/nfnl/fs.lua b/lua/eca/nfnl/fs.lua new file mode 100644 index 0000000..8f160e0 --- /dev/null +++ b/lua/eca/nfnl/fs.lua @@ -0,0 +1,132 @@ +-- [nfnl] fnl/nfnl/fs.fnl +local _local_1_ = require("eca.nfnl.module") +local autoload = _local_1_.autoload +local define = _local_1_.define +local core = autoload("eca.nfnl.core") +local str = autoload("eca.nfnl.string") +local vim = _G.vim +local jit = _G.jit +local M = define("eca.nfnl.fs") +M.basename = function(path) + if path then + return vim.fn.fnamemodify(path, ":h") + else + return nil + end +end +M.filename = function(path) + if path then + return vim.fn.fnamemodify(path, ":t") + else + return nil + end +end +M["file-name-root"] = function(path) + if path then + return vim.fn.fnamemodify(path, ":r") + else + return nil + end +end +M["full-path"] = function(path) + if path then + return vim.fn.fnamemodify(path, ":p") + else + return nil + end +end +M.mkdirp = function(dir) + if dir then + return vim.fn.mkdir(dir, "p") + else + return nil + end +end +M["replace-extension"] = function(path, ext) + if path then + return (M["file-name-root"](path) .. ("." .. ext)) + else + return nil + end +end +M["read-first-line"] = function(path) + local f = io.open(path, "r") + if (f and not core["string?"](f)) then + local line = f:read("*line") + f:close() + return line + else + return nil + end +end +M["absolute-path"] = function(path) + return vim.fs.normalize(vim.fn.fnamemodify(path, ":p")) +end +M.absglob = function(dir, expr) + return vim.fn.globpath(dir, expr, true, true) +end +M.relglob = function(dir, expr) + local dir_len = (2 + string.len(dir)) + local function _9_(_241) + return string.sub(_241, dir_len) + end + return core.map(_9_, M.absglob(dir, expr)) +end +M["glob-dir-newer?"] = function(a_dir, b_dir, expr, b_dir_path_fn) + local newer_3f = false + for _, path in ipairs(M.relglob(a_dir, expr)) do + if (vim.fn.getftime((a_dir .. path)) > vim.fn.getftime((b_dir .. b_dir_path_fn(path)))) then + newer_3f = true + else + end + end + return newer_3f +end +M["path-sep"] = function() + local os = string.lower(jit.os) + if (("linux" == os) or ("osx" == os) or ("bsd" == os) or ((1 == vim.fn.exists("+shellshash")) and vim.o.shellslash)) then + return "/" + else + return "\\" + end +end +M.findfile = function(name, path) + local res = vim.fn.findfile(name, path) + if not core["empty?"](res) then + return M["full-path"](res) + else + return nil + end +end +M["split-path"] = function(path) + return str.split(path, M["path-sep"]()) +end +M["join-path"] = function(parts) + return str.join(M["path-sep"](), core.concat(parts)) +end +M["replace-dirs"] = function(path, from, to) + local function _13_(segment) + if (from == segment) then + return to + else + return segment + end + end + return M["join-path"](core.map(_13_, M["split-path"](path))) +end +M["fnl-path->lua-path"] = function(fnl_path) + return M["replace-dirs"](M["replace-extension"](fnl_path, "lua"), "fnl", "lua") +end +M["glob-matches?"] = function(dir, expr, path) + local regex = vim.regex(vim.fn.glob2regpat(M["join-path"]({dir, expr}))) + return regex:match_str(path) +end +local uv = (vim.uv or vim.loop) +M["exists?"] = function(path) + if path then + return ("table" == type(uv.fs_stat(path))) + else + return nil + end +end +return M diff --git a/lua/eca/nfnl/gc.lua b/lua/eca/nfnl/gc.lua new file mode 100644 index 0000000..7b34979 --- /dev/null +++ b/lua/eca/nfnl/gc.lua @@ -0,0 +1,28 @@ +-- [nfnl] fnl/nfnl/gc.fnl +local _local_1_ = require("eca.nfnl.module") +local autoload = _local_1_.autoload +local define = _local_1_.define +local core = autoload("eca.nfnl.core") +local fs = autoload("eca.nfnl.fs") +local header = autoload("eca.nfnl.header") +local M = define("eca.nfnl.gc") +M["find-orphan-lua-files"] = function(_2_) + local cfg = _2_.cfg + local root_dir = _2_["root-dir"] + local fnl_path__3elua_path = cfg({"fnl-path->lua-path"}) + local ignore_patterns = cfg({"orphan-detection", "ignore-patterns"}) + local function _3_(path) + local line = fs["read-first-line"](path) + local function _4_(pat) + return path:find(pat) + end + return (not core.some(_4_, ignore_patterns) and header["tagged?"](line) and not fs["exists?"](header["source-path"](line))) + end + local function _5_(fnl_pattern) + local lua_pattern = fnl_path__3elua_path(fnl_pattern) + return fs.relglob(root_dir, lua_pattern) + end + return core.filter(_3_, core.keys(core["->set"](core.mapcat(_5_, cfg({"source-file-patterns"}))))) +end +--[[ (local config (require "eca.nfnl.config")) (M.find-orphan-lua-files (config.find-and-load ".")) ]] +return M diff --git a/lua/eca/nfnl/header.lua b/lua/eca/nfnl/header.lua new file mode 100644 index 0000000..4ef6f40 --- /dev/null +++ b/lua/eca/nfnl/header.lua @@ -0,0 +1,29 @@ +-- [nfnl] fnl/nfnl/header.fnl +local _local_1_ = require("eca.nfnl.module") +local autoload = _local_1_.autoload +local define = _local_1_.define +local core = autoload("eca.nfnl.core") +local str = autoload("eca.nfnl.string") +local M = define("eca.nfnl.header") +local tag = "[nfnl]" +M["with-header"] = function(file, src) + return ("-- " .. tag .. " " .. file .. "\n" .. src) +end +M["tagged?"] = function(s) + if s then + return core["number?"](s:find(tag, 1, true)) + else + return nil + end +end +M["source-path"] = function(s) + if M["tagged?"](s) then + local function _3_(part) + return (str["ends-with?"](part, ".fnl") and part) + end + return core.some(_3_, str.split(s, "%s+")) + else + return nil + end +end +return M diff --git a/lua/eca/nfnl/init.lua b/lua/eca/nfnl/init.lua new file mode 100644 index 0000000..c0f6d91 --- /dev/null +++ b/lua/eca/nfnl/init.lua @@ -0,0 +1,21 @@ +-- [nfnl] fnl/nfnl/init.fnl +local _local_1_ = require("eca.nfnl.module") +local define = _local_1_.define +local autoload = _local_1_.autoload +local notify = autoload("eca.nfnl.notify") +local vim = _G.vim +local M = define("nfnl") +if vim then + notify.warn("require(\"nfnl\") is deprecated. nfnl now activates via ftplugin. You can remove require(\"nfnl\") from your config.") +else +end +M.setup = function(opts) + notify.warn("eca.nfnl.setup() is deprecated. Set vim.g.nfnl#compile_on_write directly instead.") + if opts then + vim.g["nfnl#compile_on_write"] = opts.compile_on_write + return nil + else + return nil + end +end +return M diff --git a/lua/eca/nfnl/module.lua b/lua/eca/nfnl/module.lua new file mode 100644 index 0000000..492761f --- /dev/null +++ b/lua/eca/nfnl/module.lua @@ -0,0 +1,38 @@ +-- [nfnl] fnl/nfnl/module.fnl +local module_key = "nfnl/autoload-module" +local enabled_key = "nfnl/autoload-enabled?" +local M = {} +M.autoload = function(name) + local res = {[enabled_key] = true, [module_key] = false} + local ensure + local function _1_() + if res[module_key] then + return res[module_key] + else + local m = require(name) + res[module_key] = m + return m + end + end + ensure = _1_ + local function _3_(_t, ...) + return ensure()(...) + end + local function _4_(_t, k) + return ensure()[k] + end + local function _5_(_t, k, v) + ensure()[k] = v + return nil + end + return setmetatable(res, {__call = _3_, __index = _4_, __newindex = _5_}) +end +M.define = function(mod_name, base) + local loaded = package.loaded[mod_name] + if (((type(loaded) == type(base)) or (nil == base)) and ((nil ~= loaded) and ("number" ~= type(loaded)))) then + return loaded + else + return (base or {}) + end +end +return M diff --git a/lua/eca/nfnl/notify.lua b/lua/eca/nfnl/notify.lua new file mode 100644 index 0000000..38a9082 --- /dev/null +++ b/lua/eca/nfnl/notify.lua @@ -0,0 +1,23 @@ +-- [nfnl] fnl/nfnl/notify.fnl +local _local_1_ = require("eca.nfnl.module") +local autoload = _local_1_.autoload +local core = autoload("eca.nfnl.core") +local function notify(level, ...) + return vim.api.nvim_notify(core.str(...), level, {}) +end +local function debug(...) + return notify(vim.log.levels.DEBUG, ...) +end +local function error(...) + return notify(vim.log.levels.ERROR, ...) +end +local function info(...) + return notify(vim.log.levels.INFO, ...) +end +local function trace(...) + return notify(vim.log.levels.TRACE, ...) +end +local function warn(...) + return notify(vim.log.levels.WARN, ...) +end +return {debug = debug, error = error, info = info, trace = trace, warn = warn} diff --git a/lua/eca/nfnl/nvim.lua b/lua/eca/nfnl/nvim.lua new file mode 100644 index 0000000..b8c451b --- /dev/null +++ b/lua/eca/nfnl/nvim.lua @@ -0,0 +1,8 @@ +-- [nfnl] fnl/nfnl/nvim.fnl +local _local_1_ = require("eca.nfnl.module") +local autoload = _local_1_.autoload +local str = autoload("eca.nfnl.string") +local function get_buf_content_as_string(buf) + return (str.join("\n", vim.api.nvim_buf_get_lines((buf or 0), 0, -1, false)) or "") +end +return {["get-buf-content-as-string"] = get_buf_content_as_string} diff --git a/lua/eca/nfnl/repl.lua b/lua/eca/nfnl/repl.lua new file mode 100644 index 0000000..5b41012 --- /dev/null +++ b/lua/eca/nfnl/repl.lua @@ -0,0 +1,65 @@ +-- [nfnl] fnl/nfnl/repl.fnl +local _local_1_ = require("eca.nfnl.module") +local autoload = _local_1_.autoload +local core = autoload("eca.nfnl.core") +local fennel = autoload("eca.nfnl.fennel") +local notify = autoload("eca.nfnl.notify") +local str = autoload("eca.nfnl.string") +local function new(opts) + local results_to_return = nil + local cfg + do + local t_2_ = opts + if (nil ~= t_2_) then + t_2_ = t_2_.cfg + else + end + cfg = t_2_ + end + local co + local function _4_() + local function _5_(results) + results_to_return = core.concat(results_to_return, results) + return nil + end + local function _6_(err_type, err, lua_source) + local _8_ + do + local t_7_ = opts + if (nil ~= t_7_) then + t_7_ = t_7_["on-error"] + else + end + _8_ = t_7_ + end + if _8_ then + return opts["on-error"](err_type, err, lua_source) + else + return notify.error(str.trim(str.join("\n\n", {("[" .. err_type .. "] " .. err), lua_source}))) + end + end + local function _11_() + if cfg then + return cfg({"compiler-options"}) + else + return nil + end + end + return fennel.repl(core["merge!"]({pp = core.identity, readChunk = coroutine.yield, env = core.merge(_G), onValues = _5_, onError = _6_}, _11_())) + end + co = coroutine.create(_4_) + coroutine.resume(co) + local function _12_(input) + if cfg then + fennel.path = cfg({"fennel-path"}) + fennel["macro-path"] = cfg({"fennel-macro-path"}) + else + end + coroutine.resume(co, input) + local prev_eval_values = results_to_return + results_to_return = nil + return prev_eval_values + end + return _12_ +end +return {new = new} diff --git a/lua/eca/nfnl/string.lua b/lua/eca/nfnl/string.lua new file mode 100644 index 0000000..93ebeef --- /dev/null +++ b/lua/eca/nfnl/string.lua @@ -0,0 +1,78 @@ +-- [nfnl] fnl/nfnl/string.fnl +local _local_1_ = require("eca.nfnl.module") +local autoload = _local_1_.autoload +local define = _local_1_.define +local core = autoload("eca.nfnl.core") +local M = define("eca.nfnl.string") +M.join = function(...) + local args = {...} + local function _2_(...) + if (2 == core.count(args)) then + return args + else + return {"", core.first(args)} + end + end + local _let_3_ = _2_(...) + local sep = _let_3_[1] + local xs = _let_3_[2] + local len = core.count(xs) + local result = {} + if (len > 0) then + for i = 1, len do + local x = xs[i] + local tmp_6_ + if ("string" == type(x)) then + tmp_6_ = x + elseif (nil == x) then + tmp_6_ = x + else + tmp_6_ = core["pr-str"](x) + end + if (tmp_6_ ~= nil) then + table.insert(result, tmp_6_) + else + end + end + else + end + return table.concat(result, sep) +end +M.split = function(s, pat) + local acc = {} + local done_3f = false + local index = 1 + while not done_3f do + local start, _end = string.find(s, pat, index) + if ("nil" == type(start)) then + table.insert(acc, string.sub(s, index)) + done_3f = true + else + table.insert(acc, string.sub(s, index, (start - 1))) + index = (_end + 1) + end + end + return acc +end +M["blank?"] = function(s) + return (core["empty?"](s) or not string.find(s, "[^%s]")) +end +M.triml = function(s) + return string.gsub(s, "^%s*(.-)", "%1") +end +M.trimr = function(s) + return string.gsub(s, "(.-)%s*$", "%1") +end +M.trim = function(s) + return string.gsub(s, "^%s*(.-)%s*$", "%1") +end +M["ends-with?"] = function(s, suffix) + local suffix_len = #suffix + local s_len = #s + if (s_len >= suffix_len) then + return (suffix == string.sub(s, (s_len - suffix_len - -1))) + else + return false + end +end +return M diff --git a/lua/eca/observer.lua b/lua/eca/observer.lua deleted file mode 100644 index e6a4c30..0000000 --- a/lua/eca/observer.lua +++ /dev/null @@ -1,24 +0,0 @@ -local observer = {} - ----@type { [string]: fun(message: table) } -local subscriptions = {} - ----@param id string ----@param on_update fun(message: table) -function observer.subscribe(id, on_update) - subscriptions[id] = on_update -end - -function observer.unsubscribe(id) - if subscriptions[id] then - subscriptions[id] = nil - end -end - -function observer.notify(message) - for _, fn in pairs(subscriptions) do - fn(message) - end -end - -return observer diff --git a/lua/eca/path_finder.lua b/lua/eca/path_finder.lua deleted file mode 100644 index 71475f7..0000000 --- a/lua/eca/path_finder.lua +++ /dev/null @@ -1,224 +0,0 @@ -local uv = vim.uv or vim.loop -local Utils = require("eca.utils") -local Config = require("eca.config") -local Logger = require("eca.logger") - ----@class eca.PathFinder ----@field private _cache_dir string ----@field private _version_file string -local M = {} -M.__index = M - ----@return eca.PathFinder -function M:new() - local instance = setmetatable({}, M) - instance._cache_dir = Utils.get_cache_dir() - instance._version_file = instance._cache_dir .. "/eca-version" - return instance -end - ----@return table> -function M:_get_artifacts() - return { - darwin = { - x86_64 = "eca-native-macos-amd64.zip", - arm64 = "eca-native-macos-aarch64.zip", - }, - linux = { - x86_64 = "eca-native-static-linux-amd64.zip", - aarch64 = "eca-native-linux-aarch64.zip", - arm64 = "eca-native-linux-aarch64.zip", - }, - windows = { - x86_64 = "eca-native-windows-amd64.zip", - }, - } -end - ----@param platform? string ----@param arch? string ----@return string -function M:_get_artifact_name(platform, arch) - platform = platform or uv.os_uname().sysname:lower() - arch = arch or uv.os_uname().machine - - -- Normalize platform names - if platform:match("darwin") then - platform = "darwin" - elseif platform:match("linux") then - platform = "linux" - elseif platform:match("windows") or platform:match("mingw") or platform:match("msys") then - platform = "windows" - end - - local artifacts = self:_get_artifacts() - local platform_artifacts = artifacts[platform] - - if not platform_artifacts then - error("Unsupported platform: " .. platform) - end - - return platform_artifacts[arch] or "eca.jar" -end - ----@param platform? string ----@param arch? string ----@return string -function M:_get_extension_server_path(platform, arch) - local artifact_name = self:_get_artifact_name(platform, arch) - local name - - if artifact_name:match("%.jar$") then - name = "eca.jar" - else - platform = platform or uv.os_uname().sysname:lower() - name = platform:match("windows") and "eca.exe" or "eca" - end - - return self._cache_dir .. "/" .. name -end - ----@return string? -function M:_read_version_file() - local file = io.open(self._version_file, "r") - if not file then - return nil - end - - local version = file:read("*a"):gsub("%s+", "") - file:close() - return version ~= "" and version or nil -end - ----@param version string -function M:_write_version_file(version) - -- Ensure cache directory exists - vim.fn.mkdir(self._cache_dir, "p") - - local file = io.open(self._version_file, "w") - if file then - file:write(version) - file:close() - else - Logger.warn("Could not write version file: " .. self._version_file) - end -end - ----@return string? -function M:_get_latest_version() - local cmd = "curl -s https://api.github.com/repos/editor-code-assistant/eca/releases/latest" - local handle = io.popen(cmd .. " 2>/dev/null") - - if not handle then - Logger.notify("Failed to check for latest ECA version", vim.log.levels.WARN) - return nil - end - - local response = handle:read("*a") - handle:close() - - if not response or response == "" then - return nil - end - - -- Parse JSON to get tag_name - local tag_match = response:match('"tag_name"%s*:%s*"([^"]+)"') - return tag_match -end - ----@param server_path string ----@param version string ----@return boolean success -function M:_download_latest_server(server_path, version) - local artifact_name = self:_get_artifact_name() - local download_url = - string.format("https://github.com/editor-code-assistant/eca/releases/download/%s/%s", version, artifact_name) - - local download_path = self._cache_dir .. "/" .. artifact_name - - Logger.debug("Downloading latest ECA server version from: " .. download_url) - - -- Ensure cache directory exists - vim.fn.mkdir(self._cache_dir, "p") - - -- Download the file - local download_cmd = string.format( - "curl -L --fail --show-error --silent -o %s %s", - vim.fn.shellescape(download_path), - vim.fn.shellescape(download_url) - ) - - local download_result = os.execute(download_cmd) - if download_result ~= 0 then - error("Failed to download ECA server from: " .. download_url) - end - - -- Extract if it's a zip file - if artifact_name:match("%.zip$") then - local extract_cmd = - string.format("cd %s && unzip -o %s", vim.fn.shellescape(self._cache_dir), vim.fn.shellescape(artifact_name)) - - local extract_result = os.execute(extract_cmd) - if extract_result ~= 0 then - error("Failed to extract ECA server") - end - - -- Remove the zip file after extraction - os.remove(download_path) - end - - -- Make executable (if not Windows) - if not uv.os_uname().sysname:lower():match("windows") then - os.execute("chmod +x " .. vim.fn.shellescape(server_path)) - end - - if not Utils.file_exists(server_path) then - error("ECA server binary not found after download and extraction") - end - - -- Write version file - self:_write_version_file(version) - - Logger.debug("ECA server downloaded successfully") - - return true -end - ----@return string -function M:find() - local server_path = self:_get_extension_server_path() - local latest_version = self:_get_latest_version() - local current_version = self:_read_version_file() - - local server_exists = Utils.file_exists(server_path) - - -- If we can't get the latest version and server doesn't exist, that's an error - if not latest_version and not server_exists then - error( - "Could not fetch latest version of ECA. Please check your internet connection and try again. You can also download ECA manually and set the path in the settings." - ) - end - - -- Download if server doesn't exist or version is outdated - if not server_exists or (latest_version and current_version ~= latest_version) then - if not latest_version then - Logger.warn("Could not check for latest version, using existing server") - return server_path - end - - local success - - local ok, err = pcall(function() - success = self:_download_latest_server(server_path, latest_version) - end) - - if not ok or not success then - error((err and tostring(err)) or "Failed to download ECA server") - end - end - - Logger.debug("Using ECA server: " .. server_path) - return server_path -end - -return M diff --git a/lua/eca/server.lua b/lua/eca/server.lua deleted file mode 100644 index 65b3df6..0000000 --- a/lua/eca/server.lua +++ /dev/null @@ -1,362 +0,0 @@ -local Utils = require("eca.utils") -local Config = require("eca.config") -local Logger = require("eca.logger") - ----@class eca.Server ----@field process vim.SystemObj ----@field messages {content_length: integer, content: string} ----@field next_id integer next outgoing message id ----@field initialized boolean when true, server ready to receive messages ----@field on_initialize? function Callback when server initializes ----@field on_start? function Callback when the server process starts ----@field on_stop function Callback when the server stops ----Called when a notification is received(message without an ID) ----@field on_notification fun(server: eca.Server, message: table) ----@field pending_requests {id: fun(err, data)} -- outgoing requests with callbacks ----@field cwd string Current working directory for the server process ----@field workspace_folders {name: string, uri: string}[] Workspace folders to send on initialize -local M = {} - ----@param opts? table ----@return eca.Server -function M.new(opts) - opts = vim.tbl_extend("keep", opts or {}, { - on_start = function(pid) - require("eca.logger").debug("Started server with pid " .. pid) - end, - on_initialize = function() - require("eca.logger").notify("Server ready to receive messages", vim.log.levels.INFO) - end, - on_stop = function() - require("eca.logger").notify("Server stopped", vim.log.levels.INFO) - end, - ---@param _ eca.Server - ---@param message table - on_notification = function(_, message) - return vim.schedule(function() - require("eca.observer").notify(message) - end) - end, - on_request = function(_, message) - return require("eca.editor").handle_request(message) - end, - cwd = vim.fn.getcwd(), - workspace_folders = { - { - name = vim.fn.fnamemodify(Utils.get_project_root(), ":t"), - uri = "file://" .. Utils.get_project_root(), - }, - }, - }) - - return setmetatable({ - process = nil, - on_start = opts.on_start, - on_initialize = opts.on_initialize, - on_stop = opts.on_stop, - on_notification = opts.on_notification, - on_request = opts.on_request, - messages = {}, - pending_requests = {}, - initialized = false, - next_id = 0, - cwd = opts.cwd, - workspace_folders = opts.workspace_folders, - }, { __index = M }) -end - ----@param server eca.Server ----@return fun(err: string, data: string) -local function on_stdout(server) - return function(err, data) - assert(not err) - if data then - local messages = require("eca.message_handler").parse_raw_messages(data) - vim.iter(messages):each(function(message) - if #message.content ~= message.content_length then - return - end - table.insert(server.messages, message) - local msg = vim.json.decode(message.content) - server:handle_message(msg) - end) - end - end -end - ----@param err string ----@param data string -local function on_stderr(err, data) - assert(not err) - if data then - vim.schedule(function() - require("eca.logger").log(data, vim.log.levels.INFO) - end) - end -end - ----@class eca.ServerStartOpts: vim.SystemOpts ----@field cmd string[] The command to pass to vim.system ----@field on_exit fun(out: vim.SystemCompleted) callback to pass to vim.system ----@field initialize boolean Send the initialize message to ECA on startup, used ----in testing ----@param opts? eca.ServerStartOpts -function M:_run(server_path, opts) - Logger.debug("Starting ECA server: " .. server_path) - - local args = { server_path, "server" } - - if Config.server_args and Config.server_args ~= "" then - vim.list_extend(args, vim.split(Config.server_args, " ")) - end - - opts = vim.tbl_deep_extend("keep", opts, { - cmd = args, - text = true, - cwd = self.cwd, - stdin = true, - stdout = on_stdout(self), - stderr = on_stderr, - ---@param out vim.SystemCompleted - on_exit = function(out) - if out.code ~= 0 then - require("eca.logger").notify(string.format("Server exited with status code %d", out.code), vim.log.levels.ERROR) - end - end, - }) - - local started, process_or_err = pcall(vim.system, opts.cmd, { - cwd = opts.cwd, - text = opts.text, - stdin = opts.stdin, - stdout = opts.stdout, - stderr = opts.stderr, - }, opts.on_exit) - - if not started then - self.process = nil - Logger.notify(vim.inspect(process_or_err), vim.log.levels.ERROR) - return - end - - self.process = process_or_err - if self.on_start then - self.on_start(process_or_err.pid) - end - - if opts.initialize then - self:initialize() - end -end - ----@class eca.ServerStartOpts: vim.SystemOpts ----@field cmd string[] The command to pass to vim.system ----@field on_exit fun(out: vim.SystemCompleted) callback to pass to vim.system ----@field initialize boolean Send the initialize message to ECA on startup, used ----in testing ----@param opts? eca.ServerStartOpts -function M:start(opts) - opts = vim.tbl_deep_extend("force", { initialize = true }, opts or {}) - - -- Check for custom server path first - local custom_path = Config.server_path - if custom_path and custom_path:gsub("%s+", "") ~= "" then - if not Utils.file_exists(custom_path) then - Logger.notify("Custom server path does not exist: " .. custom_path, vim.log.levels.ERROR) - return - end - - self:_run(custom_path, opts) - return - end - - local this_file = debug.getinfo(1, "S").source:sub(2) - local proj_root = vim.fn.fnamemodify(this_file, ":p:h:h:h") - local script_path = proj_root .. "/scripts/server_path.lua" - - local nvim_exe = vim.fn.exepath("nvim") - - if not nvim_exe or nvim_exe == "" then - nvim_exe = "nvim" - end - - local cmd = { nvim_exe, "--headless", "-S", script_path } - - vim.system(cmd, { text = true }, function(out) - if out.code ~= 0 then - Logger.notify(out.stderr, vim.log.levels.ERROR) - return - end - - local stdout_lines = Utils.split_lines(out.stdout) - local server_path = stdout_lines[#stdout_lines] - - self:_run(server_path, opts) - end) -end - -function M:initialize() - self:send_request("initialize", { - processId = vim.fn.getpid(), - clientInfo = { - name = "Neovim", - version = vim.version().major .. "." .. vim.version().minor, - }, - capabilities = { - codeAssistant = { - chat = true, - editor = { diagnostics = true }, - }, - }, - workspaceFolders = vim.deepcopy(self.workspace_folders), - }, function(err, _) - if err then - Logger.notify("Could not initialize server: " .. err, vim.log.levels.ERROR) - return - end - - self:send_notification("initialized", {}) - - if self.on_initialize then - self.on_initialize() - end - self.initialized = true - end) -end - -function M:stop() - if self.process then - self:send_request("shutdown", {}, function(err, _) - if err then - self.process:kill("TERM") - return - end - self:send_request("exit", {}) - if self.on_stop then - self:on_stop() - end - self.process = nil - end) - end - - self._rpc = nil - self.next_id = 0 - self.initialized = false -end - ----@return boolean -function M:is_running() - return self.process and not self.process:is_closing() -end - ----@param message table incoming decoded JSON message -function M:handle_message(message) - if message.id and self.pending_requests[message.id] then - local callback = self.pending_requests[message.id] - self.pending_requests[message.id] = nil - - if message.error then - callback(message.error, nil) - else - callback(nil, message.result) - end - elseif message.id and message.method then - if self.on_request then - local id = message.id - vim.schedule(function() - local ok, result = pcall(self.on_request, self, message) - if not ok then - Logger.error("on_request error: " .. tostring(result)) - pcall(self.send_error_response, self, id, -32603, "Internal error") - return - end - if result == nil then - pcall(self.send_error_response, self, id, -32601, "Method not found") - return - end - local ok2, err = pcall(self.send_response, self, id, result) - if not ok2 then - Logger.error("send_response error: " .. tostring(err)) - end - end) - end - elseif message.method and not message.id then - if self.on_notification then - self:on_notification(message) - end - end -end - ----@param id integer|string ----@param result table -function M:send_response(id, result) - if not self:is_running() then - Logger.error("send_response: server not running, dropping response for id=" .. tostring(id)) - return - end - local message = { jsonrpc = "2.0", id = id, result = result } - local json = vim.json.encode(message) - local content = string.format("Content-Length: %d\r\n\r\n%s", #json, json) - self.process:write(content) -end - ----@param id integer|string ----@param code integer JSON-RPC error code ----@param msg string -function M:send_error_response(id, code, msg) - if not self:is_running() then - Logger.error("send_error_response: server not running, dropping error for id=" .. tostring(id)) - return - end - local message = { jsonrpc = "2.0", id = id, error = { code = code, message = msg } } - local json = vim.json.encode(message) - local content = string.format("Content-Length: %d\r\n\r\n%s", #json, json) - self.process:write(content) -end - ----@return integer -function M:get_next_id() - self.next_id = self.next_id + 1 - return self.next_id -end - ----@param method string ----@param params table ----@param callback? function -function M:send_request(method, params, callback) - local id = self:get_next_id() - local message = { - jsonrpc = "2.0", - method = method, - params = params, - } - if callback then - message.id = id - self.pending_requests[id] = callback - end - - local json = vim.json.encode(message) - table.insert(self.messages, { content = json, content_length = #json }) - - if not self:is_running() then - Logger.error("ECA server is not running") - if callback then - callback("Server not running", nil) - end - return - end - - local content = string.format("Content-Length: %d\r\n\r\n%s", #json, json) - self.process:write(content) -end - ----@param method string ----@param params table -function M:send_notification(method, params) - if not self:is_running() then - return - end - self:send_request(method, params) -end - -return M diff --git a/lua/eca/sidebar.lua b/lua/eca/sidebar.lua deleted file mode 100644 index 895f8dd..0000000 --- a/lua/eca/sidebar.lua +++ /dev/null @@ -1,3225 +0,0 @@ -local Utils = require("eca.utils") -local Logger = require("eca.logger") -local Config = require("eca.config") -local StreamQueue = require("eca.stream_queue") - --- Load nui.nvim components (required dependency) -local Split = require("nui.split") - ----@class eca.Sidebar ----@field public id integer The tab ID ----@field public containers table The nui containers ----@field public extmarks table The extmarks for various UI elements ----@field mediator eca.Mediator mediator to send server requests to ----@field private _initialized boolean Whether the sidebar has been initialized ----@field private _current_response_buffer string Buffer for accumulating streaming response ----@field private _is_streaming boolean Whether we're currently receiving a streaming response ----@field private _usage_info string Current usage information ----@field private _last_user_message string Last user message to avoid duplicates ----@field private _current_tool_call table Current tool call being accumulated ----@field private _is_tool_call_streaming boolean Whether we're currently receiving a streaming tool call ----@field private _force_welcome boolean Whether to force show welcome content on next open ----@field private _current_status string Current processing status message ----@field private _augroup integer Autocmd group ID ----@field private _response_start_time number Timestamp when streaming started ----@field private _max_response_length number Maximum allowed response length ----@field private _headers table Table of headers for the chat ----@field private _welcome_message_applied boolean Whether the welcome message has been applied ----@field private _contexts_placeholder_line string Placeholder line for contexts in input ----@field private _reasons table Map of in-flight reasoning entries keyed by id ----@field private _stream_queue eca.StreamQueue Queue for streaming text display ----@field private _stream_visible_buffer string Accumulated visible text during streaming - -local M = {} -M.__index = M - --- Height calculation constants -local MIN_CHAT_HEIGHT = 10 -- Minimum lines for chat container to remain usable -local WINDOW_MARGIN = 3 -- Additional margin for window borders and spacing -local UI_ELEMENTS_HEIGHT = 2 -- Reserve space for statusline and tabline -local SAFETY_MARGIN = 2 -- Extra margin to prevent "Not enough room" errors - -local function _format_usage(tokens, limit, costs) - local usage_cfg = (Config.windows and Config.windows.usage) or {} - local fmt = usage_cfg.format - or Config.usage_string_format -- backwards compatibility - or "{session_tokens_short} / {limit_tokens_short} (${session_cost})" - - local placeholders = { - session_tokens = tostring(tokens or 0), - limit_tokens = tostring(limit or 0), - session_tokens_short = Utils.shorten_tokens(tokens), - limit_tokens_short = Utils.shorten_tokens(limit), - session_cost = tostring(costs or "0.00"), - } - - local result = fmt:gsub("{(.-)}", function(key) - return placeholders[key] or "" - end) - - return result -end - ----@param id integer Tab ID ----@param mediator eca.Mediator ----@return eca.Sidebar -function M.new(id, mediator) - local chat_cfg = Utils.get_chat_config() - local instance = setmetatable({}, M) - instance.id = id - instance.mediator = mediator - instance.containers = {} - instance.extmarks = {} - instance._initialized = false - instance._current_response_buffer = "" - instance._is_streaming = false - instance._usage_info = "" - instance._last_user_message = "" - instance._current_tool_call = nil - instance._is_tool_call_streaming = false - instance._force_welcome = false - instance._current_status = "" - instance._augroup = vim.api.nvim_create_augroup("eca_sidebar_" .. id, { clear = true }) - instance._response_start_time = 0 - instance._max_response_length = 50000 -- 50KB max response - instance._headers = { - user = (chat_cfg.headers and chat_cfg.headers.user) or "> ", - assistant = (chat_cfg.headers and chat_cfg.headers.assistant) or "", - } - instance._welcome_message_applied = false - instance._contexts_placeholder_line = "" - instance._contexts = {} - instance._tool_calls = {} - instance._reasons = {} - instance._stream_visible_buffer = "" - - -- Get typing configuration - local typing_cfg = chat_cfg.typing or {} - local typing_enabled = typing_cfg.enabled ~= false -- Default to true - local chars_per_tick = typing_enabled and (typing_cfg.chars_per_tick or 1) or 1000 -- Large number = instant - local tick_delay = typing_enabled and (typing_cfg.tick_delay or 10) or 0 - - -- Initialize stream queue with callback to update display - instance._stream_queue = StreamQueue.new(function(chunk, is_complete) - instance._stream_visible_buffer = (instance._stream_visible_buffer or "") .. chunk - instance:_update_streaming_message(instance._stream_visible_buffer) - end, { - chars_per_tick = chars_per_tick, - tick_delay = tick_delay, - should_continue = function() - return instance._is_streaming - end, - }) - - require("eca.observer").subscribe("sidebar-" .. id, function(message) - instance:handle_chat_content(message) - end) - return instance -end - ----@return boolean -function M:is_open() - return self.containers.chat and self.containers.chat.winid and vim.api.nvim_win_is_valid(self.containers.chat.winid) -end - ----@param opts? table -function M:open(opts) - opts = opts or {} - - if self:is_open() then - self:_focus_input() - return - end - - -- Clean up any invalid containers - self:_cleanup_invalid_containers() - - -- Create/recreate containers using nui.split - self:_create_containers() - - -- Setup containers if not initialized or if we need to refresh content - if not self._initialized then - Logger.debug("Setting up containers (first time)") - self:_setup_containers() - else - Logger.debug("Reusing existing containers") - self:_refresh_container_content() - end - - -- Always focus input when opening - self:_focus_input() - - Logger.debug("ECA sidebar opened") -end - -function M:close() - self:_close_windows_only() -end - -function M:_close_windows_only() - local preserve = Config.behavior and Config.behavior.preserve_chat_history - - for name, container in pairs(self.containers) do - if container and container.winid and vim.api.nvim_win_is_valid(container.winid) then - if preserve and name == "chat" then - -- Close only the window, keep the buffer alive - pcall(vim.api.nvim_win_close, container.winid, true) - container.winid = nil - else - container:unmount() - -- Keep the container reference but mark window as invalid - container.winid = nil - end - end - end - Logger.debug("ECA sidebar windows closed") -end - -function M:_close_and_cleanup() - for name, container in pairs(self.containers) do - if container then - if container.winid and vim.api.nvim_win_is_valid(container.winid) then - container:unmount() - end - -- Check if buffer is displayed elsewhere before deleting - if container.bufnr and vim.api.nvim_buf_is_valid(container.bufnr) then - local wins = vim.fn.win_findbuf(container.bufnr) - if #wins == 0 then - pcall(vim.api.nvim_buf_delete, container.bufnr, { force = true }) - end - end - end - end - self.containers = {} - Logger.debug("ECA sidebar closed and cleaned up") -end - ----@param opts? table ----@return boolean -function M:toggle(opts) - if self:is_open() then - self:close() - return false - else - self:open(opts) - return true - end -end - -function M:focus() - if self:is_open() then - self:_focus_input() - else - self:open() - end -end - -function M:resize() - if not self:is_open() then - return - end - - -- Recalculate and update container sizes - self:_update_container_sizes() -end - -function M:reset() - if self:is_open() then - self:_close_and_cleanup() - else - self:_close_and_cleanup() - end - - -- Reset all state - self.containers = {} - self.extmarks = {} - self._initialized = false - self._is_streaming = false - self._current_response_buffer = "" - self._usage_info = "" - self._last_user_message = "" - self._current_tool_call = nil - self._is_tool_call_streaming = false - self._force_welcome = false - self._current_status = "" - self._welcome_message_applied = false - self._contexts_placeholder_line = "" - self._contexts = {} - self._tool_calls = {} - self._reasons = {} - self._stream_visible_buffer = "" - if self._stream_queue then - self._stream_queue:clear() - end -end - -function M:clear_chat() - local chat = self.containers and self.containers.chat - if chat and chat.bufnr and vim.api.nvim_buf_is_valid(chat.bufnr) then - local chat_id = self.mediator:id() - if chat_id then - self.mediator:send("chat/clear", { chatId = chat_id, messages = true }, nil) - end - - -- Reset chat content state to prevent stale line numbers / extmark IDs. - self._tool_calls = {} - self._reasons = {} - self._current_tool_call = nil - self._is_tool_call_streaming = false - self._is_streaming = false - self._current_response_buffer = "" - self._last_user_message = "" - self._stream_visible_buffer = "" - if self._stream_queue then - self._stream_queue:clear() - end - -- Reset chat extmark refs (marks are invalidated when the buffer is wiped). - if self.extmarks then - self.extmarks.assistant = nil - self.extmarks.tool_header = nil - self.extmarks.tool_diff_label = nil - end - -- Prevent state/updated events from repopulating the cleared buffer. - self._welcome_message_applied = true - self._force_welcome = false - vim.api.nvim_buf_set_lines(chat.bufnr, 0, -1, false, {}) - end -end - -function M:new_chat() - self:reset() - self._force_welcome = true - Logger.debug("New chat initiated - will show welcome content on next open") -end - ----@private -function M:_cleanup_invalid_containers() - for name, container in pairs(self.containers) do - if container then - -- Check if window is still valid - if container.winid and not vim.api.nvim_win_is_valid(container.winid) then - container.winid = nil - end - -- Check if buffer is still valid - if container.bufnr and not vim.api.nvim_buf_is_valid(container.bufnr) then - container.bufnr = nil - end - end - end -end - ----@private -function M:_create_containers() - local width = Config.get_window_width() - - -- Calculate dynamic heights using existing methods - local input_height = Config.windows.input.height - local usage_height = 1 - local original_chat_height = self:get_chat_height() - local chat_height = original_chat_height - local config_height = 1 - - -- Validate total height to prevent "Not enough room" error - local total_height = chat_height - + input_height - + usage_height - + config_height - - -- Always calculate from total screen minus UI elements (more accurate than current window) - local available_height = vim.o.lines - UI_ELEMENTS_HEIGHT - - if total_height > available_height then - Logger.debug( - string.format( - "Total height (%d) exceeds available height (%d), adjusting chat height", - total_height, - available_height - ) - ) - local extra_height = total_height - (available_height - SAFETY_MARGIN) - chat_height = math.max(MIN_CHAT_HEIGHT, chat_height - extra_height) - Logger.debug(string.format("Adjusted chat height from %d to %d", original_chat_height, chat_height)) - end - - -- Base options for all containers - local base_buf_options = { - buftype = "nofile", - bufhidden = "hide", - swapfile = false, - } - - local base_win_options = { - wrap = Config.windows.wrap, - number = false, - relativenumber = false, - signcolumn = "no", - foldcolumn = "0", - cursorline = false, - winfixheight = true, - winfixwidth = false, - } - - local preserve = Config.behavior and Config.behavior.preserve_chat_history - local existing_chat_bufnr = preserve - and self.containers.chat - and self.containers.chat.bufnr - and vim.api.nvim_buf_is_valid(self.containers.chat.bufnr) - and self.containers.chat.bufnr - or nil - - -- Always unmount the old Split to clean up its autocmds. - local old_chat = self.containers.chat - if old_chat then - if existing_chat_bufnr then - old_chat.bufnr = nil -- detach so unmount() doesn't delete the preserved buffer - end - pcall(old_chat.unmount, old_chat) - end - - -- Create and mount main chat container first - self.containers.chat = Split({ - relative = "editor", - position = "right", - size = { - width = width, - height = chat_height, - }, - buf_options = vim.tbl_deep_extend("force", base_buf_options, { - modifiable = true, - filetype = "markdown", - }), - win_options = base_win_options, - }) - - if existing_chat_bufnr then - pcall(vim.api.nvim_buf_delete, self.containers.chat.bufnr, { force = true }) - self.containers.chat.bufnr = existing_chat_bufnr - Logger.debug("Reusing existing chat buffer: " .. existing_chat_bufnr) - end - - self.containers.chat:mount() - self:_setup_container_events(self.containers.chat, "chat") - - -- Track the current container for hierarchical mounting with proper space management - local current_winid = self.containers.chat.winid - Logger.debug("Mounted container: chat (winid: " .. current_winid .. ")") - - -- Create config container in top of chat - self.containers.config = Split({ - relative = { - type = "win", - winid = current_winid, - }, - position = "top", - size = { height = config_height }, - buf_options = vim.tbl_deep_extend("force", base_buf_options, { - modifiable = false, - }), - win_options = vim.tbl_deep_extend("force", base_win_options, { - winhighlight = "Normal:Normal", - }), - }) - self.containers.config:mount() - self:_setup_container_events(self.containers.config, "config") - Logger.debug("Mounted container: config (winid: " .. self.containers.config.winid .. ")") - - -- Create input container (always present) - self.containers.input = Split({ - relative = { - type = "win", - winid = current_winid, - }, - position = "bottom", - size = { height = input_height }, - buf_options = vim.tbl_deep_extend("force", base_buf_options, { - modifiable = true, - filetype = "eca-input", - }), - win_options = vim.tbl_deep_extend("force", base_win_options, { - statusline = " ", - }), - }) - self.containers.input:mount() - self:_setup_container_events(self.containers.input, "input") - current_winid = self.containers.input.winid - Logger.debug("Mounted container: input (winid: " .. current_winid .. ")") - - -- Create usage container (always present) - moved to bottom - self.containers.usage = Split({ - relative = { - type = "win", - winid = current_winid, - }, - enter = false, - position = "bottom", - size = { height = usage_height }, - buf_options = vim.tbl_deep_extend("force", base_buf_options, { - modifiable = false, - }), - win_options = vim.tbl_deep_extend("force", base_win_options, { - winhighlight = "Normal:EcaLabel", - statusline = " ", - }), - }) - self.containers.usage:mount() - self:_setup_container_events(self.containers.usage, "usage") - Logger.debug("Mounted container: usage (winid: " .. self.containers.usage.winid .. ")") - - Logger.debug( - string.format( - "Created containers: chat=%d, input=%d, usage=%d, config=%d", - chat_height, - input_height, - usage_height, - config_height - ) - ) -end - ----@private ----@param container NuiSplit ----@param name string -function M:_setup_container_events(container, name) - -- Setup container-specific keymaps - if name == "input" then - self:_setup_input_events(container) - self:_setup_input_keymaps(container) - elseif name == "chat" then - self:_setup_chat_keymaps(container) - end -end - ----@private ----@param name string -function M:_handle_container_closed(name) - -- Handle when a container window is closed - if self.containers[name] then - self.containers[name].winid = nil - end -end - ----@private ----@param container NuiSplit -function M:_setup_input_events(container) - vim.api.nvim_create_autocmd("User", { - pattern = { "CompletionItemSelected" }, - callback = function(event) - if not event.data or not event.data.context_item or not event.data.label then - return - end - - if self._contexts then - self._contexts.to_add = { - name = event.data.label, - type = event.data.context_item.type, - data = { - path = event.data.context_item.path - } - } - end - end, - }) - - -- contexts area and input handler - vim.api.nvim_buf_attach(container.bufnr, false, { - on_lines = function(_, buf, _changedtick, first, _last, _new_last, _bytecount) - vim.schedule(function() - local lines = vim.api.nvim_buf_get_lines(buf, 0, -1, false) - - -- handle empty buffer - if not lines or #lines < 1 then - self:_update_input_display() - return - end - - local prefix_extmark = self.extmarks.prefix or nil - local contexts_extmark = self.extmarks.contexts or nil - - if not prefix_extmark or not contexts_extmark then - return - end - - local prefix_ns = prefix_extmark._ns or nil - local prefix_id = prefix_extmark._id and prefix_extmark._id[1] or nil - - if not prefix_ns or not prefix_id then - return - end - - local prefix_mark = vim.api.nvim_buf_get_extmark_by_id(buf, prefix_ns, prefix_id, {}) - local prefix_row = 1 - if prefix_mark and type(prefix_mark) == "table" and prefix_mark[1] ~= nil then - prefix_row = tonumber(prefix_mark[1]) or 1 - end - local contexts_row = 0 - - local prefix_line = lines[prefix_row + 1] or nil - local contexts_line = lines[contexts_row + 1] or nil - local contexts_placeholder_line = self._contexts_placeholder_line or "" - - if prefix_row == contexts_row then - -- prefix line missing, restore - if contexts_line == contexts_placeholder_line then - self:_update_input_display() - return - end - - -- we can consider that contexts were deleted - self.mediator:clear_contexts() - return - end - - -- prefix line missing, restore - if not prefix_line and contexts_line == contexts_placeholder_line then - self:_update_input_display() - return - end - - -- something wrong, restore - if prefix_row - contexts_row ~= 1 then - self:_update_input_display() - return - end - - local context_to_add = self._contexts.to_add or {} - - if contexts_line ~= contexts_placeholder_line then - -- a context was removed - if #contexts_line < #self._contexts_placeholder_line then - local contexts = self.mediator:contexts() - - local row, col = unpack(vim.api.nvim_win_get_cursor(container.winid)) - local context = contexts[col + 1] - - if row == 1 and context then - self.mediator:remove_context(context) - return - end - end - - -- contexts line modified - if #contexts_line > #self._contexts_placeholder_line then - local placeholders = vim.split(contexts_line, "@", { plain = true, trimempty = true }) - - for i = 1, #placeholders do - if context_to_add.name and context_to_add.name == placeholders[i] then - self.mediator:add_context(context_to_add) - self._contexts.to_add = {} - end - end - - return - end - - self:_update_input_display() - return - end - end) - end - }) -end - ----@private ----@param container NuiSplit -function M:_setup_input_keymaps(container) - local submit = Config.mappings.submit - container:map("n", submit.normal, function() - self:_handle_input() - end, { noremap = true, silent = true }) - - container:map("i", submit.insert, function() - self:_handle_input() - end, { noremap = true, silent = true }) -end - ----@private ----@param container NuiSplit -function M:_setup_chat_keymaps(container) - -- Toggle tool call details when pressing on a tool call line - container:map("n", "", function() - self:_toggle_tool_call_at_cursor() - end, { noremap = true, silent = true }) -end - ----@private -function M:_update_container_sizes() - if not self:is_open() then - return - end - - -- Recalculate heights - local new_heights = { - chat = self:get_chat_height(), - input = Config.windows.input.height, - usage = 1, - } - - -- Update container sizes - for name, height in pairs(new_heights) do - local container = self.containers[name] - if container and container.winid and vim.api.nvim_win_is_valid(container.winid) then - if height > 0 then - vim.api.nvim_win_set_height(container.winid, height) - end - end - end -end - -function M:get_chat_height() - local total_height = vim.o.lines - vim.o.cmdheight - 1 - local input_height = Config.windows.input.height - local usage_height = 1 - local config_height = 1 - - return math.max( - MIN_CHAT_HEIGHT, - total_height - - input_height - - usage_height - - WINDOW_MARGIN - - config_height - ) -end - --- Placeholder methods for the display and setup functions --- These will use the same logic as the original sidebar but with nui containers - -function M:_setup_containers() - -- Setup each container's content and behavior - self:_setup_chat_container() - - self:_update_config_display() - self:_setup_input_container() - self:_setup_usage_container() - - self._initialized = true -end - -function M:_refresh_container_content() - -- Refresh content without full setup - if self.containers.chat then - self:_set_welcome_content() - end - - if self.containers.config then - self:_update_config_display() - end - - if self.containers.input then - self:_update_input_display() - end - - if self.containers.usage then - self:_update_usage_info() - end -end - -function M:_handle_state_updated(state) - if state.contexts then - self:_update_input_display() - end - - if state.usage or state.status then - self:_update_usage_info() - end - - if state.config or state.tools then - self:_update_config_display() - self:_update_welcome_content() - end -end - --- Placeholder for all the other methods from original sidebar --- (These would be copied over with minimal modifications to work with nui containers) - -function M:_setup_chat_container() - local chat = self.containers.chat - if not chat then - return - end - - -- Set buffer options for chat - vim.api.nvim_set_option_value("buftype", "nofile", { buf = chat.bufnr }) - vim.api.nvim_set_option_value("bufhidden", "hide", { buf = chat.bufnr }) - vim.api.nvim_set_option_value("swapfile", false, { buf = chat.bufnr }) - vim.api.nvim_set_option_value("modifiable", true, { buf = chat.bufnr }) - - -- Disable treesitter initially to prevent highlighting errors during setup - vim.api.nvim_set_option_value("syntax", "off", { buf = chat.bufnr }) - - -- Set initial content first - self:_set_welcome_content() - - -- Set filetype to markdown for syntax highlighting - vim.defer_fn(function() - if vim.api.nvim_buf_is_valid(chat.bufnr) then - vim.api.nvim_set_option_value("filetype", "markdown", { buf = chat.bufnr }) - vim.api.nvim_set_option_value("syntax", "on", { buf = chat.bufnr }) - end - end, 200) -end - -function M:_setup_usage_container() - local usage = self.containers.usage - if not usage then - return - end - - -- Set initial usage info - self:_update_usage_info() -end - -function M:_setup_input_container() - local input = self.containers.input - if not input then - return - end - - -- Set initial input prompt - self:_update_input_display() -end - --- Placeholder methods that need to be implemented --- (These would be copied from the original sidebar with minimal modifications) - -function M:_set_welcome_content() - -- Implementation from original sidebar - local chat = self.containers.chat - if not chat then - return - end - - -- Check if we should force welcome content (new chat) - if not self._force_welcome then - -- Check if buffer already has content (more than just empty lines) - local existing_lines = vim.api.nvim_buf_get_lines(chat.bufnr, 0, -1, false) - local has_content = false - - for _, line in ipairs(existing_lines) do - if line:match("%S") then -- Has non-whitespace content - has_content = true - break - end - end - - -- Only set welcome content if buffer is empty or has no meaningful content - if has_content then - Logger.debug("Preserving existing chat content") - return - end - else - -- Force welcome content and reset the flag - Logger.debug("Forcing welcome content for new chat") - self._force_welcome = false - end - - self:_update_welcome_content() -end - -function M:_update_input_display(opts) - return vim.schedule(function() - local input = self.containers.input - if not input then - return - end - - local contexts = (self.mediator and self.mediator:contexts()) or {} - local contexts_name = {} - - if #contexts > 0 then - for _, context in ipairs(contexts) do - local path = context.data.path - - if not path or path == "" then - break - end - - local name - if context.type == "web" then - name = path - local max_len = (Config.windows and Config.windows.input and Config.windows.input.web_context_max_len) or 20 - if #name > max_len then - name = string.sub(name, 1, max_len - 3) .. "..." - end - else - name = vim.fn.fnamemodify(path, ":t") - end - - local lines_range = context.data.lines_range - - if lines_range and lines_range.line_start and lines_range.line_end then - name = string.format("%s:%d-%d", name, lines_range.line_start, lines_range.line_end) - end - - table.insert(contexts_name, name .. " ") - end - end - - self._contexts_placeholder_line = "@" - for _ = 1, #contexts_name do - self._contexts_placeholder_line = self._contexts_placeholder_line .. "@" - end - - local prefix_extmark = self.extmarks.prefix or nil - local prefix_ns = prefix_extmark and prefix_extmark._ns or nil - local prefix_id = prefix_extmark and prefix_extmark._id and prefix_extmark._id[1] or nil - local prefix_row = 1 - - if prefix_ns and prefix_id then - local prefix_mark = vim.api.nvim_buf_get_extmark_by_id(input.bufnr, prefix_ns, prefix_id, {}) - prefix_row = prefix_mark and #prefix_mark > 0 and prefix_mark[1] or 1 - end - - -- Get existing lines to preserve user input (lines after the header) - local existing_lines = vim.api.nvim_buf_get_lines(input.bufnr, prefix_row, -1, false) - - vim.api.nvim_buf_set_lines(input.bufnr, 0, -1, false, { self._contexts_placeholder_line, "" }) - - if not self.extmarks.contexts then - self.extmarks.contexts = { - _ns = vim.api.nvim_create_namespace('extmarks_contexts'), - } - end - - if not self.extmarks.contexts._id then - self.extmarks.contexts._id = {} - end - - vim.api.nvim_buf_clear_namespace(input.bufnr, self.extmarks.contexts._ns, 0, -1) - - for i, context_name in ipairs(contexts_name) do - self.extmarks.contexts._id[i] = vim.api.nvim_buf_set_extmark( - input.bufnr, - self.extmarks.contexts._ns, - 0, - i, - vim.tbl_extend("force", - { virt_text = { { context_name, "EcaLabel" } }, virt_text_pos = "inline", hl_mode = "replace" }, - { id = self.extmarks.contexts._id[i] }) - ) - end - - local prefix = Config.windows.input.prefix or "> " - - if not self.extmarks.prefix then - self.extmarks.prefix = { - _ns = vim.api.nvim_create_namespace('extmarks_prefix'), - } - end - - local clear = opts and opts.clear - - if #existing_lines > 0 and not clear then - vim.api.nvim_buf_set_lines(input.bufnr, 1, 1 + #existing_lines, false, existing_lines) - end - - if not self.extmarks.prefix._id then - self.extmarks.prefix._id = {} - end - - self.extmarks.prefix._id[1] = vim.api.nvim_buf_set_extmark( - input.bufnr, - self.extmarks.prefix._ns, - 1, - 0, - vim.tbl_extend("force", { virt_text = { { prefix, "Normal" } }, virt_text_pos = "inline", right_gravity = false }, - { id = self.extmarks.prefix._id[1] }) - ) - - -- Set cursor to end of input line - if vim.api.nvim_win_is_valid(input.winid) then - local row = 1 + ((not clear and existing_lines and #existing_lines > 0) and #existing_lines or 1) - local col = #prefix + - ((not clear and existing_lines and #existing_lines > 0) and #existing_lines[#existing_lines] or 0) - - vim.api.nvim_win_set_cursor(input.winid, { row, col }) - end - end) -end - -function M:_focus_input() - local input = self.containers.input - if not input or not vim.api.nvim_win_is_valid(input.winid) then - Logger.notify("Cannot focus input: invalid window", vim.log.levels.ERROR) - return - end - - vim.defer_fn(function() - if vim.api.nvim_win_is_valid(input.winid) and vim.api.nvim_buf_is_valid(input.bufnr) then - vim.api.nvim_set_current_win(input.winid) - - local lines = vim.api.nvim_buf_get_lines(input.bufnr, 0, -1, false) - local prefix = Config.windows.input.prefix or "> " - - local row = 2 - local col = #prefix - - -- Ensure there is at least a header and a prefix line - if #lines < 2 then - row = 1 - col = 0 - end - - vim.api.nvim_win_set_cursor(input.winid, { row, col }) - - -- Enter insert mode - if Config.windows and Config.windows.edit and Config.windows.edit.start_insert then - local mode = vim.api.nvim_get_mode().mode - if mode == "n" then - vim.cmd("startinsert!") - end - end - end - end, 100) -end - -function M:_handle_input() - local input = self.containers.input - if not input then - return - end - - local lines = vim.api.nvim_buf_get_lines(input.bufnr, 0, -1, false) - if #lines < 2 then - return - end - - -- Process input: ignore first line (contexts header) and use second line onwards as input - local message_lines = {} - local prefix = Config.windows.input.prefix or "> " - - for i = 2, #lines do - local line = lines[i] - local content = line - if i == 2 and vim.startswith(line, prefix) then - content = line:sub(#prefix + 1) - end - if content ~= "" then - table.insert(message_lines, content) - end - end - - local message = table.concat(message_lines, "\n") - if message == "" then - return - end - - -- Send message - self:_send_message(message) - - -- Add new input line and focus - self:_update_input_display({ clear = true }) - self:_focus_input() -end - -function M:_update_config_display() - local config = self.containers.config - if not config or not config.bufnr or not vim.api.nvim_buf_is_valid(config.bufnr) then - return - end - - local model = tostring(self.mediator:selected_model() or "unknown") - local behavior = tostring(self.mediator:selected_behavior() or "unknown") - local mcps = self.mediator:mcps() - - local registered_count = vim.tbl_count(mcps) - local starting_count = 0 - local running_count = 0 - local has_failed = false - - for _, mcp in pairs(mcps) do - if mcp.status == "starting" then - starting_count = starting_count + 1 - elseif mcp.status == "running" then - running_count = running_count + 1 - end - - if mcp.status == "failed" then - has_failed = true - end - end - - -- Active MCPs include both starting and running - local active_count = starting_count + running_count - - -- While any MCP is still starting, dim the active count - local active_hl = "Normal" - if starting_count > 0 then - active_hl = "EcaLabel" - end - - local registered_hl = "Normal" - if has_failed then - registered_hl = "Exception" -- highlight registered count in red when any MCP failed - elseif active_hl == "EcaLabel" then - -- While MCPs are still starting, dim the total count as well - registered_hl = "EcaLabel" - end - - local texts = { - { "model:", "EcaLabel" }, { model, "Normal" }, { " " }, - { "behavior:", "EcaLabel" }, { behavior, "Normal" }, { " " }, - { "mcps:", "EcaLabel" }, { tostring(active_count), active_hl }, { "/", "EcaLabel" }, - { tostring(registered_count), registered_hl }, - } - - local virt_opts = { virt_text = texts, virt_text_pos = "overlay", hl_mode = "combine" } - - if not self.extmarks.config then - self.extmarks.config = { - _ns = vim.api.nvim_create_namespace('extmarks_config'), - } - end - - vim.api.nvim_set_option_value("modifiable", true, { buf = config.bufnr }) - vim.api.nvim_buf_set_lines(config.bufnr, 0, -1, false, { "" }) - vim.api.nvim_set_option_value("modifiable", false, { buf = config.bufnr }) - - self.extmarks.config._id = vim.api.nvim_buf_set_extmark( - config.bufnr, - self.extmarks.config._ns, - 0, - -1, - vim.tbl_extend("force", virt_opts, { id = self.extmarks.config._id }) - ) -end - -function M:_update_usage_info() - local usage = self.containers.usage - if not usage or not usage.bufnr or not vim.api.nvim_buf_is_valid(usage.bufnr) then - return - end - - local status_state = self.mediator:status_state() - local status_text = self.mediator:status_text() - - if status_state == "finished" then - status_text = "Idle" - end - - local tokens = self.mediator:tokens_session() or 0 - local limit = self.mediator:tokens_limit() or 0 - local costs = self.mediator:costs_session() or "0.00" - - self._current_status = string.format("%s", status_text) - self._usage_info = _format_usage(tokens, limit, costs) - - self.extmarks = self.extmarks or {} - - if not self.extmarks.usage then - self.extmarks.usage = { - _ns = vim.api.nvim_create_namespace('extmarks_usage'), - } - end - - vim.api.nvim_set_option_value("modifiable", true, { buf = usage.bufnr }) - vim.api.nvim_buf_set_lines(usage.bufnr, 0, -1, false, { "" }) - vim.api.nvim_set_option_value("modifiable", false, { buf = usage.bufnr }) - - self.extmarks.usage._id_status = vim.api.nvim_buf_set_extmark( - usage.bufnr, - self.extmarks.usage._ns, - 0, - -1, - vim.tbl_extend("force", - { - virt_text = { { self._current_status, (status_text ~= "Idle") and "WarningMsg" or "Normal" } }, - virt_text_pos = 'eol', - hl_mode = 'combine', - }, - { id = self.extmarks.usage._id_status }) - ) - - self.extmarks.usage._id_usage = vim.api.nvim_buf_set_extmark( - usage.bufnr, - self.extmarks.usage._ns, - 0, - -1, - vim.tbl_extend("force", - { - virt_text = { { self._usage_info } }, - virt_text_pos = 'right_align', - hl_mode = 'combine', - }, - { id = self.extmarks.usage._id_usage }) - ) -end - -function M:_update_welcome_content() - if self._welcome_message_applied then - return - end - - local chat = self.containers.chat - if not chat or not vim.api.nvim_buf_is_valid(chat.bufnr) then - return - end - - local chat_cfg = Utils.get_chat_config() - local cfg = chat_cfg.welcome or {} - local cfg_msg = (cfg.message and cfg.message ~= "" and cfg.message) or nil - local welcome_message = cfg_msg or (self.mediator and self.mediator:welcome_message() or nil) - - local lines = { "Waiting for server to start..." } - - if welcome_message and welcome_message ~= "" then - lines = Utils.split_lines(welcome_message) - - local tips = cfg.tips or {} - - if #tips > 0 then - local submit = Config.mappings.submit - local placeholders = { - submit_key_normal = submit.normal, - submit_key_insert = submit.insert, - } - for _, tip in ipairs(tips) do - local rendered = tip:gsub("{(.-)}", function(k) - return placeholders[k] or ("{" .. k .. "}") - end) - table.insert(lines, rendered) - end - end - - self._welcome_message_applied = true - end - - table.insert(lines, "") - Logger.debug("Setting welcome content for chat (welcome applied: " .. tostring(self._welcome_message_applied) .. ")") - vim.api.nvim_buf_set_lines(chat.bufnr, 0, -1, false, lines) -end - -function M:_render_header(container_name, header_text) - if not Config.windows.sidebar_header.enabled then - return {} - end - - local align = Config.windows.sidebar_header.align or "center" - local rounded = Config.windows.sidebar_header.rounded - - if rounded then - header_text = "『" .. header_text .. "』" - else - header_text = " " .. header_text .. " " - end - - return { header_text } -end - --- ===== Message handling methods (copied from original sidebar) ===== - ----@param message string -function M:_send_message(message) - if not message or type(message) ~= "string" then - Logger.error("Cannot send empty message") - return - end - - -- Add user message to chat - self:_add_message("user", message) - - local replaced = message:gsub("([@#])([%w%._%-%/\\]+)", function(prefix, path) - -- expand ~ - if vim.startswith(path, "~") then - path = vim.fn.expand(path) - end - return prefix .. vim.fn.fnamemodify(path, ":p") - end) - - message = replaced - - -- Store the last user message to avoid duplication - self._last_user_message = message - - local contexts = self.mediator:contexts() - self.mediator:send("chat/prompt", { - chatId = self.mediator:id(), - requestId = tostring(os.time()), - message = message, - contexts = contexts or {}, - model = self.mediator:selected_model(), - behavior = self.mediator:selected_behavior(), - }, function(err, result) - if err then - Logger.error("Failed to send message to ECA server: " .. vim.inspect(err)) - self:_add_message("assistant", "❌ **Error**: Failed to send message to ECA server: " .. vim.inspect(err)) - return - end - -- Response will come through server notification handler - self:_update_input_display() - - self:handle_chat_content_received(result.params) - end) -end - -function M:handle_chat_content(message) - if message.params then - self:handle_chat_content_received(message.params) - end - - if message.type == "state/updated" then - self:_handle_state_updated(message.content) - end -end - ----@param params table Server content notification -function M:handle_chat_content_received(params) - if not params or not params.content then - return - end - - local content = params.content - local chat_id = params.chatId - - if content.type == "text" then - -- Handle streaming text content - self:_handle_streaming_text(content.text) - elseif content.type == "progress" then - if content.state == "finished" then - self:_finalize_streaming_response() - self:_update_input_display() - elseif content.text == "Waiting for tool call approval" then - -- Handle implicit approval flow when toolCallPrepare was already received - self:render_tool_call(content, chat_id) - end - elseif content.type == "toolCallPrepare" then - self:_finalize_streaming_response() - self:_handle_tool_call_prepare(content) - -- IMPORTANT: Return immediately - do NOT display anything for toolCallPrepare - return - elseif content.type == "toolCallRun" then - self:render_tool_call(content, chat_id) - elseif content.type == "toolCallRunning" then - -- Show the accumulated tool call - self:_display_tool_call(content) - elseif content.type == "toolCalled" then - local tool_text = self:_tool_call_text(content) - - -- If this tool call reports a file change, append the basename of the - -- path to the summary shown in the chat so users can immediately see - -- which file was touched. - local details = content.details - if details and type(details) == "table" and details.type == "fileChange" then - local path = details.path - if path and path ~= "" then - local filename = vim.fn.fnamemodify(path, ":t") - if filename and filename ~= "" then - -- Avoid duplicating the filename if it is already present - if tool_text and tool_text ~= "" then - if not string.find(tool_text, filename, 1, true) then - tool_text = string.format("%s %s", tool_text, filename) - end - else - tool_text = filename - end - end - end - end - - -- Add diff to current tool call if present in toolCalled content - if self._current_tool_call and content.details then - self._current_tool_call.details = content.details - end - - -- Show the tool result in logs only - local tool_log = string.format("**Tool Result**: %s", content.name or "unknown") - local outputs_text = nil - local outputs_type = nil - if content.outputs and #content.outputs > 0 then - local pieces = {} - for _, output in ipairs(content.outputs) do - if output.type == "text" then - local txt = output.text or output.content - if txt and txt ~= "" then - table.insert(pieces, txt) - tool_log = tool_log .. "\n" .. txt - outputs_type = outputs_type or output.type - end - else - -- Even if we don't render non-text payloads directly, remember - -- their reported type so that any displayed block can still - -- use an appropriate fence language. - outputs_type = outputs_type or output.type - end - end - if #pieces > 0 then - outputs_text = table.concat(pieces, "\n") - end - end - Logger.debug(tool_log) - - -- Determine completion status icon (configurable) - local icons = Utils.get_tool_call_icons() - local status_icon = icons.success - if content.error then - status_icon = icons.error - end - - -- Ensure tool calls table exists - self._tool_calls = self._tool_calls or {} - - -- Try to find an existing tool call entry for this id - local call = self:_find_tool_call_by_id(content.id) - - if call then - -- Update details and status for an existing call - if content.details then - call.details = content.details - call.has_diff = self:_has_details_diff(call.details) - call.diff_lines = self:_build_tool_call_diff_lines(call.details) - call.details_lines = nil - call.details_line_count = 0 - - -- If this call now has a diff and doesn't yet have a label line, add it - if call.has_diff and not call.label_line and not call.expanded then - self:_insert_tool_call_diff_label_line(call) - if Utils.should_start_diff_expanded() then - self:_expand_tool_call_diff(call) - end - end - end - - -- Always refresh stored outputs/argument lines when we get a final toolCalled event - if outputs_text and outputs_text ~= "" then - call.outputs = outputs_text - call.outputs_type = outputs_type or call.outputs_type - end - call.arguments_lines = self:_build_tool_call_arguments_lines(call.arguments, call.outputs, call.outputs_type) - - call.status = status_icon - call.title = tool_text or call.title - - -- Update the header line to move the checkmark/error icon to the end - self:_update_tool_call_header_line(call) - else - -- Create a new entry for tool calls that didn't have a running phase - local details = content.details or {} - local arguments = self._current_tool_call and self._current_tool_call.arguments or "" - local outputs = outputs_text or "" - local outputs_type_value = outputs_type - local arguments_lines = self:_build_tool_call_arguments_lines(arguments, outputs, outputs_type_value) - local diff_lines = self:_build_tool_call_diff_lines(details) - local has_diff = self:_has_details_diff(details) - - call = { - id = content.id, - title = tool_text or (content.name or "Tool call"), - header_line = nil, - expanded = false, -- controls argument visibility - diff_expanded = false, -- controls diff visibility - status = status_icon, - arguments = arguments, - details = details, - outputs = outputs, - outputs_type = outputs_type_value, - has_diff = has_diff, - label_line = nil, - -- Separate storage for arguments vs diff so each can be toggled independently - arguments_lines = arguments_lines, - diff_lines = diff_lines, - details_lines = nil, - details_line_count = 0, - } - - local chat = self.containers.chat - if chat and vim.api.nvim_buf_is_valid(chat.bufnr) then - local before_line_count = vim.api.nvim_buf_line_count(chat.bufnr) - local header_text = self:_build_tool_call_header_text(call) - self:_add_message("assistant", header_text) - call.header_line = before_line_count + 1 - - if call.has_diff then - self:_insert_tool_call_diff_label_line(call) - if Utils.should_start_diff_expanded() then - self:_expand_tool_call_diff(call) - end - end - - table.insert(self._tool_calls, call) - end - end - - -- Clean up tool call state - self:_finalize_tool_call() - elseif content.type == "reasonStarted" then - self:_handle_reason_started(content) - elseif content.type == "reasonText" then - self:_handle_reason_text(content) - elseif content.type == "reasonFinished" then - self:_handle_reason_finished(content) - end -end - -function M:render_tool_call(tool_content, chat_id) - -- Handle explicit manual approval (toolCallRun with manualApproval flag) - if tool_content.type == "toolCallRun" and tool_content.manualApproval then - -- Mark as shown to prevent duplicate approval dialogs from implicit flow - if self._current_tool_call then - self._current_tool_call.approval_shown = true - end - return require("eca.approve").approve_tool_call(tool_content, function() - self.mediator:send("chat/toolCallApprove", { chatId = chat_id, toolCallId = tool_content.id }, nil) - end, function() - self.mediator:send("chat/toolCallReject", { chatId = chat_id, toolCallId = tool_content.id }, nil) - end) - end - - -- Handle implicit approval flow: progress message "Waiting for tool call approval" - -- with a previously prepared tool call (toolCallPrepare stored in _current_tool_call) - if tool_content.type == "progress" - and tool_content.text == "Waiting for tool call approval" - and self._current_tool_call - and self._current_tool_call.id - and not self._current_tool_call.approval_shown then - -- Mark as shown to avoid duplicate approval dialogs - self._current_tool_call.approval_shown = true - - -- Store the tool call id in a local variable to avoid closure issues - local tool_call_id = self._current_tool_call.id - - -- Build tool content from the prepared tool call for the approval dialog - -- Using field names expected by approve.lua - local prepared_tool_call = { - id = tool_call_id, - name = self._current_tool_call.name or "Tool call", - summary = self._current_tool_call.summary, - arguments = self._current_tool_call.arguments or "", - origin = "eca", -- default origin for implicit approval - details = self._current_tool_call.details, - } - - return require("eca.approve").approve_tool_call(prepared_tool_call, function() - self.mediator:send("chat/toolCallApprove", { chatId = chat_id, toolCallId = tool_call_id }, nil) - end, function() - self.mediator:send("chat/toolCallReject", { chatId = chat_id, toolCallId = tool_call_id }, nil) - end) - end -end - ----@param text string -function M:_handle_streaming_text(text) - -- Only check for empty text - if not text or text == "" then - Logger.debug("Ignoring empty text response") - return - end - - Logger.debug("Received text chunk: '" .. text:sub(1, 50) .. (text:len() > 50 and "..." or "") .. "'") - - if vim.trim(text) == vim.trim(self._last_user_message) then - Logger.debug("Ignoring duplicate user message in response") - return - end - - if not self._is_streaming then - Logger.debug("Starting streaming response") - -- Start streaming with the stream queue - self._is_streaming = true - self._current_response_buffer = "" - self._stream_visible_buffer = "" - if self._stream_queue then - self._stream_queue:clear() - end - - -- Determine insertion point before adding placeholder (works even with empty header) - local chat = self.containers.chat - local start_line = 1 - if chat and vim.api.nvim_buf_is_valid(chat.bufnr) then - start_line = vim.api.nvim_buf_line_count(chat.bufnr) + 1 - end - - -- Add assistant placeholder and track its start line - self:_add_message("assistant", "") - - -- Track placeholder with an extmark independent of header content - self.extmarks = self.extmarks or {} - if not self.extmarks.assistant then - self.extmarks.assistant = { _ns = vim.api.nvim_create_namespace('extmarks_assistant') } - end - if chat and vim.api.nvim_buf_is_valid(chat.bufnr) then - self.extmarks.assistant._id = vim.api.nvim_buf_set_extmark( - chat.bufnr, - self.extmarks.assistant._ns, - start_line - 1, - 0, - { id = self.extmarks.assistant._id } - ) - end - end - - -- Accumulate the full response for finalization and history - self._current_response_buffer = (self._current_response_buffer or "") .. text - -- Enqueue new text to be rendered gradually - if self._stream_queue then - self._stream_queue:enqueue(text) - end - - Logger.debug("DEBUG: Buffer now has " .. - #self._current_response_buffer .. - " chars (queue size: " .. (self._stream_queue and self._stream_queue:size() or 0) .. ")") -end - ----@param content string -function M:_update_streaming_message(content) - local chat = self.containers.chat - if not chat then - Logger.debug("DEBUG: Cannot update - no chat") - return - end - - Logger.debug("DEBUG: Updating streaming message with " .. #content .. " chars") - - if not vim.api.nvim_buf_is_valid(chat.bufnr) then - Logger.notify("Invalid buffer, cannot update", vim.log.levels.ERROR) - return - end - - -- Capture the current chat view so we only auto-scroll if the user was - -- already at (or very near) the bottom, and hasn't moved since. - local anchor = self:_capture_chat_view_state() - - -- Simple and direct buffer update that only rewrites the assistant's - -- own streaming region. This avoids clobbering content that may have - -- been appended after it (e.g. tool calls or reasoning blocks). - local success, err = pcall(function() - -- Make buffer modifiable - vim.api.nvim_set_option_value("modifiable", true, { buf = chat.bufnr }) - - -- Concat content with header - content = self._headers.assistant .. content - - -- Get current lines - local lines = vim.api.nvim_buf_get_lines(chat.bufnr, 0, -1, false) - local content_lines = Utils.split_lines(content) - - -- Resolve assistant start line using extmark if available - local start_line = 0 - if self.extmarks and self.extmarks.assistant and self.extmarks.assistant._id then - local pos = vim.api.nvim_buf_get_extmark_by_id(chat.bufnr, self.extmarks.assistant._ns, self.extmarks.assistant - ._id, {}) - if pos and pos[1] then - start_line = pos[1] + 1 - end - end - - Logger.debug("DEBUG: Start Line: " .. tostring(start_line)) - Logger.debug("DEBUG: Content lines: " .. #content_lines) - - -- Replace assistant content directly - local new_lines = {} - - -- Keep everything before assistant response - for i = 1, start_line - 1 do - table.insert(new_lines, lines[i] or "") - end - - -- Add new content - for _, line in ipairs(content_lines) do - table.insert(new_lines, line) - end - - -- Add empty line after content - table.insert(new_lines, "") - - -- Set all lines at once - vim.api.nvim_buf_set_lines(chat.bufnr, 0, -1, false, new_lines) - - -- Re-anchor the assistant extmark at the start line (for subsequent updates) - self.extmarks = self.extmarks or {} - if not self.extmarks.assistant then - self.extmarks.assistant = { _ns = vim.api.nvim_create_namespace('extmarks_assistant') } - end - self.extmarks.assistant._id = vim.api.nvim_buf_set_extmark( - chat.bufnr, - self.extmarks.assistant._ns, - start_line - 1, - 0, - { id = self.extmarks.assistant._id } - ) - - Logger.debug("DEBUG: Buffer updated successfully with " .. #new_lines .. " total lines") - end) - - if not success then - Logger.notify("Error updating buffer: " .. tostring(err), vim.log.levels.ERROR) - else - -- Reapply highlights for existing tool calls and reasoning blocks, - -- since full-buffer updates can drop extmark-based styling. - self:_reapply_tool_call_highlights() - -- Auto-scroll only if the user was already at the bottom. - self:_scroll_to_bottom({ anchor = anchor }) - end -end - ----@param role string ----@param content string -function M:_add_message(role, content) - local chat = self.containers.chat - if not chat then - return - end - - -- Capture the current chat view before appending. We'll only auto-scroll if: - -- - this is a user message (force scroll), or - -- - the user was already at the bottom and hasn't moved since. - local anchor = self:_capture_chat_view_state() - local force_scroll = role == "user" - - self:_safe_buffer_update(chat.bufnr, function() - local lines = vim.api.nvim_buf_get_lines(chat.bufnr, 0, -1, false) - local header = "" - - if role == "user" then - header = self._headers.user - elseif role == "assistant" then - header = self._headers.assistant - end - - -- Concat header and content - content = header .. content - - -- Add content with better markdown formatting - local content_lines = Utils.split_lines(content) - - -- Check if content looks like code (starts with common programming patterns) - local is_code = content:match("^%s*function") - or content:match("^%s*class") - or content:match("^%s*def ") - or content:match("^%s*import") - or content:match("^%s*#include") - or content:match("^%s*<%?") - or content:match("^%s*= math.max(1, line_count - threshold), - -- Keep a view-based "at bottom" as well, mainly for debugging/telemetry. - at_bottom = bottomline >= math.max(1, line_count - threshold), - } - end) -end - ----Auto-scroll to bottom of the chat. ---- ----By default, we only scroll if the user was already at (or very near) the bottom. ----Pass `{ force = true }` to always scroll (e.g. after sending a user message). ----@param opts? { force?: boolean, anchor?: table } -function M:_scroll_to_bottom(opts) - opts = opts or {} - - local chat = self.containers.chat - if not chat or not vim.api.nvim_win_is_valid(chat.winid) or not vim.api.nvim_buf_is_valid(chat.bufnr) then - return - end - - local anchor = opts.anchor - -- Scroll if: - -- - explicitly forced (e.g. user just sent a message), OR - -- - the chat window is NOT focused (user isn't interacting with it), OR - -- - the chat window is focused AND the user is already at the bottom. - local should_scroll = opts.force == true - or (anchor == nil) - or (anchor and (not anchor.is_current or anchor.cursor_at_bottom)) - - if not should_scroll then - return - end - - -- Defer to the next scheduler tick so any buffer updates have been applied. - vim.schedule(function() - local chat2 = self.containers.chat - if not chat2 or not vim.api.nvim_win_is_valid(chat2.winid) or not vim.api.nvim_buf_is_valid(chat2.bufnr) then - return - end - - -- If the chat window was focused at capture time, only scroll if the user - -- hasn't moved the chat view since we captured `anchor`. - if opts.force ~= true and anchor and anchor.is_current and anchor.view then - local unchanged = vim.api.nvim_win_call(chat2.winid, function() - local view = vim.fn.winsaveview() - return view.topline == anchor.view.topline and view.lnum == anchor.view.lnum - end) - if not unchanged then - return - end - end - - local current_line_count = vim.api.nvim_buf_line_count(chat2.bufnr) - if current_line_count < 1 then - current_line_count = 1 - end - - -- Set cursor to last line and scroll to bottom - vim.api.nvim_win_set_cursor(chat2.winid, { current_line_count, 0 }) - vim.api.nvim_win_call(chat2.winid, function() - vim.cmd("normal! zb") -- scroll so cursor line is at bottom of window - end) - end) -end - ----@param bufnr integer ----@param callback function -function M:_safe_buffer_update(bufnr, callback) - -- if not vim.api.nvim_buf_s_valid(bufnr) then - -- return - -- end - -- - -- -- Simple but effective approach: disable highlighting during updates - -- local original_eventignore = vim.o.eventignore - -- local original_syntax = vim.api.nvim_get_option_value("syntax", { buf = bufnr }) - -- local original_modifiable = vim.api.nvim_get_option_value("modifiable", { buf = bufnr }) - -- - -- -- Temporarily disable events and highlighting to prevent treesitter issues - -- vim.o.eventignore = "all" - -- pcall(vim.api.nvim_set_option_value, "syntax", "off", { buf = bufnr }) - -- pcall(vim.api.nvim_set_option_value, "modifiable", true, { buf = bufnr }) - -- - -- -- Disable treesitter highlighting for this buffer temporarily - -- pcall(function() - -- if vim.treesitter.highlighter.active[bufnr] then - -- Logger.debug("Temporarily disabling treesitter for buffer " .. bufnr) - -- vim.treesitter.highlighter.active[bufnr]:destroy() - -- vim.treesitter.highlighter.active[bufnr] = nil - -- end - -- end) - -- - -- -- Execute the buffer update with maximum protection - local success, err = pcall(callback) - if not success then - Logger.notify("Buffer update failed: " .. tostring(err), vim.log.levels.ERROR) - end - - -- -- Restore original state immediately (no delay for critical settings) - -- vim.o.eventignore = original_eventignore - -- pcall(vim.api.nvim_set_option_value, "modifiable", original_modifiable, { buf = bufnr }) - -- - -- -- Re-enable highlighting with a delay to prevent conflicts - -- vim.defer_fn(function() - -- if vim.api.nvim_buf_is_valid(bufnr) then - -- -- Restore syntax highlighting - -- if original_syntax and original_syntax ~= "off" then - -- pcall(vim.api.nvim_set_option_value, "syntax", original_syntax, { buf = bufnr }) - -- end - -- - -- -- Re-initialize treesitter highlighting carefully - -- pcall(function() - -- local ok, parser = pcall(vim.treesitter.get_parser, bufnr) - -- if ok and parser then - -- -- Only create highlighter if one doesn't exist and buffer is still valid - -- if not vim.treesitter.highlighter.active[bufnr] and vim.api.nvim_buf_is_valid(bufnr) then - -- Logger.debug("Re-enabling treesitter for buffer " .. bufnr) - -- vim.treesitter.highlighter.new(parser, {}) - -- end - -- else - -- Logger.debug("No treesitter parser available for buffer " .. bufnr) - -- end - -- end) - -- end - -- end, 200) -- Longer delay to ensure stability -end - --- ===== Tool call handling methods ===== - -function M:_handle_tool_call_prepare(content) - if not self._is_tool_call_streaming then - self._is_tool_call_streaming = true - self._current_tool_call = { - id = content.id, - name = "", - summary = "", - arguments = "", - details = {}, - outputs = "", - approval_shown = false, - } - end - - -- Accumulate tool call data - if content.id then - self._current_tool_call.id = content.id - end - - if content.name then - self._current_tool_call.name = content.name - end - - if content.summary then - self._current_tool_call.summary = content.summary - end - - if content.argumentsText then - self._current_tool_call.arguments = (self._current_tool_call.arguments or "") .. content.argumentsText - end - - if content.details then - self._current_tool_call.details = content.details - end -end - ----Get the best display text for a tool call based on available data. ----Prefers the current content's summary, then the stored summary, then name fields, ----and finally falls back to a generic label if none are available. ----@param content table Tool call content from the server, possibly containing summary and name. ----@return string label The chosen text to display for the tool call. -function M:_tool_call_text(content) - if content.summary and content.summary ~= "" then - return content.summary - end - - if self._current_tool_call and self._current_tool_call.summary and self._current_tool_call.summary ~= "" then - return self._current_tool_call.summary - end - - if content.name and content.name ~= "" then - return content.name - end - - if self._current_tool_call and self._current_tool_call.name and self._current_tool_call.name ~= "" then - return self._current_tool_call.name - end - - return "Tool call" -end - ---- Displays the current streaming tool call in the chat container. ---- Uses the accumulated tool call state and the provided content ---- to build a formatted log entry (including arguments and diff, if present) ---- and appends it to the chat buffer. ----@param content table Tool call update payload (e.g. id, name, summary, argumentsText, details). ----@return nil -function M:_display_tool_call(content) - if not self._is_tool_call_streaming or not self._current_tool_call then - return nil - end - - local chat = self.containers.chat - if not chat or not vim.api.nvim_buf_is_valid(chat.bufnr) then - return nil - end - - local tool_name = self:_tool_call_text(content) - local tool_log = string.format("**Tool Call**: %s", tool_name or "unknown") - - if self._current_tool_call.arguments and self._current_tool_call.arguments ~= "" then - tool_log = tool_log .. "\n```json\n" .. self._current_tool_call.arguments .. "\n```" - end - - if self._current_tool_call.details and self._current_tool_call.details.diff then - tool_log = tool_log .. "\n\n**Diff**:\n```diff\n" .. self._current_tool_call.details.diff .. "\n```" - end - - Logger.debug(tool_log) - - -- Ensure tool calls table exists - self._tool_calls = self._tool_calls or {} - - -- Try to find an existing entry for this tool call - local existing_call = nil - if self._current_tool_call.id then - existing_call = self:_find_tool_call_by_id(self._current_tool_call.id) - end - - -- Build detail lines from current state (arguments and diff are controlled separately) - local arguments_lines = self:_build_tool_call_arguments_lines( - self._current_tool_call.arguments, - self._current_tool_call.outputs, - self._current_tool_call.outputs_type - ) - local diff_lines = self:_build_tool_call_diff_lines(self._current_tool_call.details) - local has_diff = self:_has_details_diff(self._current_tool_call.details) - - if existing_call then - -- Update details for existing call (do not add another header) - existing_call.arguments = self._current_tool_call.arguments or existing_call.arguments - existing_call.details = self._current_tool_call.details or existing_call.details - existing_call.has_diff = has_diff - existing_call.arguments_lines = arguments_lines - existing_call.diff_lines = diff_lines - existing_call.details_lines = nil - existing_call.details_line_count = 0 - - -- Reset diff visibility when we get new diff content - if not has_diff then - existing_call.diff_expanded = false - end - - -- If this call now has a diff and doesn't yet have a label line, add it - if has_diff and not existing_call.label_line and not existing_call.expanded then - self:_insert_tool_call_diff_label_line(existing_call) - end - - return - end - - -- Create a new tool call entry and header (collapsed by default) - local header_title = tool_name or "Tool call" - local call = { - id = self._current_tool_call.id or content.id, - title = header_title, - header_line = nil, - expanded = false, -- controls argument visibility - diff_expanded = false, -- controls diff visibility - status = nil, - arguments = self._current_tool_call.arguments or "", - details = self._current_tool_call.details or {}, - outputs = self._current_tool_call.outputs or "", - has_diff = has_diff, - label_line = nil, - -- Store arguments and diff lines separately so they can be toggled independently - arguments_lines = arguments_lines, - diff_lines = diff_lines, - details_lines = nil, - details_line_count = 0, - } - - local before_line_count = vim.api.nvim_buf_line_count(chat.bufnr) - local header_text = self:_build_tool_call_header_text(call) - self:_add_message("assistant", header_text) - call.header_line = before_line_count + 1 - - -- Apply header highlight (tool call vs reasoning) - self:_highlight_tool_call_header(call) - - if call.has_diff then - self:_insert_tool_call_diff_label_line(call) - if Utils.should_start_diff_expanded() then - self:_expand_tool_call_diff(call) - end - end - - table.insert(self._tool_calls, call) -end - ----Finalize the currently streaming tool call. ---- ----Clears internal streaming state so subsequent events are not appended to the ----previous tool call. -function M:_finalize_tool_call() - self._current_tool_call = nil - self._is_tool_call_streaming = false -end - --- ===== Reasoning ("Thinking") handling ===== - ----Handle the start of a streamed reasoning ("Thinking") block. ---- ----Creates a pseudo tool-call entry stored in `self._reasons` and `self._tool_calls`, ----inserts a header line into the chat buffer, and applies header highlighting. ----@param content table Event payload containing at least `id` (string). -function M:_handle_reason_started(content) - local id = content.id - if not id then - return - end - - local chat = self.containers.chat - if not chat or not vim.api.nvim_buf_is_valid(chat.bufnr) then - return - end - - self._reasons = self._reasons or {} - self._tool_calls = self._tool_calls or {} - - -- If a new reasoning starts while another one is still "running", - -- mark the previous one as finished so only one active "Thinking" - -- block is shown at a time. - local labels = Utils.get_reasoning_labels() - local running_label = labels.running - local finished_label = labels.finished - - for existing_id, existing_call in pairs(self._reasons) do - if existing_id ~= id - and existing_call - and existing_call.status == nil - -- Only auto-convert entries that are *currently* showing - -- the running label, so we don't clobber completed - -- entries like "Thought 1.23 s" when a new reasoning - -- block starts later. - and existing_call.title == running_label then - -- For reasoning entries we don't show status icons; instead we just - -- update the label from the running label to the finished label. - existing_call.title = finished_label - existing_call.status = nil - self:_update_tool_call_header_line(existing_call) - end - end - - -- Avoid creating duplicates for the same reasoning id - if self._reasons[id] then - return - end - - -- Whether "Thinking" blocks should start expanded by default - -- Use the merged chat config so both legacy `chat.reasoning` and - -- modern `windows.chat.reasoning` can control this behavior. - local chat_cfg = Utils.get_chat_config() - local reasoning_cfg = chat_cfg.reasoning or {} - local expand = reasoning_cfg.expanded == true - - local call = { - id = id, - title = running_label, -- summary label while reasoning is running - header_line = nil, - expanded = expand, -- controls visibility of reasoning text - diff_expanded = false, -- unused for reasoning - status = nil, -- unused for reasoning headers; no status icons - arguments = "", -- we reuse arguments as the accumulated reasoning text - details = {}, - has_diff = false, - label_line = nil, - arguments_lines = {}, - diff_lines = {}, - details_lines = nil, - details_line_count = 0, - is_reason = true, - } - - local before_line_count = vim.api.nvim_buf_line_count(chat.bufnr) - local header_text = self:_build_tool_call_header_text(call) - self:_add_message("assistant", header_text) - call.header_line = before_line_count + 1 - - -- Apply header highlight (reasoning entries use Comment) - self:_highlight_tool_call_header(call) - - -- Track this reasoning both in a dedicated map and in the generic tool_calls - self._reasons[id] = call - table.insert(self._tool_calls, call) -end - ----Handle streamed reasoning text for a previously started reasoning block. ---- ----Appends `content.text` to the stored reasoning body. If the block is currently ----expanded in the chat buffer, updates the in-buffer region in-place and shifts ----subsequent tool-call line markers accordingly. ----@param content table Event payload containing `id` (string) and `text` (string). -function M:_handle_reason_text(content) - local id = content.id - if not id or not content.text then - return - end - - self._reasons = self._reasons or {} - local call = self._reasons[id] - if not call then - -- If we somehow receive text without a start, create the entry lazily - self:_handle_reason_started({ id = id }) - call = self._reasons[id] - if not call then - return - end - end - - local chat = self.containers.chat - if not chat or not vim.api.nvim_buf_is_valid(chat.bufnr) then - return - end - - -- Accumulate raw reasoning text - call.arguments = (call.arguments or "") .. content.text - - -- Build plain text block for the reasoning body (no markdown quote prefix). - -- We keep the first inserted line as the first line of reasoning text rather - -- than a blank spacer so that navigation from the header lands on the actual content. - call.arguments_lines = {} - - local lines = Utils.split_lines(call.arguments or "") - for _, line in ipairs(lines) do - line = line ~= "" and line or " " - table.insert(call.arguments_lines, line) - end - - -- If the reasoning block is expanded, update its region in the buffer in-place - if call.expanded then - local prev_count = call._last_arguments_count or 0 - local new_count = #call.arguments_lines - - self:_safe_buffer_update(chat.bufnr, function() - if prev_count == 0 and new_count > 0 then - -- Insert for the first time immediately after the header - vim.api.nvim_buf_set_lines(chat.bufnr, call.header_line, call.header_line, false, call.arguments_lines) - -- Shift subsequent tool calls down by the inserted line count - self:_adjust_tool_call_lines(call, new_count) - else - -- Replace existing block; adjust subsequent calls only if size changed - vim.api.nvim_buf_set_lines(chat.bufnr, call.header_line, call.header_line + prev_count, false, - call.arguments_lines) - if new_count ~= prev_count then - self:_adjust_tool_call_lines(call, new_count - prev_count) - end - end - end) - - call._last_arguments_count = new_count - end - - -- Ensure the header arrow reflects whether there is body content to show. - -- This will add the expand/collapse icon once we have streamed some - -- reasoning text, and it will be omitted while the body is still empty. - self:_update_tool_call_header_line(call) -end - ----Finalize a reasoning ("Thinking") block. ---- ----Updates the header label to the finished label (optionally including the ----elapsed time reported by the model) and refreshes the header line in the chat. ----@param content table Event payload containing `id` (string) and optional `totalTimeMs`. -function M:_handle_reason_finished(content) - local id = content.id - if not id then - return - end - - self._reasons = self._reasons or {} - local call = self._reasons[id] - if not call then - return - end - - local labels = Utils.get_reasoning_labels() - local finished_label = labels.finished - - -- When reasoning is finished, update the label from running to a - -- finished label, appending the total time in seconds when available. - local total_ms = tonumber(content.totalTimeMs) - if total_ms and total_ms > 0 then - local seconds = total_ms / 1000 - call.title = string.format("%s %.2f s", finished_label, seconds) - else - call.title = finished_label - end - - call.status = nil - self:_update_tool_call_header_line(call) -end - ----Find an existing tool-call/reasoning entry by id. ----@param id string|nil Tool call/reasoning identifier. ----@return table|nil call The matching call entry from `self._tool_calls`, if any. -function M:_find_tool_call_by_id(id) - if not self._tool_calls or not id then - return nil - end - - for _, call in ipairs(self._tool_calls) do - if call.id == id then - return call - end - end - - return nil -end - ----Find the tool-call/reasoning entry that owns a given 1-based buffer line. ---- ----This checks the header line as well as any expanded argument/reasoning body and ----optional diff sections. ----@param line integer 1-based line number in the chat buffer. ----@return table|nil call The call entry covering `line`, if any. -function M:_find_tool_call_for_line(line) - if not self._tool_calls then - return nil - end - - for _, call in ipairs(self._tool_calls) do - if call.header_line then - local start_line = call.header_line - local end_line = start_line - - -- Include argument block when expanded - local arg_count = call.arguments_lines and #call.arguments_lines or 0 - if call.expanded and arg_count > 0 then - end_line = end_line + arg_count - end - - -- Include label line and optional diff block when present - if call.has_diff and call.label_line then - local label_end = call.label_line - local diff_count = call.diff_lines and #call.diff_lines or 0 - if call.diff_expanded and diff_count > 0 then - label_end = label_end + diff_count - end - if label_end > end_line then - end_line = label_end - end - end - - if line >= start_line and line <= end_line then - return call - end - end - end - - return nil -end - ----Build the header text displayed for a tool call/reasoning entry. ---- ----For regular tool calls this includes an expand/collapse arrow, a title, and a ----status icon. For reasoning entries (`call.is_reason`), this may omit the arrow ----until the body has content, and never shows a status icon. ----@param call table Tool-call/reasoning entry. ----@return string header_text -function M:_build_tool_call_header_text(call) - local icons = Utils.get_tool_call_icons() - - -- Reasoning ("Thinking") entries do not show status icons; they only - -- display a toggle arrow (when there is body content to show) and a - -- text label ("Thinking..." / "Thought"). - if call.is_reason then - local title = call.title or "Thinking..." - if type(title) ~= "string" then - title = tostring(title) - end - - -- Only show the expand/collapse arrow once we actually have some - -- reasoning text to display. This avoids showing a useless toggle - -- while the model is still preparing its thoughts. - local has_body = false - if call.arguments and type(call.arguments) == "string" and call.arguments:match("%S") then - has_body = true - elseif call.arguments_lines and #call.arguments_lines > 0 then - has_body = true - end - - if not has_body then - return title - end - - local arrow = call.expanded and icons.expanded or icons.collapsed - if type(arrow) ~= "string" then - arrow = tostring(arrow) - end - - return table.concat({ arrow, title }, " ") - end - - -- Regular tool calls always show an expand/collapse arrow. The arrow - -- controls the visibility of the arguments block; any diff is toggled - -- separately via the "view diff" label. - local arrow = call.expanded and icons.expanded or icons.collapsed - - -- Normalize all pieces to strings to avoid issues when configuration or - -- status fields accidentally contain non-string values (e.g. userdata). - if type(arrow) ~= "string" then - arrow = tostring(arrow) - end - - local title = call.title or "Tool call" - local status = call.status or icons.running - - if type(title) ~= "string" then - title = tostring(title) - end - if type(status) ~= "string" then - status = tostring(status) - end - - local parts = { arrow, title, status } - - return table.concat(parts, " ") -end - ----Build the argument/output detail lines for a tool call. ---- ----Arguments and outputs are rendered as fenced code blocks. The output fence ----language is derived from `outputs_type` when available. ----@param arguments string|nil JSON-encoded arguments. ----@param outputs string|nil Tool output (often JSON, sometimes plain text). ----@param outputs_type string|nil Reported output type/language (e.g. "json", "text"). ----@return string[] lines Buffer lines to insert under the tool call header. -function M:_build_tool_call_arguments_lines(arguments, outputs, outputs_type) - local lines = {} - local has_content = false - - if arguments and arguments ~= "" then - table.insert(lines, "Arguments:") - table.insert(lines, "```json") - for _, line in ipairs(Utils.split_lines(arguments)) do - table.insert(lines, line) - end - table.insert(lines, "```") - table.insert(lines, "") - has_content = true - end - - if outputs and outputs ~= "" then - if not has_content then - -- Add spacer only if this is the first section - table.insert(lines, "") - end - - table.insert(lines, "Output:") - - -- Choose fence language based on reported output type. When the tool - -- says the output type is "text", render it as a plain text fence - -- instead of JSON. For unknown types we keep using "json" for - -- backwards compatibility. - local lang = "json" - if type(outputs_type) == "string" and outputs_type ~= "" then - if outputs_type == "text" then - lang = "text" - else - lang = outputs_type - end - end - - table.insert(lines, "```" .. lang) - for _, line in ipairs(Utils.split_lines(outputs)) do - table.insert(lines, line) - end - table.insert(lines, "```") - table.insert(lines, "") - end - - -- Remove any trailing blank lines; we keep internal spacing (for example - -- between the Arguments and Output sections) intact. - while #lines > 0 and lines[#lines]:match("^%s*$") do - table.remove(lines) - end - - return lines -end - ----Build the diff detail lines for a tool call. ---- ----If `details.diff` exists, returns a `diff` fenced code block; otherwise returns ----an empty list. ----@param details table|nil Tool-call details table (may include `diff`). ----@return string[] lines -function M:_build_tool_call_diff_lines(details) - local lines = {} - - local diff = details and details.diff or nil - if diff and diff ~= "" then - -- Start the diff block with the fenced header (no leading newline) - table.insert(lines, "```diff") - for _, line in ipairs(Utils.split_lines(diff)) do - table.insert(lines, line) - end - table.insert(lines, "```") - end - - -- Remove any trailing blank lines just in case - while #lines > 0 and lines[#lines]:match("^%s*$") do - table.remove(lines) - end - - return lines -end - ----Build combined tool-call detail lines (arguments/output + diff). ---- ----NOTE: Callers that need independent control over arguments vs diff expansion ----should prefer `_build_tool_call_arguments_lines` and `_build_tool_call_diff_lines`. ----@param arguments string|nil ----@param details table|nil ----@param outputs string|nil ----@param outputs_type string|nil ----@return string[] lines -function M:_build_tool_call_details_lines(arguments, details, outputs, outputs_type) - local lines = {} - - local arg_lines = self:_build_tool_call_arguments_lines(arguments, outputs, outputs_type) - for _, line in ipairs(arg_lines) do - table.insert(lines, line) - end - - local diff_lines = self:_build_tool_call_diff_lines(details) - for _, line in ipairs(diff_lines) do - table.insert(lines, line) - end - - return lines -end - ----Check whether a tool-call details table contains a non-empty diff. ----@param details table|nil ----@return boolean has_diff -function M:_has_details_diff(details) - return details and type(details) == "table" and details.diff and details.diff ~= "" -end - ----Build the label text shown below a tool call header when a diff is available. ---- ----The label varies based on whether the diff block is currently expanded. ----@param call table Tool-call entry. ----@return string label_text -function M:_build_tool_call_diff_label_text(call) - local labels = Utils.get_tool_call_diff_labels() - - -- Use different texts depending on diff expanded/collapsed state - if call and call.diff_expanded then - return labels.expanded - end - - return labels.collapsed -end - ----Choose a sidebar highlight group for a given UI element. ----@param kind "tool_header"|"reason_header"|"diff_label"|string ----@return string hl_group -local function _eca_sidebar_hl(kind) - if kind == "tool_header" then - return "EcaToolCall" - elseif kind == "reason_header" then - return "EcaLabel" - elseif kind == "diff_label" then - return "EcaHyperlink" - end - - return "Normal" -end - ----Highlight a tool call header line (summary / reasoning label). ---- --- * Regular tool calls use the EcaToolCall highlight group. --- * Reasoning entries ("Thinking..." / "Thought ...") use the EcaLabel --- highlight group, which links to Comment in highlights.lua and adapts --- to light/dark themes; selection is handled via _eca_sidebar_hl(). ----@param call table Tool-call/reasoning entry with `header_line` populated. -function M:_highlight_tool_call_header(call) - local chat = self.containers.chat - if not chat or not vim.api.nvim_buf_is_valid(chat.bufnr) then - return - end - - if not call or not call.header_line then - return - end - - -- Guard against stale header_line values that point past the end of the - -- buffer (for example after streaming updates that rewrote the chat). - local line_count = vim.api.nvim_buf_line_count(chat.bufnr) - if call.header_line < 1 or call.header_line > line_count then - return - end - - self.extmarks = self.extmarks or {} - if not self.extmarks.tool_header then - self.extmarks.tool_header = { - _ns = vim.api.nvim_create_namespace("extmarks_tool_header"), - _id = {}, - } - end - - local ns = self.extmarks.tool_header._ns - local key = call.id or tostring(call.header_line) - - -- Clear any previous highlight for this call - if self.extmarks.tool_header._id[key] then - pcall(vim.api.nvim_buf_del_extmark, chat.bufnr, ns, self.extmarks.tool_header._id[key]) - end - - local line = vim.api.nvim_buf_get_lines(chat.bufnr, call.header_line - 1, call.header_line, false)[1] or "" - local end_col = #line - - local hl_group - if call.is_reason then - hl_group = _eca_sidebar_hl("reason_header") - else - hl_group = _eca_sidebar_hl("tool_header") - end - - -- Add an extmark that highlights the entire header line - self.extmarks.tool_header._id[key] = vim.api.nvim_buf_set_extmark(chat.bufnr, ns, call.header_line - 1, 0, { - hl_group = hl_group, - end_col = end_col, - priority = 180, - }) -end - ----Highlight the "view diff" label line for a tool call. ---- ----Uses an extmark so the highlight persists across edits; highlight priority is ----set high to win over Treesitter/markdown styling. ----@param call table Tool-call entry with `label_line` populated. -function M:_highlight_tool_call_diff_label_line(call) - local chat = self.containers.chat - if not chat or not vim.api.nvim_buf_is_valid(chat.bufnr) then - return - end - - if not call or not call.label_line then - return - end - - -- Guard against stale label_line values that point past the end of the - -- buffer (for example after streaming updates that rewrote the chat). - local line_count = vim.api.nvim_buf_line_count(chat.bufnr) - if call.label_line < 1 or call.label_line > line_count then - return - end - - self.extmarks = self.extmarks or {} - - -- Naming convention: tool-call-related extmarks are grouped under `tool_*`. - -- (We keep other sidebar extmarks like `assistant`, `prefix`, etc. as-is.) - if self.extmarks.diff_label and not self.extmarks.tool_diff_label then - -- Backwards compatible migration for hot-reloads. - self.extmarks.tool_diff_label = self.extmarks.diff_label - self.extmarks.diff_label = nil - end - - if not self.extmarks.tool_diff_label then - self.extmarks.tool_diff_label = { - _ns = vim.api.nvim_create_namespace("extmarks_tool_diff_label"), - _id = {}, - } - end - - local ns = self.extmarks.tool_diff_label._ns - local key = call.id or tostring(call.header_line) - - -- Clear any previous highlight for this call - if self.extmarks.tool_diff_label._id[key] then - pcall(vim.api.nvim_buf_del_extmark, chat.bufnr, ns, self.extmarks.tool_diff_label._id[key]) - end - - -- Determine how much of the line to highlight (the whole label text) - local line = vim.api.nvim_buf_get_lines(chat.bufnr, call.label_line - 1, call.label_line, false)[1] or "" - local end_col = #line - - -- Add an extmark that highlights the label text using a theme-aware group - -- Use a high priority so it wins over Treesitter/markdown highlights. - self.extmarks.tool_diff_label._id[key] = vim.api.nvim_buf_set_extmark(chat.bufnr, ns, call.label_line - 1, 0, { - hl_group = _eca_sidebar_hl("diff_label"), - end_col = end_col, - priority = 200, - }) -end - ----Reapply tool-call/reasoning header and diff-label highlights. ---- ----Full-buffer updates (like streaming assistant responses) can drop extmark-based ----highlighting. This helper re-creates the extmarks for all tracked entries. -function M:_reapply_tool_call_highlights() - if not self._tool_calls or vim.tbl_isempty(self._tool_calls) then - return - end - - local chat = self.containers.chat - if not chat or not vim.api.nvim_buf_is_valid(chat.bufnr) then - return - end - - for _, call in ipairs(self._tool_calls) do - if call.header_line then - self:_highlight_tool_call_header(call) - end - - if call.has_diff and call.label_line then - self:_highlight_tool_call_diff_label_line(call) - end - end -end - ----Update the existing "view diff" label line for a tool call. ---- ----This updates the label text to reflect the current expanded/collapsed state of ----the diff block and re-applies hyperlink-style highlighting. ----@param call table Tool-call entry with `label_line` populated. -function M:_update_tool_call_diff_label_line(call) - local chat = self.containers.chat - if not chat or not vim.api.nvim_buf_is_valid(chat.bufnr) then - return - end - - if not call or not call.label_line then - return - end - - local label_text = self:_build_tool_call_diff_label_text(call) - - self:_safe_buffer_update(chat.bufnr, function() - vim.api.nvim_buf_set_lines(chat.bufnr, call.label_line - 1, call.label_line, false, { label_text }) - end) - - -- Ensure the label is highlighted after updating its text - self:_highlight_tool_call_diff_label_line(call) -end - ----Insert the "view diff" label line directly below the tool call header. ---- ----Also records `call.label_line`, highlights the label, and shifts subsequent ----tool-call line markers down. ----@param call table Tool-call entry. Requires `header_line` and `has_diff`. -function M:_insert_tool_call_diff_label_line(call) - local chat = self.containers.chat - if not chat or not vim.api.nvim_buf_is_valid(chat.bufnr) then - return - end - - if not call or not call.header_line or call.label_line or not call.has_diff then - return - end - - local label_text = self:_build_tool_call_diff_label_text(call) - - self:_safe_buffer_update(chat.bufnr, function() - -- Insert label immediately after the header line - vim.api.nvim_buf_set_lines(chat.bufnr, call.header_line, call.header_line, false, { label_text }) - end) - - -- Track the label line (1-based) - call.label_line = call.header_line + 1 - - -- Ensure the label is highlighted when first inserted - self:_highlight_tool_call_diff_label_line(call) - - -- Shift subsequent tool call headers/labels down by one line - self:_adjust_tool_call_lines(call, 1) -end - ----Update the rendered header line for a tool call/reasoning entry. ---- ----Rebuilds the header text (arrow/title/status) and re-applies header highlighting. ----@param call table Tool-call/reasoning entry with `header_line` populated. -function M:_update_tool_call_header_line(call) - local chat = self.containers.chat - if not chat or not vim.api.nvim_buf_is_valid(chat.bufnr) or not call.header_line then - return - end - - local header_text = self:_build_tool_call_header_text(call) - - self:_safe_buffer_update(chat.bufnr, function() - vim.api.nvim_buf_set_lines(chat.bufnr, call.header_line - 1, call.header_line, false, { header_text }) - end) - - -- Re-apply header highlight after updating its text/arrow/status - self:_highlight_tool_call_header(call) -end - ----Adjust `header_line`/`label_line` positions for tool calls after an insertion/removal. ---- ----Whenever a tool call expands/collapses, the buffer gains or loses lines. This ----helper shifts the stored line markers for subsequent entries so cursor ----navigation and toggle behavior remain correct. ----@param changed_call table The call whose region changed. ----@param delta integer Number of lines inserted (positive) or removed (negative). -function M:_adjust_tool_call_lines(changed_call, delta) - if not self._tool_calls or delta == 0 then - return - end - - for _, call in ipairs(self._tool_calls) do - if call ~= changed_call and call.header_line and changed_call.header_line and call.header_line > changed_call.header_line then - call.header_line = call.header_line + delta - end - - if call ~= changed_call and call.label_line and changed_call.header_line and call.label_line > changed_call.header_line then - call.label_line = call.label_line + delta - end - end -end - ----Expand a tool call/reasoning entry in the chat buffer. ---- ----For tool calls this inserts the formatted arguments/output section under the ----header. For reasoning entries it inserts the current reasoning body without ----code fences. In both cases, subsequent tool-call line markers are shifted. ----@param call table Tool-call/reasoning entry. -function M:_expand_tool_call(call) - local chat = self.containers.chat - if not chat or not vim.api.nvim_buf_is_valid(chat.bufnr) then - return - end - - if call.expanded then - return - end - - -- Save cursor position before expansion (if configured) - local saved_cursor = nil - local preserve_cursor = Utils.should_preserve_cursor() - if preserve_cursor and chat.winid and vim.api.nvim_win_is_valid(chat.winid) then - saved_cursor = vim.api.nvim_win_get_cursor(chat.winid) - end - - -- Reasoning ("Thinking") entries behave slightly differently: we never - -- wrap them in code fences and the streaming handler is responsible for - -- keeping the body up to date. Here we just insert the current body once. - if call.is_reason then - -- Build a plain text block if we don't have it yet. We keep the - -- first inserted line as the first line of reasoning text rather - -- than a blank spacer so that navigation from the header lands on - -- the actual content. - if not call.arguments_lines or #call.arguments_lines == 0 then - call.arguments_lines = {} - - for _, line in ipairs(Utils.split_lines(call.arguments or "")) do - line = line ~= "" and line or " " - table.insert(call.arguments_lines, line) - end - end - - local count = call.arguments_lines and #call.arguments_lines or 0 - if count > 0 then - self:_safe_buffer_update(chat.bufnr, function() - -- Insert reasoning lines immediately after the header line - vim.api.nvim_buf_set_lines(chat.bufnr, call.header_line, call.header_line, false, call.arguments_lines) - end) - - -- Track how many lines we inserted so that subsequent streaming - -- updates (_handle_reason_text) can correctly replace this block. - call._last_arguments_count = count - - -- Shift subsequent tool call header/label lines down - self:_adjust_tool_call_lines(call, count) - end - - call.expanded = true - self:_update_tool_call_header_line(call) - - -- Restore cursor position or move to last line based on config - if saved_cursor and chat.winid and vim.api.nvim_win_is_valid(chat.winid) then - -- Adjust cursor row if it was after the insertion point - if saved_cursor[1] > call.header_line then - saved_cursor[1] = saved_cursor[1] + count - end - vim.api.nvim_win_set_cursor(chat.winid, saved_cursor) - elseif not preserve_cursor and chat.winid and vim.api.nvim_win_is_valid(chat.winid) then - -- Default behavior: move cursor to last line of expanded content - local last_line = call.header_line + (call._last_arguments_count or 0) - vim.api.nvim_win_set_cursor(chat.winid, { last_line, 0 }) - vim.api.nvim_win_call(chat.winid, function() - vim.cmd("normal! zb") - end) - end - - return - end - - -- Regular tool calls: show JSON arguments and output blocks - call.arguments_lines = call.arguments_lines or self:_build_tool_call_arguments_lines(call.arguments, call.outputs) - local count = call.arguments_lines and #call.arguments_lines or 0 - if count == 0 then - return - end - - self:_safe_buffer_update(chat.bufnr, function() - -- Insert arguments immediately after the header line - vim.api.nvim_buf_set_lines(chat.bufnr, call.header_line, call.header_line, false, call.arguments_lines) - end) - - -- If there is a diff label, it must move down by the number of inserted lines - if call.has_diff and call.label_line then - call.label_line = call.label_line + count - end - - call.expanded = true - - -- Shift subsequent tool call header/label lines down - self:_adjust_tool_call_lines(call, count) - - -- Update header arrow - self:_update_tool_call_header_line(call) - - -- Restore cursor position or move to last line based on config - if saved_cursor and chat.winid and vim.api.nvim_win_is_valid(chat.winid) then - -- Adjust cursor row if it was after the insertion point - if saved_cursor[1] > call.header_line then - saved_cursor[1] = saved_cursor[1] + count - end - vim.api.nvim_win_set_cursor(chat.winid, saved_cursor) - elseif not preserve_cursor and chat.winid and vim.api.nvim_win_is_valid(chat.winid) then - -- Default behavior: move cursor to last line of expanded content - local last_line = call.header_line + count - vim.api.nvim_win_set_cursor(chat.winid, { last_line, 0 }) - vim.api.nvim_win_call(chat.winid, function() - vim.cmd("normal! zb") - end) - end -end - ----Collapse a tool call/reasoning entry, removing its expanded body from the buffer. ---- ----Also adjusts any stored diff label line and shifts subsequent tool-call line ----markers back up. ----@param call table Tool-call/reasoning entry. -function M:_collapse_tool_call(call) - local chat = self.containers.chat - if not chat or not vim.api.nvim_buf_is_valid(chat.bufnr) then - return - end - - if not call.expanded then - return - end - - -- Save cursor position before collapsing (if configured) - local saved_cursor = nil - local preserve_cursor = Utils.should_preserve_cursor() - if preserve_cursor and chat.winid and vim.api.nvim_win_is_valid(chat.winid) then - saved_cursor = vim.api.nvim_win_get_cursor(chat.winid) - end - - local count = call.arguments_lines and #call.arguments_lines or 0 - if count == 0 then - call.expanded = false - self:_update_tool_call_header_line(call) - return - end - - self:_safe_buffer_update(chat.bufnr, function() - -- Remove the arguments block directly below the header - vim.api.nvim_buf_set_lines(chat.bufnr, call.header_line, call.header_line + count, false, {}) - end) - - -- If there is a diff label, move it back up - if call.has_diff and call.label_line then - call.label_line = call.label_line - count - end - - call.expanded = false - - -- Shift subsequent tool call header/label lines back up - self:_adjust_tool_call_lines(call, -count) - - -- Update header arrow - self:_update_tool_call_header_line(call) - - -- Restore cursor position, adjusting if it was after the collapsed region - if saved_cursor and chat.winid and vim.api.nvim_win_is_valid(chat.winid) then - -- If cursor was inside the collapsed region, move it to the header - if saved_cursor[1] > call.header_line and saved_cursor[1] <= call.header_line + count then - saved_cursor[1] = call.header_line - saved_cursor[2] = 0 - -- If cursor was after the collapsed region, adjust it up - elseif saved_cursor[1] > call.header_line + count then - saved_cursor[1] = saved_cursor[1] - count - end - vim.api.nvim_win_set_cursor(chat.winid, saved_cursor) - end -end - ----Expand a tool call diff section below its "view diff" label. ---- ----Inserts `call.diff_lines` into the buffer, updates the diff label text, and ----shifts subsequent tool-call line markers. ----@param call table Tool-call entry with a diff (`has_diff` and `label_line`). -function M:_expand_tool_call_diff(call) - local chat = self.containers.chat - if not chat or not vim.api.nvim_buf_is_valid(chat.bufnr) then - return - end - - if not call.has_diff or not call.label_line or call.diff_expanded then - return - end - - -- Save cursor position before expansion (if configured) - local saved_cursor = nil - local preserve_cursor = Utils.should_preserve_cursor() - if preserve_cursor and chat.winid and vim.api.nvim_win_is_valid(chat.winid) then - saved_cursor = vim.api.nvim_win_get_cursor(chat.winid) - end - - call.diff_lines = call.diff_lines or self:_build_tool_call_diff_lines(call.details) - local count = call.diff_lines and #call.diff_lines or 0 - if count == 0 then - return - end - - self:_safe_buffer_update(chat.bufnr, function() - -- Insert diff lines immediately after the diff label line - vim.api.nvim_buf_set_lines(chat.bufnr, call.label_line, call.label_line, false, call.diff_lines) - end) - - call.diff_expanded = true - - -- Shift subsequent tool call header/label lines down - self:_adjust_tool_call_lines(call, count) - - -- Update the diff label to show the collapse indicator - self:_update_tool_call_diff_label_line(call) - - -- Restore cursor position (no default cursor movement for diff expansion) - if saved_cursor and chat.winid and vim.api.nvim_win_is_valid(chat.winid) then - -- Adjust cursor row if it was after the insertion point - if saved_cursor[1] > call.label_line then - saved_cursor[1] = saved_cursor[1] + count - end - vim.api.nvim_win_set_cursor(chat.winid, saved_cursor) - end -end - ----Collapse a tool call diff section, removing it from the chat buffer. ---- ----Also updates the diff label text and shifts subsequent tool-call line markers ----back up. ----@param call table Tool-call entry with `diff_expanded` and `label_line`. -function M:_collapse_tool_call_diff(call) - local chat = self.containers.chat - if not chat or not vim.api.nvim_buf_is_valid(chat.bufnr) then - return - end - - if not call.diff_expanded then - return - end - - -- Save cursor position before collapsing (if configured) - local saved_cursor = nil - local preserve_cursor = Utils.should_preserve_cursor() - if preserve_cursor and chat.winid and vim.api.nvim_win_is_valid(chat.winid) then - saved_cursor = vim.api.nvim_win_get_cursor(chat.winid) - end - - local count = call.diff_lines and #call.diff_lines or 0 - if count == 0 then - call.diff_expanded = false - self:_update_tool_call_diff_label_line(call) - return - end - - self:_safe_buffer_update(chat.bufnr, function() - -- Remove the diff block that starts immediately after the label line - vim.api.nvim_buf_set_lines(chat.bufnr, call.label_line, call.label_line + count, false, {}) - end) - - call.diff_expanded = false - - -- Shift subsequent tool call header/label lines back up - self:_adjust_tool_call_lines(call, -count) - - -- Update the diff label to show the expand indicator again - self:_update_tool_call_diff_label_line(call) - - -- Restore cursor position, adjusting if it was after the collapsed region - if saved_cursor and chat.winid and vim.api.nvim_win_is_valid(chat.winid) then - -- If cursor was inside the collapsed region, move it to the label - if saved_cursor[1] > call.label_line and saved_cursor[1] <= call.label_line + count then - saved_cursor[1] = call.label_line - saved_cursor[2] = 0 - -- If cursor was after the collapsed region, adjust it up - elseif saved_cursor[1] > call.label_line + count then - saved_cursor[1] = saved_cursor[1] - count - end - vim.api.nvim_win_set_cursor(chat.winid, saved_cursor) - end -end - ----Toggle tool call details at the current cursor position in the chat window. ---- ----If the cursor is on/under the diff label, toggles the diff block only. ----Otherwise toggles the arguments/reasoning body via the header arrow. -function M:_toggle_tool_call_at_cursor() - local chat = self.containers.chat - if not chat or not vim.api.nvim_win_is_valid(chat.winid) then - return - end - - local cursor = vim.api.nvim_win_get_cursor(chat.winid) - local line = cursor[1] - - local call = self:_find_tool_call_for_line(line) - if not call then - return - end - - -- If we are on or below the diff label for a call that has a diff, - -- toggle only the diff block. - if call.has_diff and call.label_line and line >= call.label_line then - if call.diff_expanded then - self:_collapse_tool_call_diff(call) - else - self:_expand_tool_call_diff(call) - end - return - end - - -- Otherwise toggle the arguments block via the header arrow - if call.expanded then - self:_collapse_tool_call(call) - else - self:_expand_tool_call(call) - end -end - ----@param target string ----@param replacement string ----@param opts? table|nil Optional search options: { max_search_lines = number, start_line = number } ----@return boolean changed True if any replacement was made -function M:_replace_text(target, replacement, opts) - local chat = self.containers.chat - - if not chat or not vim.api.nvim_buf_is_valid(chat.bufnr) then - Logger.warn("Cannot replace message: chat buffer not available") - return false - end - - if not target or target == "" then - Logger.warn("Cannot replace message: empty target") - return false - end - - if not replacement or replacement == "" then - Logger.warn("Cannot replace message: empty replacement") - return false - end - - local changed = false - - self:_safe_buffer_update(chat.bufnr, function() - local total_lines = vim.api.nvim_buf_line_count(chat.bufnr) - opts = opts or {} - - -- Limit how many lines to search for performance with large buffers - local max_search_lines = tonumber(opts.max_search_lines) or 500 - - -- If a start line is provided, start searching from there (useful for targeted replacement) - local start_line = tonumber(opts.start_line) or total_lines - if start_line < 1 then - start_line = 1 - end - if start_line > total_lines then - start_line = total_lines - end - - -- Determine the search window [end_line, start_line] - local end_line = math.max(1, start_line - max_search_lines + 1) - - -- Fetch only the relevant range once (0-based indices for nvim API) - local range_lines = vim.api.nvim_buf_get_lines(chat.bufnr, end_line - 1, start_line, false) - - -- Iterate from bottom to top within the range - for idx = #range_lines, 1, -1 do - local line = range_lines[idx] or "" - local s_idx, e_idx = line:find(target, 1, true) - if s_idx then - local absolute_line = end_line + idx - 1 -- convert to absolute 1-based line - - -- If replacement contains newlines, split it into proper buffer lines - if type(replacement) == "string" and replacement:find("\n") then - local parts = Utils.split_lines(replacement) - local prefix = line:sub(1, s_idx - 1) - local suffix = line:sub(e_idx + 1) - - local new_lines = {} - if #parts > 0 then - -- First line: prefix + first part - table.insert(new_lines, prefix .. parts[1]) - -- Middle parts (if any) - for i = 2, #parts do - table.insert(new_lines, parts[i]) - end - -- Append suffix to the last inserted line - new_lines[#new_lines] = new_lines[#new_lines] .. suffix - else - -- Fallback: no parts (shouldn't happen), just replace inline - table.insert(new_lines, prefix .. suffix) - end - - vim.api.nvim_buf_set_lines(chat.bufnr, absolute_line - 1, absolute_line, false, new_lines) - changed = true - break - else - -- Simple single-line replacement - local new_line = (line:sub(1, s_idx - 1)) .. replacement .. (line:sub(e_idx + 1)) - vim.api.nvim_buf_set_lines(chat.bufnr, absolute_line - 1, absolute_line, false, { new_line }) - changed = true - break - end - end - end - end) - - return changed -end - -return M diff --git a/lua/eca/state.lua b/lua/eca/state.lua deleted file mode 100644 index 73b9949..0000000 --- a/lua/eca/state.lua +++ /dev/null @@ -1,289 +0,0 @@ ----@class eca.StateStatus ----@field state string ----@field text string - ----@class eca.StateConfig ----@field welcome_message string? ----@field behaviors { list: string[], default: string?, selected: string? } ----@field models { list: string[], default: string?, selected: string? } - ----@class eca.StateUsage ----@field tokens { limit: number, session: number } ----@field costs { last_message: string, session: string } - ----@class eca.StateTool ----@field type string ----@field name string ----@field status string ---- ----@class eca.State ----@field id string? ----@field status eca.StateStatus ----@field config eca.StateConfig ----@field usage eca.StateUsage ----@field tools table ----@field contexts eca.Context[] -local State = {} - ----@return eca.State -function State._new() - local instance = setmetatable({ - id = nil, - status = { - state = "idle", - text = "Idle", - }, - config = { - welcome_message = nil, - behaviors = { - list = {}, - default = nil, - selected = nil, - }, - models = { - list = {}, - default = nil, - selected = nil, - }, - }, - usage = { - tokens = { - limit = 0, - session = 0, - }, - costs = { - last_message = "0.00", - session = "0.00", - }, - }, - tools = {}, - contexts = {}, - }, { __index = State }) - - local handlers = { - ["chat/contentReceived"] = function(message) instance:_chat_content_received(message) end, - ["config/updated"] = function(message) instance:_config_updated(message) end, - ["tool/serverUpdated"] = function(message) instance:_tool_server_updated(message) end, - } - - require("eca.observer").subscribe("state-1", function(message) - if not message or not message.method then - return - end - - local handler = handlers[message.method] - - if not handler or type(handler) ~= 'function' then - return - end - - handler(message) - end) - - return instance -end - -local _instance - ----@return eca.State -function State.new() - if not _instance then - _instance = State._new() - end - - return _instance -end - -function State:_chat_content_received(message) - if not message or not message.params then - return - end - - if not message.params.content or not message.params.content.type then - return - end - - if message.params.chatId and message.params.chatId ~= self.id then - self.id = message.params.chatId - end - - local content = message.params.content - - if content.type == "progress" then - self:_update_status(content) - end - - if content.type == "usage" then - self:_update_usage(content) - end -end - -function State:_config_updated(message) - if not message or not message.params then - return - end - - if not message.params.chat or type(message.params.chat) ~= "table" then - return - end - - self:_update_config({ chat = vim.deepcopy(message.params.chat) }) -end - -function State:_tool_server_updated(message) - if not message or not message.params then - return - end - - self:_update_tools(message.params) -end - -function State:_update_config(config) - local chat = config.chat - - if not chat or type(chat) ~= "table" then - return - end - - self.config.behaviors = { - list = (chat.behaviors and vim.deepcopy(chat.behaviors)) or self.config.behaviors.list, - default = (chat.defaultBehavior) or self.config.behaviors.default, - selected = (chat.selectBehavior) or self.config.behaviors.selected, - } - - self.config.models = { - list = (chat.models and vim.deepcopy(chat.models)) or self.config.models.list, - default = (chat.defaultModel) or self.config.models.default, - selected = (chat.selectModel) or self.config.models.selected, - } - - self.config.welcome_message = (chat and chat.welcomeMessage) or self.config.welcome_message - - vim.schedule(function() - require("eca.observer").notify({ type = "state/updated", content = { config = vim.deepcopy(self.config) } }) - end) -end - -function State:_update_status(status) - self.status.state = status.state or self.status.state - self.status.text = status.text or self.status.text - - vim.schedule(function() - require("eca.observer").notify({ type = "state/updated", content = { status = vim.deepcopy(self.status) } }) - end) -end - -function State:_update_usage(usage) - self.usage = { - tokens = { - limit = (usage.limit and usage.limit.context) or self.usage.tokens.limit, - session = usage.sessionTokens or self.usage.tokens.session, - }, - costs = { - last_message = usage.lastMessageCost or self.usage.costs.last_message, - session = usage.sessionCost or self.usage.costs.session, - }, - } - - vim.schedule(function() - require("eca.observer").notify({ type = "state/updated", content = { usage = vim.deepcopy(self.usage) } }) - end) -end - -function State:_update_tools(tool) - if not tool.name then - return - end - - self.tools[tool.name] = { - name = tool.name, - type = tool.type or (self.tools[tool.name] and self.tools[tool.name].type) or "unknown", - status = tool.status or (self.tools[tool.name] and self.tools[tool.name].status) or "unknown", - } - - vim.schedule(function() - require("eca.observer").notify({ type = "state/updated", content = { tools = vim.deepcopy(self.tools) } }) - end) -end - -function State:update_selected_model(model) - if not model or type(model) ~= "string" then - return - end - - self.config.models.selected = model - - vim.schedule(function() - require("eca.observer").notify({ type = "state/updated", content = { config = vim.deepcopy(self.config) } }) - end) -end - -function State:update_selected_behavior(behavior) - if not behavior or type(behavior) ~= "string" then - return - end - - self.config.behaviors.selected = behavior - - vim.schedule(function() - require("eca.observer").notify({ type = "state/updated", content = { config = vim.deepcopy(self.config) } }) - end) -end - -function State:_update_contexts() - vim.schedule(function() - require("eca.observer").notify({ type = "state/updated", content = { contexts = vim.deepcopy(self.contexts) } }) - end) -end - -function State:add_context(context) - if not context or type(context) ~= "table" then - return - end - - if not context.type or not context.data then - return - end - - -- avoid duplicates - for _, ctx in ipairs(self.contexts) do - if ctx.type == context.type and vim.deep_equal(ctx.data, context.data) then - return - end - end - - -- if is 'cursor' type and exists 'cursor' in contexts, replace - if context.type == "cursor" then - for i, ctx in ipairs(self.contexts) do - if ctx.type == "cursor" then - self.contexts[i] = context - self:_update_contexts() - return - end - end - end - - table.insert(self.contexts, context) - self:_update_contexts() -end - -function State:remove_context(context) - if not context or type(context) ~= "table" then - return - end - - for i, ctx in ipairs(self.contexts) do - if ctx.type == context.type and vim.deep_equal(ctx.data, context.data) then - table.remove(self.contexts, i) - self:_update_contexts() - break - end - end -end - -function State:clear_contexts() - self.contexts = {} - self:_update_contexts() -end - -return State diff --git a/lua/eca/stream_queue.lua b/lua/eca/stream_queue.lua deleted file mode 100644 index 4a00b2f..0000000 --- a/lua/eca/stream_queue.lua +++ /dev/null @@ -1,126 +0,0 @@ ----@class eca.StreamQueue ----@field private queue table Array of items to process ----@field private running boolean Whether the queue is currently processing ----@field private on_process function Callback to process each item ----@field private should_continue function Optional callback to check if processing should continue ----@field private chars_per_tick number Number of characters to display per tick ----@field private tick_delay number Delay between ticks in milliseconds - -local M = {} -M.__index = M - ----Create a new stream queue ----@param on_process function Function to call for each character batch: fn(text, is_complete) ----@param opts? table Optional configuration { chars_per_tick: number, tick_delay: number, should_continue: function } ----@return eca.StreamQueue -function M.new(on_process, opts) - opts = opts or {} - local instance = setmetatable({}, M) - instance.queue = {} - instance.running = false - instance.on_process = on_process - instance.should_continue = opts.should_continue - instance.chars_per_tick = opts.chars_per_tick or 1 - instance.tick_delay = opts.tick_delay or 10 - return instance -end - ----Add text to the queue for processing ----@param text string Text to add to the queue -function M:enqueue(text) - if not text or text == "" then - return - end - table.insert(self.queue, text) - self:process() -end - ----Process the queue -function M:process() - -- If already processing or queue is empty, return early - if self.running or #self.queue == 0 then - return - end - - self.running = true - - -- Combine all queued text into a single character queue for smooth continuous streaming - local combined_text = table.concat(self.queue, "") - self.queue = {} - - -- Create a local queue of characters from all text chunks - local char_queue = {} - for i = 1, #combined_text do - table.insert(char_queue, combined_text:sub(i, i)) - end - - local function done() - self.running = false - -- Process next item in queue if available (in case new items were added during processing) - if #self.queue > 0 then - self:process() - end - end - - local function step() - -- Check if we should continue processing (e.g., streaming is still active) - if self.should_continue and not self.should_continue() then - done() - return - end - - -- Check if new items were added to the queue while we were processing - -- If so, add them to the current character queue to maintain smooth animation - if #self.queue > 0 then - local new_text = table.concat(self.queue, "") - self.queue = {} - for i = 1, #new_text do - table.insert(char_queue, new_text:sub(i, i)) - end - end - - -- If no more characters in this chunk, mark as done - if #char_queue == 0 then - done() - return - end - - -- Render a small batch of characters per tick - local count = math.min(self.chars_per_tick, #char_queue) - local chunk = "" - for _ = 1, count do - chunk = chunk .. table.remove(char_queue, 1) - end - - -- Call the process callback with the chunk - -- Pass true if this is the last chunk - local is_complete = #char_queue == 0 and #self.queue == 0 - self.on_process(chunk, is_complete) - - -- Continue processing this chunk - vim.defer_fn(step, self.tick_delay) - end - - -- Start processing this chunk - vim.defer_fn(step, math.min(1, self.tick_delay)) -end - ----Clear the queue and stop processing -function M:clear() - self.queue = {} - self.running = false -end - ----Check if the queue is empty ----@return boolean -function M:is_empty() - return #self.queue == 0 and not self.running -end - ----Get the current queue size ----@return number -function M:size() - return #self.queue -end - -return M diff --git a/lua/eca/strings.lua b/lua/eca/strings.lua deleted file mode 100644 index 5244534..0000000 --- a/lua/eca/strings.lua +++ /dev/null @@ -1,9 +0,0 @@ -local M = {} - ----@param s string ----@return boolean -function M.is_nil_or_empty(s) - return s == nil or s == "" -end - -return M diff --git a/lua/eca/types.lua b/lua/eca/types.lua deleted file mode 100644 index c7967e7..0000000 --- a/lua/eca/types.lua +++ /dev/null @@ -1,104 +0,0 @@ ----@meta - ----@alias eca.ChatModel string ----@alias eca.ChatBehavior 'agent'|'plan' ----@class eca.ServerCapabilities ----@field welcomeMessage string ----@field models eca.ChatModel[] ----@field defaultModel eca.ChatModel ----@field behaviors eca.ChatBehavior[] ----@field defaultBehavior eca.ChatBehavior - ----@class eca.ChatContext ----@field type string ----@field path? string ----@field linesRange? {start: integer, end: integer} ----@field url? string ----@field uri? string ----@field name? string ----@field description? string ----@field mimeType? string ----@field server? string - ----@class eca.ChatCommand ----@field name string ----@field description string ----@field help string ----@field type "mcp-prompt"|"native" ----@field arguments {name: string, description?: string, required: boolean}[] - ----@alias eca.ToolCallOrigin "mcp"|"native" - ----@alias eca.ToolCallDetails eca.FileChangedDetails - ----TODO: flesh these out ----@alias eca.MessageParams table ----@alias eca.Message table - ----@class eca.FileChangedDetails ----@field type 'fileChange' ----@field path string the file path of this file change ----@field diff string the content diff of this file change ----@field linesAdded integer the count of lines added in this change ----@field linesRemoved integer the count of lines removed in this change - ----@class eca.ToolCallPrepare ----@field type 'toolCallPrepare' ----@field origin eca.ToolCallOrigin ----@field id string the id of the tool call ----@field name string name of the tool ----@field argumentsText {[string]: string} arguments of the tool call ----@field manualApproval boolean whether the call requires manual approval from the user ----@field summary string summary text to present about this tool call ---- extra details for the call. clients may use this to present a different UX ---- for this tool call. ----@field details eca.ToolCallDetails ---- - ----@class eca.ToolCallRun ----@field type 'toolCallRun' ----@field origin eca.ToolCallOrigin ----@field id string the id of the tool call ----@field name string name of the tool ----@field arguments {[string]: string} arguments of the tool call ----@field manualApproval boolean whether the call requires manual approval from the user ----@field summary string summary text to present about this tool call ---- extra details for the call. clients may use this to present a different UX ---- for this tool call. ----@field details eca.ToolCallDetails - ----@class eca.ToolCalled ----@field type 'toolCalled' ----@field id string the id of the tool call ----@field name string name of the tool ----@field arguments {[string]: string} arguments of the tool call ----@field errors boolean was there an error calling the tool ----@field outputs {type: 'text', text: string}[] the result of the tool call ----@field summary? string summary text to present about the tool call ----@field details? eca.ToolCallDetails extra details about the call - ----@class eca.UsageContent ----@field type 'usage' ----@field messageInputTokens number ----@field messageOutputTokens number ----@field sessionTokens number ----@field messageCost? string ----@field sessionCost? string - ----@class eca.ContextCursor ----@field path string ----@field position { position_start: { line: number , character: number }, position_end: { line: number , character: number } } - ----@class eca.ContextDirectory ----@field path string - ----@class eca.ContextFile ----@field path string ----@field lines_range { line_start: number, line_end: number } - ----@class eca.ContextWeb ----@field path string - ----@class eca.Context ----@field type 'cursor'|'directory'|'file'|'web' ----@field data eca.ContextCursor|eca.ContextDirectory|eca.ContextFile|eca.ContextWeb diff --git a/lua/eca/ui/picker.lua b/lua/eca/ui/picker.lua deleted file mode 100644 index 1f82388..0000000 --- a/lua/eca/ui/picker.lua +++ /dev/null @@ -1,18 +0,0 @@ -local Logger = require("eca.logger") - -local M = {} - ---- Wrapper around snacks.picker to provide a common entrypoint ---- for ECA pickers and handle the snacks dependency consistently. ----@param config snacks.picker.Config -function M.pick(config) - local has_snacks, snacks = pcall(require, "snacks") - if not has_snacks then - Logger.notify("snacks.nvim is not available", vim.log.levels.ERROR) - return - end - - return snacks.picker(config) -end - -return M diff --git a/lua/eca/utils.lua b/lua/eca/utils.lua deleted file mode 100644 index 96e4366..0000000 --- a/lua/eca/utils.lua +++ /dev/null @@ -1,219 +0,0 @@ -local uv = vim.uv or vim.loop - -local Logger = require("eca.logger") -local Config = require("eca.config") - -local M = {} - -local CONSTANTS = { - SIDEBAR_FILETYPE = "Eca", - SIDEBAR_BUFFER_NAME = "__ECA__", -} - ----@param bufnr integer ----@return boolean -function M.is_sidebar_buffer(bufnr) - local bufname = vim.api.nvim_buf_get_name(bufnr) - return vim.endswith(bufname, CONSTANTS.SIDEBAR_BUFFER_NAME) -end - ----@param mode string|table ----@param lhs string ----@param rhs string|function ----@param opts table -function M.safe_keymap_set(mode, lhs, rhs, opts) - -- Check if the keymap is already set - local existing = vim.fn.maparg(lhs, type(mode) == "table" and mode[1] or mode, false, true) - if existing and existing.rhs then - Logger.debug("Keymap " .. lhs .. " already exists, skipping") - return - end - vim.keymap.set(mode, lhs, rhs, opts) -end - ----@return string -function M.get_project_root() - local cwd = vim.fn.getcwd() - local git_root = vim.fn.systemlist("git -C " .. vim.fn.shellescape(cwd) .. " rev-parse --show-toplevel")[1] - if vim.v.shell_error == 0 and git_root then - return git_root - end - return cwd -end - ----@param text string ----@return string[] -function M.split_lines(text) - return vim.split(text, "\n", { plain = true, trimempty = false }) -end - ----@param path string ----@return boolean -function M.file_exists(path) - local stat = uv.fs_stat(path) - return stat and stat.type == "file" -end - ----@param dir string ----@return boolean -function M.dir_exists(dir) - local stat = uv.fs_stat(dir) - return stat and stat.type == "directory" -end - ----@param path string -function M.create_dir(path) - vim.fn.mkdir(path, "p") -end - ----@return string -function M.get_cache_dir() - local cache_dir = vim.fn.stdpath("cache") .. "/eca" - if not M.dir_exists(cache_dir) then - M.create_dir(cache_dir) - end - return cache_dir -end - ----@return string -function M.get_data_dir() - local data_dir = vim.fn.stdpath("data") .. "/eca" - if not M.dir_exists(data_dir) then - M.create_dir(data_dir) - end - return data_dir -end - ----@param path string ----@return string? -function M.read_file(path) - if not M.file_exists(path) then - return nil - end - - local file = io.open(path, "r") - if not file then - return nil - end - - local content = file:read("*a") - file:close() - return content -end - ----@param path string ----@param content string ----@return boolean -function M.write_file(path, content) - local file = io.open(path, "w") - if not file then - return false - end - - file:write(content) - file:close() - return true -end - ----@param n number|string ----@return string -function M.shorten_tokens(n) - n = tonumber(n) or 0 - if n >= 1000 then - local rounded = math.floor(n / 1000 + 0.5) - return string.format("%dk", rounded) - end - return tostring(n) -end - ----Get chat configuration by merging top-level and windows.chat config ----@return table -function M.get_chat_config() - -- Merge top-level `chat` (backwards compatible) with `windows.chat`. - -- `windows.chat` provides modern defaults, while a user-provided - -- `chat.tool_call` block (legacy style) can still override fields - -- like `diff_label` and `diff_start_expanded`. - local win_chat = (Config.windows and Config.windows.chat) or {} - local top_chat = Config.chat or {} - - if next(top_chat) == nil then - return win_chat - end - - return vim.tbl_deep_extend("force", win_chat, top_chat) -end - ----Get tool call icons configuration ----@return table -function M.get_tool_call_icons() - local chat_cfg = M.get_chat_config() - local icons_cfg = (chat_cfg.tool_call and chat_cfg.tool_call.icons) or {} - return { - success = icons_cfg.success or "✅", - error = icons_cfg.error or "❌", - running = icons_cfg.running or "⏳", - expanded = icons_cfg.expanded or "▲", - collapsed = icons_cfg.collapsed or "▶", - } -end - ----Get tool call diff labels configuration ---- ----Configuration (under `windows.chat.tool_call`): ---- tool_call = { ---- diff = { ---- collapsed_label = "+ view diff", -- Label when the diff is collapsed ---- expanded_label = "- view diff", -- Label when the diff is expanded ---- expanded = false, -- When true, tool diffs start expanded ---- }, ---- } ----@return table -function M.get_tool_call_diff_labels() - local chat_cfg = M.get_chat_config() - local cfg = chat_cfg.tool_call or {} - local diff_cfg = cfg.diff or {} - - return { - collapsed = diff_cfg.collapsed_label or "+ view diff", - expanded = diff_cfg.expanded_label or "- view diff", - } -end - ----Check if tool call diffs should start expanded ----@return boolean -function M.should_start_diff_expanded() - local chat_cfg = M.get_chat_config() - local cfg = chat_cfg.tool_call or {} - local diff_cfg = cfg.diff or {} - - return diff_cfg.expanded == true -end - ----Check if cursor position should be preserved when expanding/collapsing tool calls ----@return boolean -function M.should_preserve_cursor() - local chat_cfg = M.get_chat_config() - local cfg = chat_cfg.tool_call or {} - - return cfg.preserve_cursor == true -end - ----Get reasoning labels configuration ----@return table -function M.get_reasoning_labels() - local chat_cfg = M.get_chat_config() - local cfg = chat_cfg.reasoning or {} - local running = cfg.running_label or "Thinking..." - local finished = cfg.finished_label or "Thought" - - return { - running = running, - finished = finished, - } -end - -function M.constants() - return CONSTANTS -end - -return M diff --git a/lua/spec/nfnl/example_spec.lua b/lua/spec/nfnl/example_spec.lua new file mode 100644 index 0000000..45ce659 --- /dev/null +++ b/lua/spec/nfnl/example_spec.lua @@ -0,0 +1,18 @@ +-- [nfnl] fnl/spec/nfnl/example_spec.fnl +local _local_1_ = require("plenary.busted") +local describe = _local_1_.describe +local it = _local_1_.it +local assert = require("luassert.assert") +local core = require("eca.nfnl.core") +local function _2_() + local function _3_() + return assert.equals(1, core.first({1, 2, 3, 4, 5})) + end + it("gets the first value", _3_) + local function _4_() + assert.is_nil(core.first(nil)) + return assert.is_nil(core.first({})) + end + return it("returns nil for empty lists or nil", _4_) +end +return describe("first", _2_) diff --git a/plugin-spec.lua b/plugin-spec.lua deleted file mode 100644 index e908522..0000000 --- a/plugin-spec.lua +++ /dev/null @@ -1,73 +0,0 @@ --- Plugin specification for package managers -return { - name = "eca-nvim", - description = "ECA (Editor Code Assistant) integration for Neovim", - dependencies = { - "MunifTanjim/nui.nvim", -- UI framework (required) - "nvim-lua/plenary.nvim", -- For async operations (optional) - }, - config = function() - require("eca").setup({ - -- Default configuration - server_path = "", - server_args = "", - windows = { - usage = { - format = "{session_tokens_short} / {limit_tokens_short} (${session_cost})", - }, - }, - log = { - display = "split", -- "split" or "popup" - level = vim.log.levels.INFO, - file = "", -- Empty string uses default path - max_file_size_mb = 10, - }, - behavior = { - auto_set_keymaps = true, - auto_focus_sidebar = true, - auto_start_server = false, - auto_download = true, - show_status_updates = true, - }, - mappings = { - chat = "ec", - focus = "ef", - toggle = "et", - }, - }) - end, - keys = { - { "ec", "EcaChat", desc = "Open ECA chat" }, - { "ef", "EcaFocus", desc = "Focus ECA sidebar" }, - { "et", "EcaToggle", desc = "Toggle ECA sidebar" }, - }, - cmd = { - "EcaChat", - "EcaToggle", - "EcaFocus", - "EcaClose", - "EcaAddFile", - "EcaChatAddFile", - "EcaRemoveContext", - "EcaChatRemoveFile", - "EcaAddSelection", - "EcaChatAddSelection", - "EcaChatAddUrl", - "EcaListContexts", - "EcaChatListContexts", - "EcaClearContexts", - "EcaChatClearContexts", - "EcaServerStart", - "EcaServerStop", - "EcaServerRestart", - "EcaServerMessages", - "EcaSend", - "EcaLogs", - "EcaDebugWidth", - "EcaRedownload", - "EcaStopResponse", - "EcaFixTreesitter", - "EcaChatSelectModel", - "EcaChatSelectBehavior", - }, -} diff --git a/plugin/eca.lua b/plugin/eca.lua deleted file mode 100644 index c05b88a..0000000 --- a/plugin/eca.lua +++ /dev/null @@ -1,11 +0,0 @@ --- plugin/eca.lua --- Main plugin entry point for ECA - -if vim.g.loaded_eca then - return -end - --- Setup commands immediately -require("eca.commands").setup() - -vim.g.loaded_eca = 1 diff --git a/script/nfnl b/script/nfnl new file mode 100755 index 0000000..6c9deb9 --- /dev/null +++ b/script/nfnl @@ -0,0 +1,15 @@ +#!/usr/bin/env bash + +set -xe + +mkdir -p deps + +if [ -d "deps/nfnl" ]; then + (cd deps/nfnl && git pull) +else + git clone https://github.com/Olical/nfnl.git deps/nfnl +fi + +SRC_DIR=deps/nfnl \ + DEST_PROJECT=eca \ + ./deps/nfnl/script/embed "." diff --git a/scripts/minimal_init.lua b/scripts/minimal_init.lua deleted file mode 100644 index 7414242..0000000 --- a/scripts/minimal_init.lua +++ /dev/null @@ -1,25 +0,0 @@ --- Minimal init.lua for testing -vim.cmd([[let &rtp.=','.getcwd()]]) - --- Disable swap files and other unnecessary features for testing -vim.o.swapfile = false -vim.o.backup = false -vim.o.writebackup = false - --- Add dependencies to runtime path if headless -if #vim.api.nvim_list_uis() == 0 then - vim.cmd('set rtp+=deps/mini.nvim') - vim.cmd('set rtp+=deps/nui.nvim') - require('mini.test').setup({ - collect = { - emulate_busted = true, - find_files = function() - return vim.fn.globpath('tests', '**/test_*.lua', true, true) - end, - }, - execute = { - stop_on_error = false, - }, - silent = false, - }) -end \ No newline at end of file diff --git a/scripts/server_path.lua b/scripts/server_path.lua deleted file mode 100644 index 882cdef..0000000 --- a/scripts/server_path.lua +++ /dev/null @@ -1,42 +0,0 @@ --- Setup if headless -if #vim.api.nvim_list_uis() == 0 then - -- hijack to make server tests work on CI using --clean mode - local ok = pcall(require, "eca") - if not ok then - vim.cmd([[let &rtp.=','.getcwd()]]) - vim.cmd('set rtp+=deps/nui.nvim') - vim.cmd('set rtp+=deps/eca-nvim') - - local try_again, err = pcall(require, "eca") - if not try_again then - error("Could not load eca.nvim: " .. tostring(err)) - os.exit(1) - end - end - - vim.o.swapfile = false - vim.o.backup = false - vim.o.writebackup = false -end - -local path_finder, path_finder_or_err = pcall(require, "eca.path_finder") - -if not path_finder then - io.stderr:write("Could not load eca.path_finder: " .. tostring(path_finder_or_err)) - os.exit(1) -end - -local PathFinder = path_finder_or_err:new() -local path - -local ok, err = pcall(function() - path = PathFinder:find() -end) - -if not ok then - io.stderr:write(tostring(err)) - os.exit(1) -end - -io.stdout:write(tostring(path)) -os.exit(0) diff --git a/tests/stubs/tool_calls.lua b/tests/stubs/tool_calls.lua deleted file mode 100644 index 097ad72..0000000 --- a/tests/stubs/tool_calls.lua +++ /dev/null @@ -1,48 +0,0 @@ -local stubs = {} - -stubs.read_file = { - arguments = { - path = "/Users/tgeorge/git/eca-nvim/hack/messages.lua", - }, - id = "toolu_013zj73SHzZNoeE7kzD7qzb4", - manualApproval = true, - name = "eca_read_file", - origin = "native", - summary = "Reading file messages.lua", - type = "toolCallRun", -} - -stubs.edit_file = { - arguments = { - new_content = 'local M = {}\n\n--- Show ECA messages using snacks.picker\nfunction M.show()\n local has_snacks, picker = pcall(require, "snacks.picker")\n if not has_snacks then\n vim.notify("snacks.picker is not available", vim.log.levels.ERROR)\n return\n end\n\n Snacks.picker(\n ---@type snacks.picker.Config\n {\n source = "eca messages",\n finder = function(opts, ctx)\n ---@type snacks.picker.finder.Item[]\n local items = {}\n for msg in vim.iter(require("eca").server.messages) do\n local decoded = vim.json.decode(msg.content)\n table.insert(items, {\n text = decoded.method,\n idx = decoded.id,\n preview = {\n text = vim.inspect(decoded),\n ft = "lua",\n},\n})\n end\n return items\n end,\n preview = "preview",\n format = "text",\n confirm = function(self, item, _)\n vim.fn.setreg("", item.preview.text)\n self:close()\n end,\n }\n )\nend\n\nreturn M', - original_content = 'local has_snacks, picker = pcall(require, "snacks.picker")\nif has_snacks then\n Snacks.picker(\n ---@type snacks.picker.Config\n {\n source = "eca messages",\n finder = function(opts, ctx)\n ---@type snacks.picker.finder.Item[]\n local items = {}\n for msg in vim.iter(require("eca").server.messages) do\n local decoded = vim.json.decode(msg.content)\n table.insert(items, {\n text = decoded.method,\n idx = decoded.id,\n preview = {\n text = vim.inspect(decoded),\n ft = "lua",\n },\n })\n end\n return items\n end,\n preview = "preview",\n format = "text",\n confirm = function(self, item, _)\n vim.fn.setreg("", item.preview.text)\n self:close()\n end,\n }\n )\nend', - path = "/Users/tgeorge/git/eca-nvim/hack/messages.lua", - }, - details = { - diff = '@@ -1, 5 +1, 13 @@\n-local has_snacks, picker = pcall(require, "snacks.picker")\n-if has_snacks then\n+local M = {}\n+\n+--- Show ECA messages using snacks.picker\n+function M.show()\n+ local has_snacks, picker = pcall(require, "snacks.picker")\n+ if not has_snacks then\n+ vim.notify("snacks.picker is not available", vim.log.levels.ERROR)\n+ return\n+ end\n+\n Snacks.picker(\n ---@type snacks.picker.Config\n {\n@@ -29, 3 +37, 5 @@\n }\n )\n end\n+\n+return M', - linesAdded = 12, - linesRemoved = 10, - path = "/Users/tgeorge/git/eca-nvim/hack/messages.lua", - type = "fileChange", - }, - id = "toolu_01KAVb3qpJDcSnbnJmpUndQF", - manualApproval = true, - name = "eca_edit_file", - origin = "native", - summary = "Editting file", - type = "toolCallRun", -} - -stubs.mcp = { - arguments = { - content = 'return "hello world"', - path = "/Users/tgeorge/git/eca-nvim/hack/test_mcp_write_file.lua", - }, - id = "toolu_01B8xcb7csLRHvqrnAZTgzPi", - manualApproval = true, - name = "write_file", - origin = "mcp", - type = "toolCallRun", -} - -return stubs diff --git a/tests/test_approve.lua b/tests/test_approve.lua deleted file mode 100644 index 17db288..0000000 --- a/tests/test_approve.lua +++ /dev/null @@ -1,91 +0,0 @@ -local MiniTest = require("mini.test") -local eq = MiniTest.expect.equality -local child = MiniTest.new_child_neovim() -local stubs = require("tests.stubs.tool_calls") - -local T = MiniTest.new_set({ - hooks = { - pre_case = function() - child.restart({ "-u", "scripts/minimal_init.lua" }) - child.lua([[ - _G.notifications = {} - _G.on_accept = function() table.insert(_G.notifications, "accept") end - _G.on_reject = function() table.insert(_G.notifications, "reject") end - ]]) - end, - post_once = child.stop, - }, -}) - -T["preview lines"] = function() - local test_cases = { - { - input = stubs.read_file, - want = { - "Summary: Reading file messages.lua", - "Tool Name: eca_read_file", - "Tool Type: native", - "Tool Arguments: ", - "{", - ' path = "/Users/tgeorge/git/eca-nvim/hack/messages.lua"', - "}", - }, - }, - { - input = stubs.edit_file, - want = { - "/Users/tgeorge/git/eca-nvim/hack/messages.lua", - "@@ -1, 5 +1, 13 @@", - '-local has_snacks, picker = pcall(require, "snacks.picker")', - "-if has_snacks then", - "+local M = {}", - "+", - "+--- Show ECA messages using snacks.picker", - "+function M.show()", - '+ local has_snacks, picker = pcall(require, "snacks.picker")', - "+ if not has_snacks then", - '+ vim.notify("snacks.picker is not available", vim.log.levels.ERROR)', - "+ return", - "+ end", - "+", - " Snacks.picker(", - " ---@type snacks.picker.Config", - " {", - "@@ -29, 3 +37, 5 @@", - " }", - " )", - " end", - "+", - "+return M", - }, - }, - { - input = stubs.mcp, - want = { - "Tool Name: write_file", - "Tool Type: mcp", - "Tool Arguments: ", - "{", - " content = 'return \"hello world\"',", - ' path = "/Users/tgeorge/git/eca-nvim/hack/test_mcp_write_file.lua"', - "}", - }, - }, - } - for _, test_case in pairs(test_cases) do - local got = child.lua_get('require("eca.approve").get_preview_lines(...)', { test_case.input }) - eq(got, test_case.want) - end -end - -T["tool approval calls callback"] = function() - child.lua("_G.tool_call = " .. vim.inspect(stubs.read_file)) - child.lua('require("eca.approve").approve_tool_call(_G.tool_call, _G.on_accept, _G.on_reject)') - child.type_keys("y") - eq(child.lua_get("_G.notifications"), { "accept" }) - child.lua('require("eca.approve").approve_tool_call(_G.tool_call, _G.on_accept, _G.on_reject)') - child.type_keys("n") - eq(child.lua_get("_G.notifications"), { "accept", "reject" }) -end - -return T diff --git a/tests/test_chat_clear.lua b/tests/test_chat_clear.lua deleted file mode 100644 index 8cb78c0..0000000 --- a/tests/test_chat_clear.lua +++ /dev/null @@ -1,246 +0,0 @@ -local MiniTest = require("mini.test") -local eq = MiniTest.expect.equality -local child = MiniTest.new_child_neovim() - -local function flush(ms) - vim.uv.sleep(ms or 120) - child.api.nvim_eval("1") -end - --- Returns the registered command's name, or nil if not registered. Filters --- server-side so the function-valued `callback` field (present on 0.12+) --- does not cross the MiniTest msgpack boundary. -local function cmd_registered_name(name) - return child.lua_get(string.format( - "(vim.api.nvim_get_commands({})[%q] or {}).name", - name - )) -end - -local function setup_helpers() - _G.fill_chat = function() - local sidebar = require("eca").get() - local chat = sidebar.containers.chat - vim.api.nvim_buf_set_lines(chat.bufnr, 0, -1, false, { "hello", "world", "foo" }) - end - - _G.get_chat_lines = function() - local sidebar = require("eca").get() - if not sidebar then - return nil - end - local chat = sidebar.containers and sidebar.containers.chat - if not chat or not vim.api.nvim_buf_is_valid(chat.bufnr) then - return nil - end - return vim.api.nvim_buf_get_lines(chat.bufnr, 0, -1, false) - end - - _G.chat_has_old_content = function() - for _, line in ipairs(_G.get_chat_lines() or {}) do - if line == "hello" or line == "world" or line == "foo" then - return true - end - end - return false - end - - _G.get_sidebar_flags = function() - local sidebar = require("eca").get() - if not sidebar then - return nil - end - return { - welcome_message_applied = sidebar._welcome_message_applied, - force_welcome = sidebar._force_welcome, - } - end -end - -local function setup_env(preserve_chat_history) - child.lua( - [[ - local Eca = require("eca") - Eca.setup({ - behavior = { - auto_start_server = false, - auto_set_keymaps = false, - preserve_chat_history = ..., - }, - }) - local tab = vim.api.nvim_get_current_tabpage() - Eca._init(tab) - Eca.open_sidebar({}) - ]], - { preserve_chat_history } - ) - child.lua_func(setup_helpers) -end - -local T = MiniTest.new_set({ - hooks = { - pre_case = function() - child.restart({ "-u", "scripts/minimal_init.lua" }) - end, - post_once = child.stop, - }, -}) - --- EcaChatClear --------------------------------------------------------------- - -T["EcaChatClear"] = MiniTest.new_set() - -T["EcaChatClear"]["command is registered"] = function() - setup_env(false) - eq(cmd_registered_name("EcaChatClear"), "EcaChatClear") -end - -T["EcaChatClear"]["clears chat buffer when sidebar is open"] = function() - setup_env(false) - flush(200) - - child.lua("_G.fill_chat()") - eq(#child.lua_get("_G.get_chat_lines()"), 3) - - child.cmd("EcaChatClear") - - eq(child.lua_get("_G.get_chat_lines()"), { "" }) -end - -T["EcaChatClear"]["works without error when buffer is already empty"] = function() - setup_env(false) - flush(200) - - child.lua([[ - local sidebar = require("eca").get() - vim.api.nvim_buf_set_lines(sidebar.containers.chat.bufnr, 0, -1, false, {}) - ]]) - - child.cmd("EcaChatClear") - - eq(child.lua_get("_G.get_chat_lines()"), { "" }) -end - -T["EcaChatClear"]["clears hidden buffer when sidebar is closed with preserve=true"] = function() - setup_env(true) - flush(200) - - child.lua("_G.fill_chat()") - child.lua([[require("eca").close_sidebar()]]) - flush(100) - - child.cmd("EcaChatClear") - - eq(child.lua_get("_G.get_chat_lines()"), { "" }) -end - -T["EcaChatClear"]["buffer stays cleared on reopen with preserve=true"] = function() - setup_env(true) - flush(200) - - child.lua("_G.fill_chat()") - child.lua([[require("eca").close_sidebar()]]) - flush(100) - - child.cmd("EcaChatClear") - - eq(child.lua_get("_G.get_chat_lines()"), { "" }) - - child.lua([[require("eca").open_sidebar({})]]) - flush(200) - - eq(child.lua_get("_G.chat_has_old_content()"), false) -end - -T["EcaChatClear"]["is a no-op when sidebar is closed and buffer was destroyed (preserve=false)"] = function() - -- With preserve=false, closing the sidebar destroys the buffer, so there is - -- nothing for EcaChatClear to clear. The important guarantee is that the - -- command does not raise an error in this state. - setup_env(false) - flush(200) - - child.lua("_G.fill_chat()") - child.lua([[require("eca").close_sidebar()]]) - flush(100) - - local ok = child.lua_get("pcall(vim.cmd, 'EcaChatClear')") - eq(ok, true) -end - -T["EcaChatClear"]["marks welcome as applied and clears force_welcome after clear"] = function() - setup_env(false) - flush(200) - - child.lua("_G.fill_chat()") - child.cmd("EcaChatClear") - - local flags = child.lua_get("_G.get_sidebar_flags()") - eq(flags.welcome_message_applied, true) - eq(flags.force_welcome, false) -end - -T["EcaChatClear"]["is idempotent when called twice"] = function() - setup_env(false) - flush(200) - - child.lua("_G.fill_chat()") - child.cmd("EcaChatClear") - child.cmd("EcaChatClear") - - eq(child.lua_get("_G.get_chat_lines()"), { "" }) -end - --- preserve_chat_history toggle cycle ----------------------------------------- - -T["preserve_chat_history"] = MiniTest.new_set() - -T["preserve_chat_history"]["reuses same bufnr and keeps content across close/open"] = function() - setup_env(true) - flush(200) - - child.lua("_G.fill_chat()") - local bufnr_before = child.lua_get("require('eca').get().containers.chat.bufnr") - - child.lua([[require("eca").close_sidebar()]]) - flush(100) - child.lua([[require("eca").open_sidebar({})]]) - flush(200) - - local bufnr_after = child.lua_get("require('eca').get().containers.chat.bufnr") - eq(bufnr_before, bufnr_after) - eq(child.lua_get("_G.chat_has_old_content()"), true) -end - -T["preserve_chat_history"]["does not leak buffers across repeated toggles"] = function() - setup_env(true) - flush(200) - - local buf_count_before = child.lua_get("#vim.api.nvim_list_bufs()") - - for _ = 1, 5 do - child.lua([[require("eca").close_sidebar()]]) - flush(100) - child.lua([[require("eca").open_sidebar({})]]) - flush(200) - end - - local buf_count_after = child.lua_get("#vim.api.nvim_list_bufs()") - -- Allow at most 1 extra buffer (nui internals), but definitely not 5+ - eq(buf_count_after - buf_count_before <= 1, true) -end - -T["preserve_chat_history"]["content is lost when preserve is disabled"] = function() - setup_env(false) - flush(200) - - child.lua("_G.fill_chat()") - - child.lua([[require("eca").close_sidebar()]]) - flush(100) - child.lua([[require("eca").open_sidebar({})]]) - flush(200) - - eq(child.lua_get("_G.chat_has_old_content()"), false) -end - -return T diff --git a/tests/test_chat_id.lua b/tests/test_chat_id.lua deleted file mode 100644 index 49d135b..0000000 --- a/tests/test_chat_id.lua +++ /dev/null @@ -1,118 +0,0 @@ -local MiniTest = require("mini.test") -local eq = MiniTest.expect.equality -local child = MiniTest.new_child_neovim() - -local function flush(ms) - vim.uv.sleep(ms or 50) - child.api.nvim_eval("1") -end - -local function setup_env() - -- Initialize everything - _G.Server = require('eca.server').new() - _G.State = require('eca.state').new() - _G.Mediator = require('eca.mediator').new(_G.Server, _G.State) - _G.Sidebar = require('eca.sidebar').new(1, _G.Mediator) -end - -local T = MiniTest.new_set({ - hooks = { - pre_case = function() - child.restart({ "-u", "scripts/minimal_init.lua" }) - child.lua([[require('eca.commands').setup()]]) - child.lua_func(setup_env) - end, - post_case = function() - child.lua("if _G.Server and _G.Server.process then _G.Server.process:kill() end") - end, - post_once = child.stop, - }, -}) - -T["chat id lifecycle"] = MiniTest.new_set() - -T["chat id lifecycle"]["mediator id follows state id updates"] = function() - -- Initially there is no chat id - eq(child.lua_get("_G.State.id"), vim.NIL) - eq(child.lua_get("_G.Mediator:id()"), vim.NIL) - - -- Simulate a content notification with a chatId - child.lua([[require('eca.observer').notify({ - method = 'chat/contentReceived', - params = { chatId = 'chat-123', content = { type = 'progress', state = 'responding', text = '...' } }, - })]]) - flush() - - eq(child.lua_get("_G.State.id"), "chat-123") - eq(child.lua_get("_G.Mediator:id()"), "chat-123") -end - -T["chat id lifecycle"]["send request uses current chat id when available"] = function() - -- Ensure no chat id initially - eq(child.lua_get("_G.State.id"), vim.NIL) - - -- Send a message before any chat id exists - child.lua([[_G.Sidebar:_send_message('hello')]]) - - -- Inspect the last message sent to the server - local last_json = child.lua_get("_G.Server.messages[#_G.Server.messages].content") - local parsed = child.lua_get("vim.json.decode(...)", { last_json }) - eq(parsed.method, "chat/prompt") - -- When id is nil, chatId should be absent in params - eq(parsed.params.chatId == nil, true) - - -- Now simulate receiving a new chat id - child.lua([[require('eca.observer').notify({ - method = 'chat/contentReceived', - params = { chatId = 'chat-new', content = { type = 'progress', state = 'responding', text = '...' } }, - })]]) - flush() - eq(child.lua_get("_G.State.id"), "chat-new") - - -- Send another message; it should include the new chat id - child.lua([[_G.Sidebar:_send_message('again')]]) - local last_json2 = child.lua_get("_G.Server.messages[#_G.Server.messages].content") - local parsed2 = child.lua_get("vim.json.decode(...)", { last_json2 }) - eq(parsed2.method, "chat/prompt") - eq(parsed2.params.chatId, "chat-new") -end - -T["chat id lifecycle"]["reopening neovim uses a new chat id"] = function() - -- First session: set a chat id via notification - child.lua([[require('eca.observer').notify({ - method = 'chat/contentReceived', - params = { chatId = 'chat-first', content = { type = 'progress', state = 'responding', text = '...' } }, - })]]) - flush() - eq(child.lua_get("_G.State.id"), "chat-first") - - -- Restart Neovim to simulate reopening - child.restart({ "-u", "scripts/minimal_init.lua" }) - child.lua([[require('eca.commands').setup()]]) - child.lua_func(setup_env) - - -- New session should not carry over the previous chat id - eq(child.lua_get("_G.State.id"), vim.NIL) - - -- First message should not include a chatId - child.lua([[_G.Sidebar:_send_message('hello after reopen')]]) - local last_json3 = child.lua_get("_G.Server.messages[#_G.Server.messages].content") - local parsed = child.lua_get("vim.json.decode(...)", { last_json3 }) - eq(parsed.method, "chat/prompt") - eq(parsed.params.chatId == nil, true) - - -- After receiving content, a new chat id should be used - child.lua([[require('eca.observer').notify({ - method = 'chat/contentReceived', - params = { chatId = 'chat-second', content = { type = 'progress', state = 'responding', text = '...' } }, - })]]) - flush() - eq(child.lua_get("_G.State.id"), "chat-second") - - child.lua([[_G.Sidebar:_send_message('use new id')]]) - local last_json4 = child.lua_get("_G.Server.messages[#_G.Server.messages].content") - local parsed2 = child.lua_get("vim.json.decode(...)", { last_json4 }) - eq(parsed2.params.chatId, "chat-second") -end - -return T diff --git a/tests/test_config.lua b/tests/test_config.lua deleted file mode 100644 index 1a958f9..0000000 --- a/tests/test_config.lua +++ /dev/null @@ -1,787 +0,0 @@ -local MiniTest = require("mini.test") -local eq = MiniTest.expect.equality -local child = MiniTest.new_child_neovim() - -local T = MiniTest.new_set({ - hooks = { - pre_case = function() - child.restart({ "-u", "scripts/minimal_init.lua" }) - end, - post_once = child.stop, - }, -}) - --- ===== Chat config merging tests ===== - -T["chat_config"] = MiniTest.new_set() - -T["chat_config"]["get_chat_config merges legacy and new config"] = function() - child.lua([[ - local Config = require('eca.config') - Config.override({ - chat = { - headers = { - user = "OLD> ", - }, - }, - windows = { - chat = { - headers = { - user = "NEW> ", - assistant = "AI: ", - }, - }, - }, - }) - - local Utils = require('eca.utils') - local merged = Utils.get_chat_config() - _G.merged_config = { - user_header = merged.headers and merged.headers.user or nil, - assistant_header = merged.headers and merged.headers.assistant or nil, - } - ]]) - - local merged = child.lua_get("_G.merged_config") - - -- Legacy chat.headers overrides windows.chat.headers via deep_extend - eq(merged.user_header, "OLD> ") - eq(merged.assistant_header, "AI: ") -end - -T["chat_config"]["get_chat_config returns windows.chat when no legacy config"] = function() - child.lua([[ - local Config = require('eca.config') - Config.override({ - windows = { - chat = { - headers = { - user = "> ", - assistant = "", - }, - }, - }, - }) - - local Utils = require('eca.utils') - local merged = Utils.get_chat_config() - _G.merged_config = { - user_header = merged.headers and merged.headers.user or nil, - assistant_header = merged.headers and merged.headers.assistant or nil, - } - ]]) - - local merged = child.lua_get("_G.merged_config") - - eq(merged.user_header, "> ") - eq(merged.assistant_header, "") -end - --- ===== Diff expansion config tests ===== - -T["diff_config"] = MiniTest.new_set() - -T["diff_config"]["should_start_diff_expanded respects windows.chat.tool_call.diff.expanded"] = function() - child.lua([[ - local Config = require('eca.config') - Config.override({ - windows = { - chat = { - tool_call = { - diff = { - expanded = true, - }, - }, - }, - }, - }) - - local Utils = require('eca.utils') - _G.should_expand = Utils.should_start_diff_expanded() - ]]) - - eq(child.lua_get("_G.should_expand"), true) -end - -T["diff_config"]["should_start_diff_expanded checks diff.expanded only"] = function() - child.lua([[ - local Config = require('eca.config') - Config.override({ - windows = { - chat = { - tool_call = { - diff = { - expanded = false, - }, - }, - }, - }, - }) - - local Utils = require('eca.utils') - _G.should_expand = Utils.should_start_diff_expanded() - ]]) - - eq(child.lua_get("_G.should_expand"), false) -end - -T["diff_config"]["should_start_diff_expanded defaults to false"] = function() - child.lua([[ - local Config = require('eca.config') - Config.override({}) - - local Utils = require('eca.utils') - _G.should_expand = Utils.should_start_diff_expanded() - ]]) - - eq(child.lua_get("_G.should_expand"), false) -end - --- ===== Preserve cursor config tests ===== - -T["preserve_cursor_config"] = MiniTest.new_set() - -T["preserve_cursor_config"]["should_preserve_cursor returns true when enabled"] = function() - child.lua([[ - local Config = require('eca.config') - Config.override({ - windows = { - chat = { - tool_call = { - preserve_cursor = true, - }, - }, - }, - }) - - local Utils = require('eca.utils') - _G.preserve = Utils.should_preserve_cursor() - ]]) - - eq(child.lua_get("_G.preserve"), true) -end - -T["preserve_cursor_config"]["should_preserve_cursor returns false when disabled"] = function() - child.lua([[ - local Config = require('eca.config') - Config.override({ - windows = { - chat = { - tool_call = { - preserve_cursor = false, - }, - }, - }, - }) - - local Utils = require('eca.utils') - _G.preserve = Utils.should_preserve_cursor() - ]]) - - eq(child.lua_get("_G.preserve"), false) -end - -T["preserve_cursor_config"]["should_preserve_cursor defaults to true"] = function() - child.lua([[ - local Config = require('eca.config') - Config.override({}) - - local Utils = require('eca.utils') - _G.preserve = Utils.should_preserve_cursor() - ]]) - - eq(child.lua_get("_G.preserve"), true) -end - -T["preserve_cursor_config"]["should_preserve_cursor respects legacy chat.tool_call config"] = function() - child.lua([[ - local Config = require('eca.config') - Config.override({ - chat = { - tool_call = { - preserve_cursor = true, - }, - }, - }) - - local Utils = require('eca.utils') - _G.preserve = Utils.should_preserve_cursor() - ]]) - - eq(child.lua_get("_G.preserve"), true) -end - -T["preserve_cursor_config"]["should_preserve_cursor merges windows.chat and chat config"] = function() - child.lua([[ - local Config = require('eca.config') - Config.override({ - windows = { - chat = { - tool_call = { - preserve_cursor = false, - }, - }, - }, - chat = { - tool_call = { - preserve_cursor = true, - }, - }, - }) - - local Utils = require('eca.utils') - _G.preserve = Utils.should_preserve_cursor() - ]]) - - -- Legacy chat config should override windows.chat via deep_extend - eq(child.lua_get("_G.preserve"), true) -end - --- ===== Behavioral validation tests ===== --- These tests verify that config changes actually affect sidebar behavior - -T["behavior_validation"] = MiniTest.new_set() - -T["behavior_validation"]["preserve_cursor=true actually preserves cursor position on expand"] = function() - child.lua([[ - local Config = require('eca.config') - Config.override({ - windows = { - chat = { - tool_call = { - preserve_cursor = true, - }, - }, - }, - }) - - local Server = require('eca.server').new() - local State = require('eca.state').new() - local Mediator = require('eca.mediator').new(Server, State) - local Sidebar = require('eca.sidebar') - local sidebar = Sidebar.new(1, Mediator) - - sidebar:open() - - local chat = sidebar.containers.chat - vim.api.nvim_buf_set_lines(chat.bufnr, 0, -1, false, { - "Line 1", - "Line 2", - "Line 3", - "Line 4", - "Line 5", - }) - - sidebar._tool_calls = { - { - id = "test-id", - title = "Test", - header_line = 2, - expanded = false, - arguments = "{}", - arguments_lines = {"arg1", "arg2"}, - details = {}, - has_diff = false, - } - } - - vim.api.nvim_win_set_cursor(chat.winid, {5, 0}) - sidebar:_expand_tool_call(sidebar._tool_calls[1]) - - local cursor = vim.api.nvim_win_get_cursor(chat.winid) - _G.cursor_after = cursor[1] - _G.expected = 7 -- Line 5 + 2 inserted lines - ]]) - - eq(child.lua_get("_G.cursor_after"), child.lua_get("_G.expected")) -end - -T["behavior_validation"]["preserve_cursor=false moves cursor to end on expand"] = function() - child.lua([[ - local Config = require('eca.config') - Config.override({ - windows = { - chat = { - tool_call = { - preserve_cursor = false, - }, - }, - }, - }) - - local Server = require('eca.server').new() - local State = require('eca.state').new() - local Mediator = require('eca.mediator').new(Server, State) - local Sidebar = require('eca.sidebar') - local sidebar = Sidebar.new(1, Mediator) - - sidebar:open() - - local chat = sidebar.containers.chat - vim.api.nvim_buf_set_lines(chat.bufnr, 0, -1, false, { - "Line 1", - "Line 2", - "Line 3", - "Line 4", - }) - - sidebar._tool_calls = { - { - id = "test-id", - title = "Test", - header_line = 2, - expanded = false, - arguments = "{}", - arguments_lines = {"arg1", "arg2"}, - details = {}, - has_diff = false, - } - } - - vim.api.nvim_win_set_cursor(chat.winid, {1, 0}) - sidebar:_expand_tool_call(sidebar._tool_calls[1]) - - local cursor = vim.api.nvim_win_get_cursor(chat.winid) - _G.cursor_after = cursor[1] - _G.expected = 4 -- header_line (2) + arguments_lines count (2) - ]]) - - eq(child.lua_get("_G.cursor_after"), child.lua_get("_G.expected")) -end - -T["behavior_validation"]["diff.expanded=true causes diffs to start expanded"] = function() - child.lua([[ - local Config = require('eca.config') - Config.override({ - windows = { - chat = { - tool_call = { - diff = { - expanded = true, - }, - }, - }, - }, - }) - - local Server = require('eca.server').new() - local State = require('eca.state').new() - local Mediator = require('eca.mediator').new(Server, State) - local Sidebar = require('eca.sidebar') - local sidebar = Sidebar.new(1, Mediator) - - sidebar:open() - - local chat = sidebar.containers.chat - vim.api.nvim_buf_set_lines(chat.bufnr, 0, -1, false, {"Line 1"}) - - -- Simulate a tool call with diff that should auto-expand - sidebar:handle_chat_content_received({ - chatId = 'test', - content = { - type = 'toolCallPrepare', - id = 'tool-1', - name = 'test_tool', - summary = 'Test', - argumentsText = '{}', - details = { - diff = '@@ -1 +1 @@\n-old\n+new', - }, - }, - }) - - sidebar:handle_chat_content_received({ - chatId = 'test', - content = { - type = 'toolCalled', - id = 'tool-1', - name = 'test_tool', - details = { - diff = '@@ -1 +1 @@\n-old\n+new', - }, - outputs = {}, - }, - }) - - -- Find the tool call and check if diff is expanded - local call = sidebar._tool_calls[1] - _G.diff_expanded = call and call.diff_expanded or false - ]]) - - eq(child.lua_get("_G.diff_expanded"), true) -end - -T["behavior_validation"]["diff.expanded=false causes diffs to start collapsed"] = function() - child.lua([[ - local Config = require('eca.config') - Config.override({ - windows = { - chat = { - tool_call = { - diff = { - expanded = false, - }, - }, - }, - }, - }) - - local Server = require('eca.server').new() - local State = require('eca.state').new() - local Mediator = require('eca.mediator').new(Server, State) - local Sidebar = require('eca.sidebar') - local sidebar = Sidebar.new(1, Mediator) - - sidebar:open() - - local chat = sidebar.containers.chat - vim.api.nvim_buf_set_lines(chat.bufnr, 0, -1, false, {"Line 1"}) - - -- Simulate a tool call with diff that should NOT auto-expand - sidebar:handle_chat_content_received({ - chatId = 'test', - content = { - type = 'toolCallPrepare', - id = 'tool-1', - name = 'test_tool', - summary = 'Test', - argumentsText = '{}', - details = { - diff = '@@ -1 +1 @@\n-old\n+new', - }, - }, - }) - - sidebar:handle_chat_content_received({ - chatId = 'test', - content = { - type = 'toolCalled', - id = 'tool-1', - name = 'test_tool', - details = { - diff = '@@ -1 +1 @@\n-old\n+new', - }, - outputs = {}, - }, - }) - - -- Find the tool call and check if diff is collapsed - local call = sidebar._tool_calls[1] - _G.diff_expanded = call and call.diff_expanded or false - ]]) - - eq(child.lua_get("_G.diff_expanded"), false) -end - -T["behavior_validation"]["reasoning.expanded=true causes reasoning to start expanded"] = function() - child.lua([[ - local Config = require('eca.config') - Config.override({ - windows = { - chat = { - reasoning = { - expanded = true, - }, - }, - }, - }) - - local Server = require('eca.server').new() - local State = require('eca.state').new() - local Mediator = require('eca.mediator').new(Server, State) - local Sidebar = require('eca.sidebar') - local sidebar = Sidebar.new(1, Mediator) - - sidebar:open() - - -- Simulate reasoning started event - sidebar:handle_chat_content_received({ - chatId = 'test', - content = { - type = 'reasonStarted', - id = 'reason-1', - }, - }) - - -- Check if reasoning block started expanded - local call = sidebar._reasons['reason-1'] - _G.expanded = call and call.expanded or false - ]]) - - eq(child.lua_get("_G.expanded"), true) -end - -T["behavior_validation"]["reasoning.expanded=false causes reasoning to start collapsed"] = function() - child.lua([[ - local Config = require('eca.config') - Config.override({ - windows = { - chat = { - reasoning = { - expanded = false, - }, - }, - }, - }) - - local Server = require('eca.server').new() - local State = require('eca.state').new() - local Mediator = require('eca.mediator').new(Server, State) - local Sidebar = require('eca.sidebar') - local sidebar = Sidebar.new(1, Mediator) - - sidebar:open() - - -- Simulate reasoning started event - sidebar:handle_chat_content_received({ - chatId = 'test', - content = { - type = 'reasonStarted', - id = 'reason-1', - }, - }) - - -- Check if reasoning block started collapsed - local call = sidebar._reasons['reason-1'] - _G.expanded = call and call.expanded or false - ]]) - - eq(child.lua_get("_G.expanded"), false) -end - -T["behavior_validation"]["typing.enabled=false displays text instantly"] = function() - child.lua([[ - local Config = require('eca.config') - Config.override({ - windows = { - chat = { - typing = { - enabled = false, - }, - }, - }, - }) - - local Server = require('eca.server').new() - local State = require('eca.state').new() - local Mediator = require('eca.mediator').new(Server, State) - local Sidebar = require('eca.sidebar') - local sidebar = Sidebar.new(1, Mediator) - - -- Check that stream queue was configured for instant display - local queue = sidebar._stream_queue - _G.chars_per_tick = queue.chars_per_tick - -- When typing is disabled, chars_per_tick should be a large number (instant) - _G.is_instant = _G.chars_per_tick >= 1000 - ]]) - - eq(child.lua_get("_G.is_instant"), true) -end - -T["behavior_validation"]["typing.enabled=true enables gradual display"] = function() - child.lua([[ - local Config = require('eca.config') - Config.override({ - windows = { - chat = { - typing = { - enabled = true, - chars_per_tick = 2, - tick_delay = 5, - }, - }, - }, - }) - - local Server = require('eca.server').new() - local State = require('eca.state').new() - local Mediator = require('eca.mediator').new(Server, State) - local Sidebar = require('eca.sidebar') - local sidebar = Sidebar.new(1, Mediator) - - -- Check that stream queue was configured with custom values - local queue = sidebar._stream_queue - _G.chars_per_tick = queue.chars_per_tick - _G.tick_delay = queue.tick_delay - ]]) - - eq(child.lua_get("_G.chars_per_tick"), 2) - eq(child.lua_get("_G.tick_delay"), 5) -end - --- ===== Mappings tests ===== - -T["mappings"] = MiniTest.new_set() - -T["mappings"]["submit defaults bind in normal and in insert"] = function() - child.lua([[ - local Server = require('eca.server').new() - local State = require('eca.state').new() - local Mediator = require('eca.mediator').new(Server, State) - local Sidebar = require('eca.sidebar') - local sidebar = Sidebar.new(1, Mediator) - - sidebar:open() - - local input_bufnr = sidebar.containers.input.bufnr - - -- Normalize a key string the same way nvim does internally for keymaps - local function norm(k) - return vim.api.nvim_replace_termcodes(k, true, true, true) - end - local function has_mapping(mode, key) - local target = norm(key) - for _, m in ipairs(vim.api.nvim_buf_get_keymap(input_bufnr, mode)) do - if norm(m.lhs) == target then - return true - end - end - return false - end - - _G.has_normal_cr = has_mapping("n", "") - _G.has_insert_cs = has_mapping("i", "") - ]]) - - eq(child.lua_get("_G.has_normal_cr"), true) - eq(child.lua_get("_G.has_insert_cs"), true) -end - -T["mappings"]["submit partial override preserves other mode default"] = function() - child.lua([[ - local Config = require('eca.config') - Config.override({ - mappings = { - submit = { - insert = "", - }, - }, - }) - - local Server = require('eca.server').new() - local State = require('eca.state').new() - local Mediator = require('eca.mediator').new(Server, State) - local Sidebar = require('eca.sidebar') - local sidebar = Sidebar.new(1, Mediator) - - sidebar:open() - - local input_bufnr = sidebar.containers.input.bufnr - - local function norm(k) - return vim.api.nvim_replace_termcodes(k, true, true, true) - end - local function has_mapping(mode, key) - local target = norm(key) - for _, m in ipairs(vim.api.nvim_buf_get_keymap(input_bufnr, mode)) do - if norm(m.lhs) == target then - return true - end - end - return false - end - - _G.has_normal_cr = has_mapping("n", "") -- default preserved - _G.has_insert_cx = has_mapping("i", "") -- override applied - _G.has_insert_cs = has_mapping("i", "") -- old default unbound - ]]) - - eq(child.lua_get("_G.has_normal_cr"), true) - eq(child.lua_get("_G.has_insert_cx"), true) - eq(child.lua_get("_G.has_insert_cs"), false) -end - -T["mappings"]["submit full override binds both modes"] = function() - child.lua([[ - local Config = require('eca.config') - Config.override({ - mappings = { - submit = { - normal = "", - insert = "", - }, - }, - }) - - local Server = require('eca.server').new() - local State = require('eca.state').new() - local Mediator = require('eca.mediator').new(Server, State) - local Sidebar = require('eca.sidebar') - local sidebar = Sidebar.new(1, Mediator) - - sidebar:open() - - local input_bufnr = sidebar.containers.input.bufnr - - local function norm(k) - return vim.api.nvim_replace_termcodes(k, true, true, true) - end - local function has_mapping(mode, key) - local target = norm(key) - for _, m in ipairs(vim.api.nvim_buf_get_keymap(input_bufnr, mode)) do - if norm(m.lhs) == target then - return true - end - end - return false - end - - _G.has_normal_cy = has_mapping("n", "") - _G.has_insert_cx = has_mapping("i", "") - _G.has_normal_cr = has_mapping("n", "") - ]]) - - eq(child.lua_get("_G.has_normal_cy"), true) - eq(child.lua_get("_G.has_insert_cx"), true) - eq(child.lua_get("_G.has_normal_cr"), false) -end - -T["mappings"]["welcome tip substitutes submit key placeholders"] = function() - child.lua([[ - local Config = require('eca.config') - Config.override({ - mappings = { - submit = { - normal = "", - insert = "", - }, - }, - windows = { - chat = { - welcome = { - tips = { - "normal={submit_key_normal} insert={submit_key_insert} unknown={nope}", - }, - }, - }, - }, - }) - - local Server = require('eca.server').new() - local State = require('eca.state').new() - local Mediator = require('eca.mediator').new(Server, State) - -- Force a non-empty welcome_message so the tips branch runs - function Mediator:welcome_message() return "welcome" end - - local Sidebar = require('eca.sidebar') - local sidebar = Sidebar.new(1, Mediator) - sidebar:open() - sidebar:_update_welcome_content() - - local chat_bufnr = sidebar.containers.chat.bufnr - local lines = vim.api.nvim_buf_get_lines(chat_bufnr, 0, -1, false) - _G.lines = lines - ]]) - - local lines = child.lua_get("_G.lines") - local found = false - for _, line in ipairs(lines) do - if line == "normal= insert= unknown={nope}" then - found = true - break - end - end - eq(found, true) -end - -return T diff --git a/tests/test_context_area.lua b/tests/test_context_area.lua deleted file mode 100644 index c48fee0..0000000 --- a/tests/test_context_area.lua +++ /dev/null @@ -1,440 +0,0 @@ -local MiniTest = require("mini.test") -local eq = MiniTest.expect.equality -local child = MiniTest.new_child_neovim() - -local function setup_test_environment() - -- makes easy to debug test - _G.log = {} - Logger = require("eca.logger") - Logger.test = function(message) - table.insert(_G.log, message) - end - - -- Setup a minimal environment: Server, State, Mediator, Sidebar - _G.Server = require('eca.server').new() - _G.State = require('eca.state').new() - _G.Mediator = require('eca.mediator').new(_G.Server, _G.State) - _G.Sidebar = require('eca.sidebar').new(1, _G.Mediator) - _G.Eca = require('eca') - _G.Eca.sidebars[1] = _G.Sidebar - _G.Eca.current = { sidebar = _G.Sidebar } - - _G.get_state = function() - local buf = _G.Sidebar.containers.input.bufnr - local win = _G.Sidebar.containers.input.winid - local contexts_ns = _G.Sidebar.extmarks.contexts._ns - local contexts_ids = _G.Sidebar.extmarks.contexts._id - local contexts = {} - for _, id in ipairs(contexts_ids) do - local mark = vim.api.nvim_buf_get_extmark_by_id(buf, contexts_ns, id, { details = true }) - local _, _, details = unpack(mark) - local context_name = details and details.virt_text[1][1] or nil - if context_name then - table.insert(contexts, context_name) - end - end - return { - lines = vim.api.nvim_buf_get_lines(buf, 0, -1, false), - cursor = vim.api.nvim_win_get_cursor(win), - prefix = require('eca.config').windows.input.prefix, - contexts = contexts, - } - end - - _G.set_lines = function(opts) - local buf = _G.Sidebar.containers.input.bufnr - local line_start = opts and opts.line_start or 0 - local line_end = opts and opts.line_end or -1 - local lines = opts and opts.lines or {} - vim.api.nvim_buf_set_lines(buf, line_start, line_end, true, lines) - end - - _G.set_text = function(opts) - local buf = _G.Sidebar.containers.input.bufnr - local start_row = opts and opts.start_row or 0 - local start_col = opts and opts.start_col or 0 - local end_row = opts and opts.end_row or 0 - local end_col = opts and opts.end_col or 1 - local lines = opts and opts.lines or {} - vim.api.nvim_buf_set_text(buf, start_row, start_col, end_row, end_col, lines) - end - - _G.set_cursor = function(row, col) - local win = _G.Sidebar.containers.input.winid - vim.api.nvim_set_current_win(win) - vim.api.nvim_win_set_cursor(win, { row, col }) - end - - _G.add_contexts = function(ctxs) - for _, ctx in ipairs(ctxs) do - _G.Mediator:add_context(ctx) - end - end - - -- Open the sidebar so containers are created - _G.Sidebar:open() -end - -local T = MiniTest.new_set({ - hooks = { - pre_case = function() - child.restart({ "-u", "scripts/minimal_init.lua" }) - child.lua_func(setup_test_environment) - end, - post_case = function() - -- Ensure sidebar windows cleaned - child.lua([[ if _G.Sidebar then _G.Sidebar:close() end ]]) - end, - post_once = child.stop, - }, -}) - --- Helper to flush scheduled operations (vim.schedule / vim.defer_fn) -local function flush(ms) - vim.uv.sleep(ms or 100) - child.api.nvim_eval("1") -end - -T["context area"] = MiniTest.new_set() - -T["context area"]["deletes all lines"] = function() - flush() - - local initial = child.lua_get("_G.get_state()") - - eq(initial.lines, { "@", "" }) - eq(initial.cursor, { 2, 0 }) - eq(initial.contexts, {}) - - -- Delete all lines in input buffer - child.lua("_G.set_lines({ lines = {} })") - - flush() - - local result = child.lua_get("_G.get_state()") - - eq(result.lines, { "@", "" }) - eq(result.cursor, { 2, 0 }) - eq(result.contexts, {}) -end - -T["context area"]["deletes the contexts line"] = function() - flush() - - local initial = child.lua_get("_G.get_state()") - - eq(initial.lines, { "@", "" }) - eq(initial.cursor, { 2, 0 }) - eq(initial.contexts, {}) - - -- Delete only first line - child.lua("_G.set_lines({ line_start = 0, line_end = 1, lines = {} })") - - flush() - - local result = child.lua_get("_G.get_state()") - - eq(result.lines, { "@", "" }) - eq(result.cursor, { 2, 0 }) - eq(result.contexts, {}) -end - -T["context area"]["deletes the input line"] = function() - flush() - - local initial = child.lua_get("_G.get_state()") - - eq(initial.lines, { "@", "" }) - eq(initial.cursor, { 2, 0 }) - eq(initial.contexts, {}) - - -- Delete the input line - child.lua("_G.set_lines({ line_start = 1, line_end = -1, lines = {} })") - - flush() - - local result = child.lua_get("_G.get_state()") - - eq(result.lines, { "@", "" }) - eq(result.cursor, { 2, 0 }) - eq(result.contexts, {}) -end - -T["context area"]["keep input text when deleting contexts line"] = function() - flush() - - local input_text = "text*in<>the > input#preFIX 123456 lIne" - - -- Set input text - child.lua(string.format("_G.set_lines({ line_start = 1, line_end = -1, lines = { '%s' } })", input_text)) - - flush() - - local initial = child.lua_get("_G.get_state()") - - eq(initial.lines, { "@", input_text }) - eq(initial.cursor, { 2, 0 }) - eq(initial.contexts, {}) - - -- Delete the contexts line - child.lua("_G.set_lines({ line_start = 0, line_end = 1, lines = {} })") - - flush() - - local result = child.lua_get("_G.get_state()") - - eq(result.lines, { "@", input_text }) - eq(result.cursor, { 2, #input_text }) - eq(result.contexts, {}) -end - -T["context area"]["keep multiple lines text input when removing the first context"] = function() - flush() - - local input_text_first_line = "text*in<>the > input#preFIX 123456 lIne" - local input_text_second_line = "text in the 2nd line after input prefix line" - - -- Set input text - child.lua(string.format("_G.set_lines({ line_start = 1, line_end = -1, lines = { '%s', '%s' } })", input_text_first_line, input_text_second_line)) - - -- Add context - child.lua([[_G.add_contexts({ - { type = 'file', data = { path = '/tmp/sidebar.lua' } } - })]]) - - flush() - - local initial = child.lua_get("_G.get_state()") - - eq(initial.lines, { "@@", input_text_first_line, input_text_second_line }) - eq(initial.cursor, { 3, #input_text_second_line }) - eq(initial.contexts, { "sidebar.lua " }) - - -- Set cursor to first context placeholder - child.lua("_G.set_cursor(1, 0)") - - -- Delete the context placeholder in contexts line - child.lua("_G.set_text({ start_row = 0, start_col = 0, end_row = 0, end_col = 1, lines = {} })") - - flush() - - -- eq(child.lua_get("_G.log"), {}) - - local result = child.lua_get("_G.get_state()") - - eq(result.lines, { "@", input_text_first_line, input_text_second_line }) - eq(result.cursor, { 3, #input_text_second_line }) - eq(result.contexts, {}) -end - -T["context area"]["remove all contexts when deleting the contexts line"] = function() - flush() - - local input_text_first_line = "text*in<>the > input#preFIX 123456 lIne" - local input_text_second_line = "text in the 2nd line after input prefix line" - local input_text_fourth_line = "another text in the 4 line (note that line 3 is only with a newline)" - - -- Set input text - child.lua(string.format("_G.set_lines({ line_start = 1, line_end = -1, lines = { '%s', '%s', '', '%s' } })", input_text_first_line, input_text_second_line, input_text_fourth_line)) - - -- Add context - child.lua([[_G.add_contexts({ - { type = 'file', data = { path = '/tmp/sidebar.lua' } }, - { type = 'file', data = { path = '/tmp/sidebar.lua', lines_range = {line_start = 25, line_end = 50 } } } - })]]) - - flush() - - local initial = child.lua_get("_G.get_state()") - - eq(initial.lines, { "@@@", input_text_first_line, input_text_second_line, "", input_text_fourth_line }) - eq(initial.cursor, { 5, #input_text_fourth_line }) - eq(initial.contexts, { "sidebar.lua ", "sidebar.lua:25-50 " }) - - -- Delete the contexts line - child.lua("_G.set_lines({ line_start = 0, line_end = 1, lines = {} })") - - flush() - - local result = child.lua_get("_G.get_state()") - - eq(result.lines, { "@", input_text_first_line, input_text_second_line, "", input_text_fourth_line }) - eq(result.cursor, { 5, #input_text_fourth_line }) - eq(result.contexts, {}) -end - -T["context area"]["remove one specific context when multiple contexts are present"] = function() - flush() - - local input_text_first_line = "text*in<>the > input#preFIX 123456 lIne" - local input_text_second_line = "text in the 2nd line after input prefix line" - local input_text_fourth_line = "another text in the 4 line (note that line 3 is only with a newline)" - - -- Set input text - child.lua(string.format("_G.set_lines({ line_start = 1, line_end = -1, lines = { '%s', '%s', '', '%s' } })", input_text_first_line, input_text_second_line, input_text_fourth_line)) - - -- Add context - child.lua([[_G.add_contexts({ - { type = 'file', data = { path = '/tmp/sidebar.lua' } }, - { type = 'file', data = { path = '/tmp/sidebar.lua', lines_range = { line_start = 25, line_end = 50 } } }, - { type = 'file', data = { path = '/tmp/server.lua' } } - })]]) - - flush() - - local initial = child.lua_get("_G.get_state()") - - eq(initial.lines, { "@@@@", input_text_first_line, input_text_second_line, "", input_text_fourth_line }) - eq(initial.cursor, { 5, #input_text_fourth_line }) - eq(initial.contexts, { "sidebar.lua ", "sidebar.lua:25-50 ", "server.lua " }) - - -- Set cursor to the second context placeholder - child.lua("_G.set_cursor(1, 1)") - - -- Delete the context placeholder in contexts line - child.lua("_G.set_text({ start_row = 0, start_col = 1, end_row = 0, end_col = 2, lines = {} })") - - flush() - - local result = child.lua_get("_G.get_state()") - - eq(result.lines, { "@@@", input_text_first_line, input_text_second_line, "", input_text_fourth_line }) - eq(result.cursor, { 5, #input_text_fourth_line }) - eq(result.contexts, { "sidebar.lua ", "server.lua " }) -end - -T["context area"]["remove contexts one by one in an arbitrary order while preserving input"] = function() - flush() - - local input_text_first_line = "text*in<>the > input#preFIX 123456 lIne" - local input_text_second_line = "text in the 2nd line after input prefix line" - local input_text_fourth_line = "another text in the 4 line (note that line 3 is only with a newline)" - - -- Set input text - child.lua(string.format("_G.set_lines({ line_start = 1, line_end = -1, lines = { '%s', '%s', '', '%s' } })", input_text_first_line, input_text_second_line, input_text_fourth_line)) - - -- Add context - child.lua([[_G.add_contexts({ - { type = 'file', data = { path = '/dev/chat.lua' } }, - { type = 'file', data = { path = '/tmp/sidebar.lua' } }, - { type = 'file', data = { path = '/tmp/sidebar.lua', lines_range = { line_start = 25, line_end = 50 } } }, - { type = 'file', data = { path = '/dev/server.lua', lines_range = { line_start = 999, line_end = 1200 } } }, - { type = 'file', data = { path = '/dev/server.lua' } }, - })]]) - - flush() - - local initial = child.lua_get("_G.get_state()") - - eq(initial.lines, { "@@@@@@", input_text_first_line, input_text_second_line, "", input_text_fourth_line }) - eq(initial.cursor, { 5, #input_text_fourth_line }) - eq(initial.contexts, { "chat.lua ", "sidebar.lua ", "sidebar.lua:25-50 ", "server.lua:999-1200 ", "server.lua " }) - - -- Set cursor to the second context placeholder - child.lua("_G.set_cursor(1, 1)") - - -- Delete the context placeholder in contexts line - child.lua("_G.set_text({ start_row = 0, start_col = 1, end_row = 0, end_col = 2, lines = {} })") - - flush() - - local result = child.lua_get("_G.get_state()") - - eq(result.lines, { "@@@@@", input_text_first_line, input_text_second_line, "", input_text_fourth_line }) - eq(result.cursor, { 5, #input_text_fourth_line }) - eq(result.contexts, { "chat.lua ", "sidebar.lua:25-50 ", "server.lua:999-1200 ", "server.lua " }) - - -- Set cursor to the second context placeholder - child.lua("_G.set_cursor(1, 3)") - - -- Delete the context placeholder in contexts line - child.lua("_G.set_text({ start_row = 0, start_col = 3, end_row = 0, end_col = 4, lines = {} })") - - flush() - - local result_2 = child.lua_get("_G.get_state()") - - eq(result_2.lines, { "@@@@", input_text_first_line, input_text_second_line, "", input_text_fourth_line }) - eq(result_2.cursor, { 5, #input_text_fourth_line }) - eq(result_2.contexts, { "chat.lua ", "sidebar.lua:25-50 ", "server.lua:999-1200 " }) - - -- Set cursor to the second context placeholder - child.lua("_G.set_cursor(1, 0)") - - -- Delete the context placeholder in contexts line - child.lua("_G.set_text({ start_row = 0, start_col = 0, end_row = 0, end_col = 1, lines = {} })") - - flush() - - local result_3 = child.lua_get("_G.get_state()") - - eq(result_3.lines, { "@@@", input_text_first_line, input_text_second_line, "", input_text_fourth_line }) - eq(result_3.cursor, { 5, #input_text_fourth_line }) - eq(result_3.contexts, { "sidebar.lua:25-50 ", "server.lua:999-1200 " }) - - -- Delete the contexts line - child.lua("_G.set_lines({ line_start = 0, line_end = 1, lines = {} })") - - flush() - - local result_4 = child.lua_get("_G.get_state()") - - eq(result_4.lines, { "@", input_text_first_line, input_text_second_line, "", input_text_fourth_line }) - eq(result_4.cursor, { 5, #input_text_fourth_line }) - eq(result_4.contexts, {}) -end - -T["context area"]["displays filename in context area and expands path in sent message"] = function() - flush() - - local rel_path = "lua/eca/sidebar.lua" - local abs_path = child.lua_get("vim.fn.fnamemodify(..., ':p')", { rel_path }) - local tail = child.lua_get("vim.fn.fnamemodify(..., ':t')", { rel_path }) .. " " - - -- Add a context with relative path; context area should show only the - -- filename (tail), not the full path. - child.lua([[_G.add_contexts({ - { type = 'file', data = { path = 'lua/eca/sidebar.lua' } }, - })]]) - - flush() - - local state = child.lua_get("_G.get_state()") - - -- Contexts in the area should use the tail of the path - eq(state.contexts, { tail }) - - -- Mock server on mediator so we don't start a real process. Capture - -- the last request instead of sending anything. - child.lua([[ - _G.last_request = nil - _G.Mediator.server = { - is_running = function() - return true - end, - send_request = function(_, method, params, callback) - _G.last_request = { method = method, params = params } - if callback then - callback(nil, {}) - end - end, - } - ]]) - - -- Send a message that references the same relative path using the - -- @path shorthand. Sidebar should expand it to an absolute path - -- before sending to the (mocked) server. - child.lua("_G.Sidebar:_send_message('please check @' .. '" .. rel_path .. "')") - - local req = child.lua_get("_G.last_request") - eq(req.method, "chat/prompt") - - local msg = req.params.message - local expected = "please check @" .. abs_path - - -- Message sent to the server must contain the absolute path and no - -- longer contain the original relative path. - eq(msg, expected) -end - -return T diff --git a/tests/test_context_commands.lua b/tests/test_context_commands.lua deleted file mode 100644 index 23ef1fe..0000000 --- a/tests/test_context_commands.lua +++ /dev/null @@ -1,403 +0,0 @@ -local MiniTest = require("mini.test") -local eq = MiniTest.expect.equality -local child = MiniTest.new_child_neovim() - -local function flush(ms) - vim.uv.sleep(ms or 100) - child.api.nvim_eval("1") -end - --- Returns the registered command's name, or nil if not registered. Filters --- server-side so the function-valued `callback` field (present on 0.12+) --- does not cross the MiniTest msgpack boundary. -local function cmd_registered_name(name) - return child.lua_get(string.format( - "(vim.api.nvim_get_commands({})[%q] or {}).name", - name - )) -end - -local function setup_test_environment() - child.lua([[ - local Eca = require('eca') - - -- Setup plugin with no auto server or keymaps so tests are - -- deterministic and don't spawn external processes. - Eca.setup({ - behavior = { - auto_start_server = false, - auto_set_keymaps = false, - }, - }) - - -- Ensure we have a sidebar/mediator for the current tab - local tab = vim.api.nvim_get_current_tabpage() - Eca._init(tab) - Eca.open_sidebar({}) - - -- Fake server so eca.api thinks it is running but we never - -- actually start the external binary. - if Eca.server then - Eca.server.is_running = function() - return true - end - else - Eca.server = { - is_running = function() - return true - end, - } - end - - -- Clear any existing contexts before each test - if Eca.mediator then - Eca.mediator:clear_contexts() - end - - -- Capture Logger.notify calls (used by deprecated commands and - -- some API helpers) so we can assert on deprecation messages. - local Logger = require('eca.logger') - _G.Logger = Logger - _G.original_logger_notify = Logger.notify - _G.captured_notifications = {} - - Logger.notify = function(msg, level, opts) - level = level or vim.log.levels.INFO - opts = opts or {} - - table.insert(_G.captured_notifications, { - message = msg, - level = level, - opts = opts, - }) - - if _G.original_logger_notify then - _G.original_logger_notify(msg, level, opts) - end - end - - -- Stub vim.ui.input so we can simulate user input in tests - vim.ui = vim.ui or {} - _G.__test_next_input = nil - vim.ui.input = function(opts, on_confirm) - if on_confirm then - on_confirm(_G.__test_next_input) - end - end - ]]) -end - -local T = MiniTest.new_set({ - hooks = { - pre_case = function() - child.restart({ "-u", "scripts/minimal_init.lua" }) - setup_test_environment() - end, - post_once = child.stop, - }, -}) - -local function contexts_count() - return child.lua_get("#require('eca').mediator:contexts()") -end - -local function get_contexts() - return child.lua_get("require('eca').mediator:contexts()") -end - --- EcaChatAddFile ----------------------------------------------------------- - -T["EcaChatAddFile"] = MiniTest.new_set() - -T["EcaChatAddFile"]["command is registered"] = function() - eq(cmd_registered_name("EcaChatAddFile"), "EcaChatAddFile") -end - -T["EcaChatAddFile"]["adds current file as context when no args"] = function() - child.cmd("edit README.md") - local abs = child.lua_get("vim.fn.fnamemodify('README.md', ':p')") - - eq(contexts_count(), 0) - - child.cmd("EcaChatAddFile") - flush() - - local contexts = get_contexts() - eq(#contexts, 1) - eq(contexts[1].type, "file") - eq(contexts[1].data.path, abs) -end - -T["EcaChatAddFile"]["adds provided path as context when args are given"] = function() - local filename = "README.md" - local expected_abs = child.lua_get("vim.fn.fnamemodify(..., ':p')", { filename }) - - eq(contexts_count(), 0) - - child.cmd("EcaChatAddFile " .. filename) - flush() - - local contexts = get_contexts() - eq(#contexts, 1) - eq(contexts[1].type, "file") - eq(contexts[1].data.path, expected_abs) -end - --- Deprecated EcaAddFile ---------------------------------------------------- - -T["EcaAddFile"] = MiniTest.new_set() - -T["EcaAddFile"]["command is registered"] = function() - eq(cmd_registered_name("EcaAddFile"), "EcaAddFile") -end - -T["EcaAddFile"]["shows deprecation notice when called"] = function() - child.cmd("EcaAddFile") - flush() - - local notifications = child.lua_get("_G.captured_notifications") - eq(#notifications > 0, true) - eq(notifications[1].message, "EcaAddFile is deprecated. Use EcaChatAddFile instead.") - eq(notifications[1].level, child.lua_get("vim.log.levels.WARN")) -end - --- EcaChatRemoveFile -------------------------------------------------------- - -T["EcaChatRemoveFile"] = MiniTest.new_set() - -T["EcaChatRemoveFile"]["command is registered"] = function() - eq(cmd_registered_name("EcaChatRemoveFile"), "EcaChatRemoveFile") -end - -T["EcaChatRemoveFile"]["removes current file context when no args"] = function() - child.cmd("edit README.md") - - child.cmd("EcaChatAddFile") - flush() - eq(contexts_count(), 1) - - child.cmd("EcaChatRemoveFile") - flush() - - eq(contexts_count(), 0) -end - -T["EcaChatRemoveFile"]["removes context for provided path when args are given"] = function() - local filename = "README.md" - - child.cmd("edit README.md") - child.cmd("EcaChatAddFile") - flush() - eq(contexts_count(), 1) - - child.cmd("EcaChatRemoveFile " .. filename) - flush() - - eq(contexts_count(), 0) -end - --- Deprecated EcaRemoveContext --------------------------------------------- - -T["EcaRemoveContext"] = MiniTest.new_set() - -T["EcaRemoveContext"]["command is registered"] = function() - eq(cmd_registered_name("EcaRemoveContext"), "EcaRemoveContext") -end - -T["EcaRemoveContext"]["shows deprecation notice when called"] = function() - child.cmd("EcaRemoveContext") - flush() - - local notifications = child.lua_get("_G.captured_notifications") - eq(#notifications > 0, true) - eq(notifications[1].message, "EcaRemoveContext is deprecated. Use EcaChatRemoveFile instead.") - eq(notifications[1].level, child.lua_get("vim.log.levels.WARN")) -end - -T["EcaChatAddSelection"] = MiniTest.new_set() - -T["EcaChatAddSelection"]["command is registered"] = function() - eq(cmd_registered_name("EcaChatAddSelection"), "EcaChatAddSelection") -end - -T["EcaChatAddSelection"]["adds a ranged file context based on visual selection"] = function() - child.cmd("edit README.md") - local abs = child.lua_get("vim.fn.fnamemodify('README.md', ':p')") - - -- Manually set visual selection marks for lines 1-2 to avoid headless - -- visual-mode quirks - child.lua([[ - local bufnr = vim.api.nvim_get_current_buf() - vim.fn.setpos("'<", {bufnr, 1, 1, 0}) - vim.fn.setpos("'>", {bufnr, 2, 1, 0}) - ]]) - - eq(contexts_count(), 0) - - child.cmd("EcaChatAddSelection") - flush(200) - - local contexts = get_contexts() - eq(#contexts, 1) - eq(contexts[1].type, "file") - eq(contexts[1].data.path, abs) - eq(contexts[1].data.lines_range.line_start, 1) - eq(contexts[1].data.lines_range.line_end, 2) -end - --- Deprecated EcaAddSelection ----------------------------------------------- - -T["EcaAddSelection"] = MiniTest.new_set() - -T["EcaAddSelection"]["command is registered"] = function() - eq(cmd_registered_name("EcaAddSelection"), "EcaAddSelection") -end - -T["EcaAddSelection"]["shows deprecation notice when called"] = function() - child.cmd("EcaAddSelection") - flush(200) - - local notifications = child.lua_get("_G.captured_notifications") - eq(#notifications > 0, true) - eq(notifications[1].message, "EcaAddSelection is deprecated. Use EcaChatAddSelection instead.") - eq(notifications[1].level, child.lua_get("vim.log.levels.WARN")) -end - -T["EcaChatAddUrl"] = MiniTest.new_set() - -T["EcaChatAddUrl"]["command is registered"] = function() - eq(cmd_registered_name("EcaChatAddUrl"), "EcaChatAddUrl") -end - -T["EcaChatAddUrl"]["adds web context and truncates name based on config"] = function() - -- Use a small max length to make truncation easy to assert on - child.lua([[require('eca.config').override({ - windows = { - input = { - web_context_max_len = 10, - }, - }, - })]]) - - local long_url = "https://example.com/some/really/long/path" - - -- Provide the URL for the stubbed vim.ui.input - child.lua(string.format("_G.__test_next_input = %q", long_url)) - - eq(contexts_count(), 0) - - child.cmd("EcaChatAddUrl") - flush(200) - - local contexts = get_contexts() - eq(#contexts, 1) - eq(contexts[1].type, "web") - eq(contexts[1].data.path, long_url) - - -- Ensure the context name shown in the input buffer is truncated - child.lua([[ - local eca = require('eca') - local sidebar = eca.current.sidebar - if not sidebar or not sidebar.containers or not sidebar.containers.input then - _G.__test_displayed_context = nil - return - end - local input = sidebar.containers.input - local ns = vim.api.nvim_create_namespace('extmarks_contexts') - local marks = vim.api.nvim_buf_get_extmarks(input.bufnr, ns, 0, -1, { details = true }) - if not marks or #marks == 0 then - _G.__test_displayed_context = nil - return - end - local details = marks[1][4] - if not details or not details.virt_text or #details.virt_text == 0 then - _G.__test_displayed_context = nil - return - end - _G.__test_displayed_context = details.virt_text[1][1] - ]]) - - local displayed = child.lua_get("_G.__test_displayed_context") - local expected = long_url:sub(1, 7) .. "... " - eq(displayed, expected) -end - -T["EcaChatListContexts"] = MiniTest.new_set() - -T["EcaChatListContexts"]["command is registered"] = function() - eq(cmd_registered_name("EcaChatListContexts"), "EcaChatListContexts") -end - -T["EcaChatListContexts"]["runs without modifying contexts"] = function() - child.cmd("edit README.md") - child.cmd("EcaChatAddFile") - flush() - - local before = contexts_count() - child.cmd("EcaChatListContexts") - flush() - local after = contexts_count() - - eq(after, before) -end - --- Deprecated EcaListContexts ----------------------------------------------- - -T["EcaListContexts"] = MiniTest.new_set() - -T["EcaListContexts"]["command is registered"] = function() - eq(cmd_registered_name("EcaListContexts"), "EcaListContexts") -end - -T["EcaListContexts"]["shows deprecation notice when called"] = function() - child.cmd("EcaListContexts") - flush() - - local notifications = child.lua_get("_G.captured_notifications") - eq(#notifications > 0, true) - eq(notifications[1].message, "EcaListContexts is deprecated. Use EcaChatListContexts instead.") - eq(notifications[1].level, child.lua_get("vim.log.levels.WARN")) - -- No explicit level is passed in the command for this deprecation, - -- so we only assert on the message. -end - -T["EcaChatClearContexts"] = MiniTest.new_set() - -T["EcaChatClearContexts"]["command is registered"] = function() - eq(cmd_registered_name("EcaChatClearContexts"), "EcaChatClearContexts") -end - -T["EcaChatClearContexts"]["clears all contexts"] = function() - child.cmd("edit README.md") - child.cmd("EcaChatAddFile") - child.cmd("EcaChatAddFile") - flush() - eq(contexts_count() > 0, true) - - child.cmd("EcaChatClearContexts") - flush() - - eq(contexts_count(), 0) -end - --- Deprecated EcaClearContexts ---------------------------------------------- - -T["EcaClearContexts"] = MiniTest.new_set() - -T["EcaClearContexts"]["command is registered"] = function() - eq(cmd_registered_name("EcaClearContexts"), "EcaClearContexts") -end - -T["EcaClearContexts"]["shows deprecation notice when called"] = function() - child.cmd("EcaClearContexts") - flush() - - local notifications = child.lua_get("_G.captured_notifications") - eq(#notifications > 0, true) - eq(notifications[1].message, "EcaClearContexts is deprecated. Use EcaChatClearContexts instead.") - eq(notifications[1].level, child.lua_get("vim.log.levels.WARN")) - -- No explicit level is passed in the command for this deprecation, - -- so we only assert on the message. -end - -return T diff --git a/tests/test_eca.lua b/tests/test_eca.lua deleted file mode 100644 index faab82a..0000000 --- a/tests/test_eca.lua +++ /dev/null @@ -1,36 +0,0 @@ -local MiniTest = require("mini.test") -local T = MiniTest.new_set() - --- Test that the plugin loads without errors -T["loads without error"] = function() - MiniTest.expect.no_error(function() - require("eca") - end) -end - --- Test basic config functionality -T["config"] = MiniTest.new_set() - -T["config"]["has default values"] = function() - local config = require("eca.config") - MiniTest.expect.equality(type(config), "table") -end - -T["config"]["has usage window defaults"] = function() - local config = require("eca.config") - MiniTest.expect.equality( - config.options.windows.usage.format, - "{session_tokens_short} / {limit_tokens_short} (${session_cost})" - ) -end - --- Test utilities -T["utils"] = MiniTest.new_set() - -T["utils"]["module exists"] = function() - MiniTest.expect.no_error(function() - require("eca.utils") - end) -end - -return T diff --git a/tests/test_editor_diagnostics.lua b/tests/test_editor_diagnostics.lua deleted file mode 100644 index 240eff2..0000000 --- a/tests/test_editor_diagnostics.lua +++ /dev/null @@ -1,123 +0,0 @@ -local MiniTest = require("mini.test") -local eq = MiniTest.expect.equality -local child = MiniTest.new_child_neovim() - -local T = MiniTest.new_set({ - hooks = { - pre_case = function() - child.restart({ "-u", "scripts/minimal_init.lua" }) - end, - post_once = child.stop, - }, -}) - -T["editor"] = MiniTest.new_set() - -T["editor"]["returns empty diagnostics when buffer not found"] = function() - local diagnostics = child.lua_get([[ - require("eca.editor").handle_request({ - method = "editor/getDiagnostics", - params = { uri = "file:///nonexistent/file.lua" }, - }).diagnostics - ]]) - eq(#diagnostics, 0) -end - -T["editor"]["maps severity levels correctly"] = function() - child.lua([[ - local bufnr = vim.api.nvim_create_buf(false, true) - vim.api.nvim_buf_set_name(bufnr, "/tmp/eca_test_sev.lua") - local ns = vim.api.nvim_create_namespace("eca_sev") - vim.diagnostic.set(ns, bufnr, { - { lnum=0, col=0, end_lnum=0, end_col=1, message="err", severity=vim.diagnostic.severity.ERROR }, - { lnum=1, col=0, end_lnum=1, end_col=1, message="warn", severity=vim.diagnostic.severity.WARN }, - { lnum=2, col=0, end_lnum=2, end_col=1, message="info", severity=vim.diagnostic.severity.INFO }, - { lnum=3, col=0, end_lnum=3, end_col=1, message="hint", severity=vim.diagnostic.severity.HINT }, - }) - local res = require("eca.editor").handle_request({ - method = "editor/getDiagnostics", - params = { uri = "file:///tmp/eca_test_sev.lua" }, - }) - _G.sev_result = {} - for _, d in ipairs(res.diagnostics) do - table.insert(_G.sev_result, d.severity) - end - vim.api.nvim_buf_delete(bufnr, { force = true }) - ]]) - eq(child.lua_get("_G.sev_result[1]"), "error") - eq(child.lua_get("_G.sev_result[2]"), "warning") - eq(child.lua_get("_G.sev_result[3]"), "information") - eq(child.lua_get("_G.sev_result[4]"), "hint") -end - -T["editor"]["includes range and message fields"] = function() - child.lua([[ - local bufnr = vim.api.nvim_create_buf(false, true) - vim.api.nvim_buf_set_name(bufnr, "/tmp/eca_test_fields.lua") - local ns = vim.api.nvim_create_namespace("eca_fields") - vim.diagnostic.set(ns, bufnr, { - { lnum=5, col=3, end_lnum=5, end_col=10, message="test error", severity=vim.diagnostic.severity.ERROR, source="myls" }, - }) - local res = require("eca.editor").handle_request({ - method = "editor/getDiagnostics", - params = { uri = "file:///tmp/eca_test_fields.lua" }, - }) - _G.field_result = res.diagnostics[1] - vim.api.nvim_buf_delete(bufnr, { force = true }) - ]]) - eq(child.lua_get("_G.field_result.message"), "test error") - eq(child.lua_get("_G.field_result.range.start.line"), 5) - eq(child.lua_get("_G.field_result.range.start.character"), 3) - eq(child.lua_get([[_G.field_result.range["end"].line]]), 5) - eq(child.lua_get([[_G.field_result.range["end"].character]]), 10) -end - -T["editor"]["falls back to information for unknown severity"] = function() - child.lua([[ - local bufnr = vim.api.nvim_create_buf(false, true) - vim.api.nvim_buf_set_name(bufnr, "/tmp/eca_test_fallback.lua") - local ns = vim.api.nvim_create_namespace("eca_fallback") - vim.diagnostic.set(ns, bufnr, { - { lnum=0, col=0, end_lnum=0, end_col=1, message="x", severity=99 }, - }) - local res = require("eca.editor").handle_request({ - method = "editor/getDiagnostics", - params = { uri = "file:///tmp/eca_test_fallback.lua" }, - }) - _G.fallback_sev = res.diagnostics[1] and res.diagnostics[1].severity - vim.api.nvim_buf_delete(bufnr, { force = true }) - ]]) - eq(child.lua_get("_G.fallback_sev"), "information") -end - -T["editor"]["uri field is present on each diagnostic"] = function() - child.lua([[ - local bufnr = vim.api.nvim_create_buf(false, true) - vim.api.nvim_buf_set_name(bufnr, "/tmp/eca_test_uri.lua") - local ns = vim.api.nvim_create_namespace("eca_uri") - vim.diagnostic.set(ns, bufnr, { - { lnum=0, col=0, end_lnum=0, end_col=1, message="e1", severity=vim.diagnostic.severity.ERROR }, - { lnum=1, col=0, end_lnum=1, end_col=1, message="e2", severity=vim.diagnostic.severity.WARN }, - }) - local res = require("eca.editor").handle_request({ - method = "editor/getDiagnostics", - params = { uri = "file:///tmp/eca_test_uri.lua" }, - }) - _G.uri_result = {} - for _, d in ipairs(res.diagnostics) do - table.insert(_G.uri_result, d.uri) - end - vim.api.nvim_buf_delete(bufnr, { force = true }) - ]]) - eq(child.lua_get("_G.uri_result[1]"), "file:///tmp/eca_test_uri.lua") - eq(child.lua_get("_G.uri_result[2]"), "file:///tmp/eca_test_uri.lua") -end - -T["editor"]["returns nil for unknown method"] = function() - local is_nil = child.lua_get([[ - require("eca.editor").handle_request({ method = "editor/unknown", params = {} }) == nil - ]]) - eq(is_nil, true) -end - -return T diff --git a/tests/test_highlights.lua b/tests/test_highlights.lua deleted file mode 100644 index 9ddfd3b..0000000 --- a/tests/test_highlights.lua +++ /dev/null @@ -1,27 +0,0 @@ -local MiniTest = require("mini.test") -local eq = MiniTest.expect.equality -local child = MiniTest.new_child_neovim() - -local T = MiniTest.new_set({ - hooks = { - pre_case = function() - child.restart({ "-u", "scripts/minimal_init.lua" }) - child.lua([[require('eca.highlights').setup()]]) - end, - post_once = child.stop, - }, -}) - -T["highlights"] = MiniTest.new_set() - -T["highlights"]["defines ECA highlight groups used in sidebar"] = function() - local ok_label = child.lua_get("pcall(vim.api.nvim_get_hl, 0, { name = 'EcaLabel' })") - local ok_tool = child.lua_get("pcall(vim.api.nvim_get_hl, 0, { name = 'EcaToolCall' })") - local ok_link = child.lua_get("pcall(vim.api.nvim_get_hl, 0, { name = 'EcaHyperlink' })") - - eq(ok_label, true) - eq(ok_tool, true) - eq(ok_link, true) -end - -return T diff --git a/tests/test_logging.lua b/tests/test_logging.lua deleted file mode 100644 index 189d78a..0000000 --- a/tests/test_logging.lua +++ /dev/null @@ -1,483 +0,0 @@ -local MiniTest = require("mini.test") -local child = MiniTest.new_child_neovim() -local eq = MiniTest.expect.equality -local new_set = MiniTest.new_set - -local expect_match = MiniTest.new_expectation("string matching", function(str, pattern) - return str:find(pattern) ~= nil -end, function(str, pattern) - return string.format("Pattern: %s\nObserved string: %s", vim.inspect(pattern), str) -end) - -local expect_no_match = MiniTest.new_expectation("string not matching", function(str, pattern) - return str:find(pattern) == nil -end, function(str, pattern) - return string.format("Pattern: %s\nObserved string: %s", vim.inspect(pattern), str) -end) - -local setup_test_environment = function() - child.lua([[ - _G.test_log_dir = vim.fn.tempname() .. '_logs' - vim.fn.mkdir(_G.test_log_dir, 'p') - - _G.captured_notifications = {} - local original_notify = vim.notify - vim.notify = function(msg, level, opts) - table.insert(_G.captured_notifications, { - message = msg, - level = level, - opts = opts or {} - }) - return original_notify(msg, level, opts) - end - ]]) -end - -local cleanup_test_files = function() - child.lua([[ - if _G.test_log_dir then - vim.fn.delete(_G.test_log_dir, 'rf') - end - ]]) -end - ---- Get absolute path for a test log file within the temporary test directory ---- ---- @param filename string The filename within the test directory (e.g., "test.log", "nested/dir/file.log") ---- @return string Absolute path to the test file -local get_test_file_path = function(filename) - return child.lua_get("_G.test_log_dir") .. "/" .. filename -end - ---- Setup the Logger module with a given configuration in the child Neovim process ---- Use this when you need custom logger configuration that doesn't fit the common patterns ---- covered by setup_logger_with_file(). ---- ---- @param config table Logger configuration options (level, file, display, etc.) -local setup_logger = function(config) - child.lua("Logger.setup(...)", { config }) -end - ---- Setup logger with a test file and common defaults, with optional overrides ---- ---- @param filename string The log filename within the test directory ---- @param overrides? table Optional config overrides (level, display, etc.) -local setup_logger_with_file = function(filename, overrides) - local config = vim.tbl_extend("force", { - level = vim.log.levels.INFO, - file = get_test_file_path(filename), - }, overrides or {}) - setup_logger(config) -end - ---- Read entire contents of a test log file as a single string ---- ---- @param relative_path string Path relative to test directory, should start with "/" (e.g., "/test.log") ---- @return string Complete file contents joined with newlines, or empty string if file not found -local read_log_file = function(relative_path) - return child.lua([[ - local log_path = _G.test_log_dir .. ']] .. relative_path .. [[' - if vim.fn.filereadable(log_path) == 1 then - return table.concat(vim.fn.readfile(log_path), '\n') - end - return '' - ]]) -end - ---- Read only the first line of a test log file ---- ---- @param relative_path string Path relative to test directory, should start with "/" (e.g., "/test.log") ---- @return string First line of the file, or empty string if file not found or empty ---- ---- Example usage: ---- local first_line = read_log_first_line("/format_test.log") ---- expect_match(first_line, "%[%d%d%d%d%-%d%d%-%d%d %d%d:%d%d:%d%d%]") -- timestamp format -local read_log_first_line = function(relative_path) - return child.lua([[ - local log_path = _G.test_log_dir .. ']] .. relative_path .. [[' - if vim.fn.filereadable(log_path) == 1 then - return vim.fn.readfile(log_path)[1] or '' - end - return '' - ]]) -end - ---- Wait for async logging operations to complete ---- ---- @param ms? number Milliseconds to wait (default: 100) ---- -local wait_for_async = function(ms) - vim.uv.sleep(ms or 100) -end - ---- Common test loop: sconfigure logger → run logging code → verify file contents ---- ---- @param filename string The log filename within the test directory (no leading slash) ---- @param log_commands string Lua code to execute in child process (usually Logger.* calls) ---- @param config_overrides? table Optional logger config overrides (level, notify, etc.) ---- @return string Complete log file contents for assertion testing ---- ---- Example usage: ---- -- basic ---- local contents = log_and_read("test.log", "Logger.info('hello world')") ---- expect_match(contents, "hello world") ---- ---- -- Test with custom log level ---- local contents = log_and_read("debug.log", [[ ---- Logger.debug('debug msg') ---- Logger.info('info msg') ---- ]], { level = vim.log.levels.DEBUG }) ---- ---- -- Test multiple log calls ---- local contents = log_and_read("multi.log", [[ ---- Logger.warn('warning') ---- Logger.error('error') ---- ]]) -local log_and_read = function(filename, log_commands, config_overrides) - setup_logger_with_file(filename, config_overrides) - child.lua(log_commands) - wait_for_async() - return read_log_file("/" .. filename) -end - -local T = new_set({ - hooks = { - pre_case = function() - child.restart({ "-u", "scripts/minimal_init.lua" }) - child.lua([[Logger = require('eca.logger')]]) - setup_test_environment() - end, - post_case = cleanup_test_files, - post_once = child.stop, - }, -}) - -T["configuration"] = new_set() - -T["configuration"]["default configuration"] = function() - child.lua([[ - Logger.setup() - ]]) - - eq(child.lua_get("Logger.get_log_path()"), vim.fn.stdpath("state") .. "/eca.log") - eq(child.lua_get("Logger.config.level"), vim.log.levels.INFO) - eq(child.lua_get("Logger.config.display"), "split") -end - -T["configuration"]["file logging with default path"] = function() - setup_logger({ - level = vim.log.levels.INFO, - }) - - local log_path = child.lua_get("Logger.get_log_path()") - eq(vim.fn.stdpath("state") .. "/eca.log", log_path) -end - -T["configuration"]["file logging with custom path"] = function() - setup_logger({ - level = vim.log.levels.INFO, - file = get_test_file_path("custom.log"), - }) - - local log_path = child.lua_get("Logger.get_log_path()") - expect_match(log_path, "custom%.log$") -end - -T["log_levels"] = new_set() - -T["log_levels"]["respects minimum log level"] = function() - local contents = log_and_read( - "level_test.log", - [[ - Logger.debug('debug message') - Logger.info('info message') - Logger.warn('warn message') - Logger.error('error message') - ]], - { level = vim.log.levels.WARN } - ) - - expect_no_match(contents, "DEBUG") - expect_no_match(contents, "INFO") - expect_match(contents, "WARN") - expect_match(contents, "ERROR") -end - -T["log_levels"]["invalid level defaults to info"] = function() - local contents = log_and_read( - "invalid_level.log", - [[ - Logger.debug('debug message') - Logger.info('info message') - ]], - { level = 999 } - ) - - expect_no_match(contents, "DEBUG") - expect_no_match(contents, "INFO") -end - -T["file_logging"] = new_set() - -T["file_logging"]["writes to file with correct format"] = function() - setup_logger_with_file("format_test.log") - child.lua([[Logger.info('test message')]]) - wait_for_async() - - local contents = read_log_first_line("/format_test.log") - - expect_match(contents, "%[%d%d%d%d%-%d%d%-%d%d %d%d:%d%d:%d%d%]") - expect_match(contents, "INFO") - expect_match(contents, "test message") -end - -T["file_logging"]["creates parent directory"] = function() - setup_logger({ - level = vim.log.levels.INFO, - file = get_test_file_path("nested/dir/test.log"), - }) - - child.lua([[Logger.info('nested test')]]) - - wait_for_async() - - local dir_exists = child.lua([[ - return vim.fn.isdirectory(_G.test_log_dir .. '/nested/dir') == 1 - ]]) - local file_exists = child.lua([[ - return vim.fn.filereadable(_G.test_log_dir .. '/nested/dir/test.log') == 1 - ]]) - - eq(dir_exists, true) - eq(file_exists, true) -end - -T["file_logging"]["supports path expansion"] = function() - setup_logger({ - level = vim.log.levels.INFO, - file = "~/test-eca.log", - }) - - local expanded_path = child.lua_get("Logger.get_log_path()") - expect_no_match(expanded_path, "^~") - expect_match(expanded_path, "test%-eca%.log$") -end - -T["notifications"] = new_set() - -T["notifications"]["Logger.notify sends vim.notify"] = function() - setup_logger_with_file("notify_test.log") - - child.lua([[ - Logger.notify('warning message', vim.log.levels.WARN) - Logger.notify('error message', vim.log.levels.ERROR) - ]]) - - local notifications = child.lua_get("_G.captured_notifications") - eq(#notifications, 2) - eq(notifications[1].message, "warning message") - eq(notifications[1].level, vim.log.levels.WARN) - eq(notifications[2].message, "error message") - eq(notifications[2].level, vim.log.levels.ERROR) -end - -T["notifications"]["Logger.notify defaults to INFO level"] = function() - setup_logger_with_file("notify_default_test.log") - - child.lua([[Logger.notify('default level message')]]) - - local notifications = child.lua_get("_G.captured_notifications") - eq(#notifications, 1) - eq(notifications[1].message, "default level message") - eq(notifications[1].level, vim.log.levels.INFO) -end - -T["notifications"]["Logger.notify writes to log file"] = function() - local contents = log_and_read( - "notify_log_test.log", - [[ - Logger.notify('test notification message', vim.log.levels.WARN) - ]] - ) - - expect_match(contents, "WARN") - expect_match(contents, "test notification message") - - local notifications = child.lua_get("_G.captured_notifications") - eq(#notifications, 1) - eq(notifications[1].message, "test notification message") - eq(notifications[1].level, vim.log.levels.WARN) -end - -T["display modes"] = new_set() - -T["display modes"]["default display mode is split"] = function() - setup_logger_with_file("display_test.log") - - local display = child.lua_get("Logger.get_display()") - eq(display, "split") -end - -T["display modes"]["can configure popup mode"] = function() - setup_logger({ - level = vim.log.levels.INFO, - file = get_test_file_path("popup_test.log"), - display = "popup", - }) - - local display = child.lua_get("Logger.get_display()") - eq(display, "popup") -end - -T["utilities"] = new_set() - -T["utilities"]["get_log_stats"] = function() - setup_logger_with_file("stats_test.log") - - child.lua([[Logger.info('message for stats')]]) - - wait_for_async() - - local stats = child.lua_get("Logger.get_log_stats()") - eq(type(stats), "table") - expect_match(stats.path, "stats_test%.log$") - eq(type(stats.size), "number") - eq(stats.size > 0, true) - eq(type(stats.size_mb), "number") - eq(type(stats.modified), "string") -end - -T["utilities"]["clear_log"] = function() - local content_before = log_and_read("clear_test.log", [[Logger.info('message to be cleared')]]) - expect_match(content_before, "message to be cleared") - - local cleared = child.lua_get("Logger.clear_log()") - eq(cleared, true) - - local content_after = read_log_file("/clear_test.log") - eq(content_after, "") -end - -T["integration"] = new_set() - -T["integration"]["logger functions work correctly"] = function() - local contents = log_and_read( - "logger_integration.log", - [[ - Logger.debug('debug message') - Logger.info('info message') - Logger.warn('warn message') - Logger.error('error message') - ]], - { level = vim.log.levels.DEBUG } - ) - - expect_match(contents, "debug message") - expect_match(contents, "info message") - expect_match(contents, "warn message") - expect_match(contents, "error message") -end - -T["integration"]["EcaLogs command behavior"] = function() - setup_logger_with_file("eca_logs_test.log") - - child.lua([[Logger.info('Test log entry for EcaLogs')]]) - - wait_for_async() - - local log_path = child.lua_get("Logger.get_log_path()") - expect_match(log_path, "eca_logs_test%.log$") - - local api_result = child.lua([[ - local Api = require('eca.api') - local Logger = require('eca.logger') - - local log_path = Logger.get_log_path() - return { - log_path_exists = vim.fn.filereadable(log_path) == 1, - log_path = log_path, - file_readable = vim.fn.filereadable(log_path) == 1 - } - ]]) - - eq(api_result.log_path_exists, true) - eq(api_result.file_readable, true) - expect_match(api_result.log_path, "eca_logs_test%.log$") -end - -T["integration"]["EcaLogs subcommands"] = function() - setup_logger_with_file("subcommands_test.log") - - child.lua([[ - Logger.info('Test content for subcommands') - Logger.warn('Test warning message') - ]]) - - wait_for_async() - - local log_path_result = child.lua([[ - local Logger = require("eca.logger") - return Logger.get_log_path() - ]]) - expect_match(log_path_result, "subcommands_test%.log$") - - local stats_result = child.lua([[ - local Logger = require("eca.logger") - return Logger.get_log_stats() - ]]) - eq(type(stats_result), "table") - expect_match(stats_result.path, "subcommands_test%.log$") - eq(stats_result.size > 0, true) - - local clear_result = child.lua([[ - local Logger = require("eca.logger") - return Logger.clear_log() - ]]) - eq(clear_result, true) - - local file_empty = child.lua([[ - local Logger = require("eca.logger") - local stats = Logger.get_log_stats() - return stats and stats.size == 0 - ]]) - eq(file_empty, true) -end - -T["integration"]["large log file notification"] = function() - -- Create a small log file first - setup_logger_with_file("notification_test.log") - child.lua([[Logger.info('Initial log entry')]]) - wait_for_async() - - -- Clear notifications before testing - child.lua([[_G.captured_notifications = {}]]) - - -- Setup logger with max_file_size_mb = 0 to trigger notification immediately - setup_logger({ - level = vim.log.levels.INFO, - file = get_test_file_path("notification_test.log"), - max_file_size_mb = 0, -- Set to 0 to trigger notification for any file size - }) - - wait_for_async(200) - - local notifications = child.lua_get("_G.captured_notifications") - eq(#notifications >= 1, true) - - local large_file_notification = nil - for _, notification in ipairs(notifications) do - if notification.message and notification.message:match("ECA log file is large") then - large_file_notification = notification - break - end - end - - eq(large_file_notification ~= nil, true) - expect_match(large_file_notification.message, "ECA log file is large") - expect_match(large_file_notification.message, "MB%)") - expect_match(large_file_notification.message, "Consider clearing it with :EcaLogs clear") - eq(large_file_notification.level, vim.log.levels.WARN) - eq(large_file_notification.opts.title, "ECA") -end - -return T diff --git a/tests/test_message_handler.lua b/tests/test_message_handler.lua deleted file mode 100644 index 74ab9e3..0000000 --- a/tests/test_message_handler.lua +++ /dev/null @@ -1,42 +0,0 @@ -local MiniTest = require("mini.test") -local eq = MiniTest.expect.equality -local child = MiniTest.new_child_neovim() - -local T = MiniTest.new_set({ - hooks = { - pre_case = function() - child.restart({ "-u", "scripts/minimal_init.lua" }) - end, - post_case = function() - child.lua("if _G.proc then _G.proc:kill() end") - end, - post_once = child.stop, - }, -}) - -local function grab_message(data) - child.lua("_G.data =" .. vim.inspect(data)) - eq(child.lua_get("_G.data"), data) - return child.lua_get("require('eca.message_handler').parse_raw_messages(_G.data)") -end - -T["message handling"] = MiniTest.new_set({ - parametrize = { - { 'Content-Length: 18\n\n{"jsonrpc": "1.0"}', { { content_length = 18, content = '{"jsonrpc": "1.0"}' } } }, - { - 'Content-Length: 18\n\n{"jsonrpc": "1.0"}Content-Length: 18\n\n{"jsonrpc": "2.0"}', - { - { content_length = 18, content = '{"jsonrpc": "1.0"}' }, - { content_length = 18, content = '{"jsonrpc": "2.0"}' }, - }, - }, - { "", {} }, - { "not a message", {} }, - }, -}) -T["message handling"]["parses one message"] = function(input, want) - local got = grab_message(input) - eq(got, want) -end - -return T diff --git a/tests/test_picker.lua b/tests/test_picker.lua deleted file mode 100644 index 2a28a18..0000000 --- a/tests/test_picker.lua +++ /dev/null @@ -1,77 +0,0 @@ -local MiniTest = require("mini.test") -local eq = MiniTest.expect.equality -local child = MiniTest.new_child_neovim() - -local T = MiniTest.new_set({ - hooks = { - pre_case = function() - child.restart({ "-u", "scripts/minimal_init.lua" }) - child.lua([[ - _G.captured_notifications = {} - local Logger = require('eca.logger') - _G._original_notify = Logger.notify - Logger.notify = function(msg, level, opts) - table.insert(_G.captured_notifications, { - message = msg, - level = level, - opts = opts or {}, - }) - end - ]]) - end, - post_case = function() - child.lua([[ - local Logger = require('eca.logger') - if _G._original_notify then - Logger.notify = _G._original_notify - end - _G.captured_notifications = nil - ]]) - end, - post_once = child.stop, - }, -}) - -T["picker wrapper"] = MiniTest.new_set() - -T["picker wrapper"]["logs error when snacks is missing"] = function() - child.lua([[ - package.loaded['snacks'] = nil - local Picker = require('eca.ui.picker') - _G.result = Picker.pick({ source = 'test-source' }) - ]]) - - local result = child.lua_get("_G.result") - eq(result, vim.NIL) - - local notifications = child.lua_get("_G.captured_notifications") - eq(#notifications, 1) - eq(notifications[1].message, "snacks.nvim is not available") - eq(notifications[1].level, child.lua_get("vim.log.levels.ERROR")) -end - -T["picker wrapper"]["delegates to snacks.picker when available"] = function() - child.lua([[ - local calls = {} - package.loaded['snacks'] = { - picker = function(config) - table.insert(calls, config) - return 'OK' - end, - } - _G.snacks_calls = calls - - local Picker = require('eca.ui.picker') - _G.result = Picker.pick({ source = 'test-source', extra = true }) - ]]) - - local result = child.lua_get("_G.result") - eq(result, "OK") - - local calls = child.lua_get("_G.snacks_calls") - eq(#calls, 1) - eq(calls[1].source, "test-source") - eq(calls[1].extra, true) -end - -return T diff --git a/tests/test_select_commands.lua b/tests/test_select_commands.lua deleted file mode 100644 index c563fc8..0000000 --- a/tests/test_select_commands.lua +++ /dev/null @@ -1,204 +0,0 @@ -local MiniTest = require("mini.test") -local eq = MiniTest.expect.equality -local child = MiniTest.new_child_neovim() - --- Returns the registered command's name, or nil if not registered. Filters --- server-side so the function-valued `callback` field (present on 0.12+) --- does not cross the MiniTest msgpack boundary. -local function cmd_registered_name(name) - return child.lua_get(string.format( - "(vim.api.nvim_get_commands({})[%q] or {}).name", - name - )) -end - -local function setup_test_environment() - -- Setup commands - require('eca.commands').setup() - - -- Initialize everything - _G.Server = require('eca.server').new() - _G.State = require('eca.state').new() - _G.Mediator = require('eca.mediator').new(_G.Server, _G.State) - _G.Sidebar = require('eca.sidebar').new(1, _G.Mediator) - _G.Eca = require('eca') - _G.Eca.sidebars[1] = _G.Sidebar - _G.Eca.current = { sidebar = _G.Sidebar } - - -- Mock vim.ui.select for testing - _G.selected_choice = nil - _G.shown_items = nil - _G.shown_prompt = nil - _G.original_select = vim.ui.select - - _G.mock_select = function(choice) - _G.selected_choice = choice - vim.ui.select = function(items, opts, on_choice) - _G.shown_items = items - _G.shown_prompt = opts.prompt - on_choice(choice) - end - end - - _G.restore_select = function() - vim.ui.select = _G.original_select - end -end - -local T = MiniTest.new_set({ - hooks = { - pre_case = function() - child.restart({ "-u", "scripts/minimal_init.lua" }) - child.lua_func(setup_test_environment) - end, - post_case = function() - child.lua([[_G.restore_select()]]) - end, - post_once = child.stop, - }, -}) - --- Test EcaChatSelectModel command -T["EcaChatSelectModel"] = MiniTest.new_set() - -T["EcaChatSelectModel"]["command is registered"] = function() - eq(cmd_registered_name("EcaChatSelectModel"), "EcaChatSelectModel") -end - -T["EcaChatSelectModel"]["updates state when model selected"] = function() - -- Setup initial state with models - child.lua([[ - _G.State.config.models.list = { "model1", "model2", "model3" } - _G.State.config.models.selected = "model1" - - -- Mock vim.ui.select to auto-select model2 - _G.mock_select("model2") - ]]) - - -- Execute command - child.cmd("EcaChatSelectModel") - - -- Check that state was updated - eq(child.lua_get("_G.State.config.models.selected"), "model2") -end - -T["EcaChatSelectModel"]["notifies server of model change"] = function() - child.lua([[ - _G.State.config.models.list = { "model1", "model2", "model3" } - _G.State.config.models.selected = "model1" - - -- Capture outgoing notifications - _G.sent_notifications = {} - _G.Mediator.send = function(self, method, params, callback) - table.insert(_G.sent_notifications, { method = method, params = params }) - end - - _G.mock_select("model2") - ]]) - - child.cmd("EcaChatSelectModel") - - local notifications = child.lua_get("_G.sent_notifications") - eq(#notifications, 1) - eq(notifications[1].method, "chat/selectedModelChanged") - eq(notifications[1].params.model, "model2") -end - -T["EcaChatSelectModel"]["handles nil selection"] = function() - -- Setup initial state - child.lua([[ - _G.State.config.models.list = { "model1", "model2" } - _G.State.config.models.selected = "model1" - - -- Mock vim.ui.select to return nil (user cancelled) - _G.mock_select(nil) - ]]) - - -- Execute command - child.cmd("EcaChatSelectModel") - - -- Check that state was NOT updated (still model1) - eq(child.lua_get("_G.State.config.models.selected"), "model1") -end - -T["EcaChatSelectModel"]["displays all available models"] = function() - -- Setup models list - child.lua([[ - _G.State.config.models.list = { "gpt-4", "gpt-3.5-turbo", "claude-3" } - - -- Mock vim.ui.select to capture the items shown - _G.mock_select(nil) - ]]) - - -- Execute command - child.cmd("EcaChatSelectModel") - - -- Verify all models were shown - local shown_items = child.lua_get("_G.shown_items") - eq(shown_items[1], "gpt-4") - eq(shown_items[2], "gpt-3.5-turbo") - eq(shown_items[3], "claude-3") -end - --- Test EcaChatSelectBehavior command -T["EcaChatSelectBehavior"] = MiniTest.new_set() - -T["EcaChatSelectBehavior"]["command is registered"] = function() - eq(cmd_registered_name("EcaChatSelectBehavior"), "EcaChatSelectBehavior") -end - -T["EcaChatSelectBehavior"]["updates state when behavior selected"] = function() - -- Setup initial state with behaviors - child.lua([[ - _G.State.config.behaviors.list = { "helpful", "creative", "concise" } - _G.State.config.behaviors.selected = "helpful" - - -- Mock vim.ui.select to auto-select creative - _G.mock_select("creative") - ]]) - - -- Execute command - child.cmd("EcaChatSelectBehavior") - - -- Check that state was updated - eq(child.lua_get("_G.State.config.behaviors.selected"), "creative") -end - -T["EcaChatSelectBehavior"]["handles nil selection"] = function() - -- Setup initial state - child.lua([[ - _G.State.config.behaviors.list = { "helpful", "creative" } - _G.State.config.behaviors.selected = "helpful" - - -- Mock vim.ui.select to return nil (user cancelled) - _G.mock_select(nil) - ]]) - - -- Execute command - child.cmd("EcaChatSelectBehavior") - - -- Check that state was NOT updated (still helpful) - eq(child.lua_get("_G.State.config.behaviors.selected"), "helpful") -end - -T["EcaChatSelectBehavior"]["displays all available behaviors"] = function() - -- Setup behaviors list - child.lua([[ - _G.State.config.behaviors.list = { "helpful", "creative", "concise", "technical" } - - -- Mock vim.ui.select to capture the items shown - _G.mock_select(nil) - ]]) - - -- Execute command - child.cmd("EcaChatSelectBehavior") - - -- Verify all behaviors were shown - local shown_items = child.lua_get("_G.shown_items") - eq(shown_items[1], "helpful") - eq(shown_items[2], "creative") - eq(shown_items[3], "concise") - eq(shown_items[4], "technical") -end - -return T diff --git a/tests/test_server_integration.lua b/tests/test_server_integration.lua deleted file mode 100644 index 9b5668b..0000000 --- a/tests/test_server_integration.lua +++ /dev/null @@ -1,84 +0,0 @@ -local MiniTest = require("mini.test") -local eq = MiniTest.expect.equality -local child = MiniTest.new_child_neovim() - -local function setup_test_environment() - _G.log = {} - _G.notifications = {} - Logger = require("eca.logger") - Logger.log = function(message, level) - table.insert(_G.log, { message = message, level = level }) - end - Logger.notify = function(message, level, opts) - table.insert(_G.notifications, { message = message, level = level, opts = opts }) - end - _G.server = require("eca.server").new() -end - -local T = MiniTest.new_set({ - hooks = { - pre_case = function() - child.restart({ "-u", "scripts/minimal_init.lua" }) - child.lua_func(setup_test_environment) - end, - post_case = function() - child.lua("if _G.server and _G.server.process then _G.server.process:kill() end") - end, - post_once = child.stop, - }, -}) - --- See https://github.com/echasnovski/mini.nvim/issues/1863#issuecomment-2983629024 --- for why the sleep is necessary when testing something with a callback -local function sleep(ms) - vim.uv.sleep(ms) - -- Execute 'nvim_eval' (a deferred function) to - -- force at least one main_loop iteration - child.api.nvim_eval("1") -end - -T["server"] = MiniTest.new_set() - -T["server"]["start"] = function() - child.lua("_G.server:start()") - child.lua([[ - _G.server_started = vim.wait(10000, function() - return _G.server and _G.server:is_running() - end, 100) - ]]) - eq(child.lua_get("_G.server_started"), true) - sleep(1000) - eq(child.lua_get("_G.server.initialized"), true) -end - -T["server"]["start without initialize"] = function() - child.lua("_G.server:start({ initialize = false })") - child.lua([[ - _G.server_started = vim.wait(10000, function() - return _G.server and _G.server:is_running() - end, 100) - ]]) - eq(child.lua_get("_G.server_started"), true) - sleep(1000) - eq(child.lua_get("_G.server.initialized"), false) -end - -T["server"]["start with inexistent path"] = function() - child.lua([[ - _G.config = require("eca.config") - _G.config.setup({ server_path = "non-existing-path" }) - _G.server:start() - ]]) - child.lua([[ - _G.server_started = vim.wait(1000, function() - return _G.server and _G.server:is_running() - end, 100) - ]]) - - eq(child.lua_get("_G.server_started"), false) - sleep(1000) - eq(child.lua_get("_G.server.initialized"), false) - eq(string.find(child.lua_get("_G.notifications[1].message"), "non-existing-path", 1 , true) ~= nil, true) -end - -return T diff --git a/tests/test_server_path.lua b/tests/test_server_path.lua deleted file mode 100644 index 6ab038a..0000000 --- a/tests/test_server_path.lua +++ /dev/null @@ -1,79 +0,0 @@ -local MiniTest = require("mini.test") -local eq = MiniTest.expect.equality -local child = MiniTest.new_child_neovim() - -local function setup_test_environment() - Utils = require("eca.utils") - _G.cmd = function(custom_path) - return { - "nvim", - "--headless", - "--cmd", - string.format([[lua - package.preload["eca.config"] = function() - local M = {} - M.server_path = %q - return M - end - ]], custom_path or ""), - "--cmd", - [[lua - package.preload["eca.path_finder"] = function() - local M = {} - function M.new() - return setmetatable({}, { __index = M }) - end - function M:find() - Config = require("eca.config") - local custom_path = Config.server_path - - if custom_path == "error" then - error("custom-server-path-error") - end - return (custom_path ~= "" and custom_path) or "no-custom-server-path" - end - return M - end - ]], - "-S", - "scripts/server_path.lua", - } - end -end - -local T = MiniTest.new_set({ - hooks = { - pre_case = function() - child.restart({ "-u", "scripts/minimal_init.lua" }) - child.lua_func(setup_test_environment) - end, - post_case = function() - end, - post_once = child.stop, - }, -}) - -T["server_path"] = MiniTest.new_set() - -T["server_path"]["run without custom path should print to stdout"] = function() - child.lua("_G.result = vim.system(_G.cmd(), { text = true }):wait()") - eq(child.lua_get("_G.result.code"), 0) - eq(child.lua_get("_G.result.stdout"), "no-custom-server-path") - eq(child.lua_get("_G.result.stderr"), "") -end - -T["server_path"]["run with custom path should print to stdout"] = function() - child.lua("_G.result = vim.system(_G.cmd('custom-server-path'), { text = true }):wait()") - eq(child.lua_get("_G.result.code"), 0) - eq(child.lua_get("_G.result.stdout"), "custom-server-path") - eq(child.lua_get("_G.result.stderr"), "") -end - -T["server_path"]["run with error should print to stderr"] = function() - child.lua("_G.result = vim.system(_G.cmd('error'), { text = true }):wait()") - eq(child.lua_get("_G.result.code"), 1) - eq(child.lua_get("_G.result.stdout"), "") - eq(string.find(child.lua_get("_G.result.stderr"), "custom-server-path-error", 1 , true) ~= nil, true) -end - -return T diff --git a/tests/test_server_picker_commands.lua b/tests/test_server_picker_commands.lua deleted file mode 100644 index dd08581..0000000 --- a/tests/test_server_picker_commands.lua +++ /dev/null @@ -1,182 +0,0 @@ -local MiniTest = require("mini.test") -local eq = MiniTest.expect.equality -local child = MiniTest.new_child_neovim() - -local function flush(ms) - vim.uv.sleep(ms or 50) - child.api.nvim_eval("1") -end - -local function setup_env() - require('eca.commands').setup() - - -- Stub Picker.pick so commands can run without snacks.nvim - local Picker = require('eca.ui.picker') - _G.picker_calls = {} - Picker.pick = function(config) - table.insert(_G.picker_calls, config) - end -end - -local T = MiniTest.new_set({ - hooks = { - pre_case = function() - child.restart({ "-u", "scripts/minimal_init.lua" }) - child.lua_func(setup_env) - end, - post_case = function() - child.lua("_G.picker_calls = nil") - end, - post_once = child.stop, - }, -}) - -T["EcaServerMessages"] = MiniTest.new_set() - -T["EcaServerMessages"]["uses picker and filters invalid JSON messages"] = function() - child.lua([[ - local eca = require('eca') - eca.server = eca.server or {} - eca.server.messages = { - { id = 1, direction = 'send', content = vim.json.encode({ jsonrpc = '2.0', method = 'test/method', id = 1 }) }, - { id = 2, direction = 'recv', content = 'not-json' }, - } - - vim.cmd('EcaServerMessages') - ]]) - - flush() - - child.lua([[ - local calls = _G.picker_calls or {} - local cfg = calls[1] - _G.picker_info = { - count = #calls, - source = cfg and cfg.source or nil, - } - ]]) - - local picker_info = child.lua_get("_G.picker_info") - - eq(picker_info.count, 1) - eq(picker_info.source, "eca messages") - - -- Run finder and inspect produced items - child.lua([[ - local cfg = _G.picker_calls[1] - local items = cfg.finder({}, {}) - _G.result_messages = { - count = #items, - first = items[1], - } - ]]) - - local result = child.lua_get("_G.result_messages") - - -- Only the valid JSON message should be included - eq(result.count, 1) - eq(type(result.first), "table") - eq(result.first.idx, 1) - eq(result.first.preview.ft, "lua") - - -- Preview text should contain the method name - local has_method = child.lua_get("string.find(..., 'test/method', 1, true) ~= nil", { result.first.preview.text }) - eq(has_method, true) - - -- Confirm callback yanks preview text and closes picker - child.lua([[ - local cfg = _G.picker_calls[1] - local item = cfg.finder({}, {})[1] - local picker = { closed = false } - function picker:close() self.closed = true end - - cfg.confirm(picker, item, nil) - - _G.confirm_messages = { - reg = vim.fn.getreg(''), - closed = picker.closed, - } - ]]) - - local confirm_ok = child.lua_get("_G.confirm_messages") - - eq(confirm_ok.closed, true) - eq(type(confirm_ok.reg), "string") - local has_method_in_reg = child.lua_get("string.find(..., 'test/method', 1, true) ~= nil", { confirm_ok.reg }) - eq(has_method_in_reg, true) -end - -T["EcaServerTools"] = MiniTest.new_set() - -T["EcaServerTools"]["lists tools from state in sorted order"] = function() - child.lua([[ - local eca = require('eca') - eca.state = eca.state or {} - eca.state.tools = { - zebra = { kind = 'z' }, - alpha = { kind = 'a' }, - middle = { kind = 'm' }, - } - - vim.cmd('EcaServerTools') - ]]) - - flush() - - child.lua([[ - local calls = _G.picker_calls or {} - _G.picker_info = { - count = #calls, - } - ]]) - - local picker_info = child.lua_get("_G.picker_info") - - eq(picker_info.count, 1) - - child.lua([[ - local cfg = _G.picker_calls[1] - local items = cfg.finder({}, {}) - _G.result_tools = { - count = #items, - names = { items[1].text, items[2].text, items[3].text }, - first = items[1], - } - ]]) - - local result = child.lua_get("_G.result_tools") - - eq(result.count, 3) - -- Names must be sorted alphabetically - eq(result.names[1], "alpha") - eq(result.names[2], "middle") - eq(result.names[3], "zebra") - - -- Preview contains vim.inspect output of the tool - local has_kind = child.lua_get("string.find(..., 'kind%p a', 1) ~= nil", { result.first.preview.text }) - eq(has_kind, true) - - -- Confirm yanks preview text and closes picker - child.lua([[ - local cfg = _G.picker_calls[1] - local items = cfg.finder({}, {}) - local picker = { closed = false } - function picker:close() self.closed = true end - - cfg.confirm(picker, items[2], nil) - - _G.confirm_tools = { - reg = vim.fn.getreg(''), - closed = picker.closed, - } - ]]) - - local confirm_ok = child.lua_get("_G.confirm_tools") - - eq(confirm_ok.closed, true) - eq(type(confirm_ok.reg), "string") - local has_middle = child.lua_get("string.find(..., 'middle', 1, true) ~= nil", { confirm_ok.reg }) - eq(has_middle, true) -end - -return T diff --git a/tests/test_sidebar_autoscroll.lua b/tests/test_sidebar_autoscroll.lua deleted file mode 100644 index 0d233c0..0000000 --- a/tests/test_sidebar_autoscroll.lua +++ /dev/null @@ -1,154 +0,0 @@ -local MiniTest = require("mini.test") -local eq = MiniTest.expect.equality -local child = MiniTest.new_child_neovim() - -local function flush(ms) - vim.uv.sleep(ms or 120) - child.api.nvim_eval("1") -end - -local function setup_env() - _G.Server = require('eca.server').new() - _G.State = require('eca.state').new() - _G.Mediator = require('eca.mediator').new(_G.Server, _G.State) - _G.Sidebar = require('eca.sidebar').new(1, _G.Mediator) - - _G.Sidebar:open() - - _G.fill_chat = function(n) - local chat = _G.Sidebar.containers.chat - vim.api.nvim_set_option_value('modifiable', true, { buf = chat.bufnr }) - - local lines = {} - for i = 1, n do - lines[i] = string.format('line %03d', i) - end - - vim.api.nvim_buf_set_lines(chat.bufnr, 0, -1, false, lines) - end - - _G.focus_chat = function() - vim.api.nvim_set_current_win(_G.Sidebar.containers.chat.winid) - end - - _G.focus_input = function() - vim.api.nvim_set_current_win(_G.Sidebar.containers.input.winid) - end - - _G.set_chat_cursor = function(row) - local win = _G.Sidebar.containers.chat.winid - vim.api.nvim_win_set_cursor(win, { row, 0 }) - end - - _G.add_assistant_message = function(text) - _G.Sidebar:_add_message('assistant', text) - end - - _G.get_chat_view = function() - local chat = _G.Sidebar.containers.chat - local view = vim.api.nvim_win_call(chat.winid, function() - local v = vim.fn.winsaveview() - return { topline = v.topline, lnum = v.lnum } - end) - - local bottomline = vim.api.nvim_win_call(chat.winid, function() - return vim.fn.line('w$') - end) - - return { - current_win = vim.api.nvim_get_current_win(), - chat_win = chat.winid, - input_win = _G.Sidebar.containers.input.winid, - cursor = vim.api.nvim_win_get_cursor(chat.winid), - topline = view.topline, - lnum = view.lnum, - bottomline = bottomline, - line_count = vim.api.nvim_buf_line_count(chat.bufnr), - } - end -end - -local T = MiniTest.new_set({ - hooks = { - pre_case = function() - child.restart({ "-u", "scripts/minimal_init.lua" }) - child.lua_func(setup_env) - end, - post_case = function() - child.lua([[ if _G.Sidebar then _G.Sidebar:close() end ]]) - end, - post_once = child.stop, - }, -}) - -T["sidebar autoscroll"] = MiniTest.new_set() - -T["sidebar autoscroll"]["auto-scrolls when chat is not focused"] = function() - -- Let deferred sidebar setup (like initial focus) settle. - flush(200) - - child.lua([[ - _G.fill_chat(100) - _G.focus_chat() - _G.set_chat_cursor(1) - _G.focus_input() - ]]) - - -- Add a new assistant message while focus is on input. - child.lua([[_G.add_assistant_message('incoming')]]) - - flush(220) - - local view = child.lua_get("_G.get_chat_view()") - - -- Focus should remain on input. - eq(view.current_win, view.input_win) - -- Chat cursor should be moved to the bottom. - eq(view.cursor[1], view.line_count) -end - -T["sidebar autoscroll"]["does not auto-scroll when chat is focused and not at bottom"] = function() - -- Let deferred sidebar setup (like initial focus) settle. - flush(200) - - child.lua([[ - _G.fill_chat(100) - _G.focus_chat() - _G.set_chat_cursor(10) - _G.before = _G.get_chat_view() - ]]) - - child.lua([[_G.add_assistant_message('incoming')]]) - - flush(220) - - local before = child.lua_get("_G.before") - local after = child.lua_get("_G.get_chat_view()") - - eq(after.current_win, after.chat_win) - eq(after.cursor[1], before.cursor[1]) - eq(after.topline, before.topline) -end - -T["sidebar autoscroll"]["auto-scrolls when chat is focused and at bottom"] = function() - -- Let deferred sidebar setup (like initial focus) settle. - flush(200) - - child.lua([[ - _G.fill_chat(100) - _G.focus_chat() - _G.set_chat_cursor(100) - _G.before = _G.get_chat_view() - ]]) - - child.lua([[_G.add_assistant_message('incoming')]]) - - flush(220) - - local after = child.lua_get("_G.get_chat_view()") - - eq(after.current_win, after.chat_win) - eq(after.cursor[1], after.line_count) -end - -return T diff --git a/tests/test_sidebar_usage_and_tools.lua b/tests/test_sidebar_usage_and_tools.lua deleted file mode 100644 index 20873b7..0000000 --- a/tests/test_sidebar_usage_and_tools.lua +++ /dev/null @@ -1,672 +0,0 @@ -local MiniTest = require("mini.test") -local eq = MiniTest.expect.equality -local child = MiniTest.new_child_neovim() - -local function flush(ms) - vim.uv.sleep(ms or 80) - child.api.nvim_eval("1") -end - -local function setup_env() - -- Minimal environment with Server, State, Mediator, Sidebar - _G.Server = require('eca.server').new() - _G.State = require('eca.state').new() - _G.Mediator = require('eca.mediator').new(_G.Server, _G.State) - _G.Sidebar = require('eca.sidebar').new(1, _G.Mediator) - - -- Open sidebar so containers are created - _G.Sidebar:open() -end - -local T = MiniTest.new_set({ - hooks = { - pre_case = function() - child.restart({ "-u", "scripts/minimal_init.lua" }) - child.lua_func(setup_env) - end, - post_case = function() - child.lua([[ if _G.Sidebar then _G.Sidebar:close() end ]]) - end, - post_once = child.stop, - }, -}) - -T["usage formatting"] = MiniTest.new_set() - -T["usage formatting"]["uses default short token format"] = function() - child.lua([[ - local Sidebar = _G.Sidebar - local Mediator = _G.Mediator - - -- Stub mediator usage values - function Mediator:status_state() return 'responding' end - function Mediator:status_text() return 'Responding' end - function Mediator:tokens_session() return 1499 end - function Mediator:tokens_limit() return 1501 end - function Mediator:costs_session() return '0.00' end - - Sidebar:_update_usage_info() - ]]) - - local info = child.lua_get("_G.Sidebar._usage_info") - -- 1499 -> 1k, 1501 -> 2k with rounding - eq(info, "1k / 2k ($0.00)") -end - -T["usage formatting"]["respects custom windows.usage.format"] = function() - child.lua([[ - local Config = require('eca.config') - Config.override({ - windows = { - usage = { - format = '{session_tokens} of {limit_tokens} tokens (${session_cost})', - }, - }, - }) - - local Sidebar = _G.Sidebar - local Mediator = _G.Mediator - - function Mediator:status_state() return 'responding' end - function Mediator:status_text() return 'Responding' end - function Mediator:tokens_session() return 42 end - function Mediator:tokens_limit() return 1000 end - function Mediator:costs_session() return '1.23' end - - Sidebar:_update_usage_info() - ]]) - - local info = child.lua_get("_G.Sidebar._usage_info") - eq(info, "42 of 1000 tokens ($1.23)") -end - -T["tool call diffs"] = MiniTest.new_set() - -T["tool call diffs"]["shows arguments and outputs sections when expanded"] = function() - child.lua([[ - local Sidebar = _G.Sidebar - - -- Simulate a tool call lifecycle with arguments and outputs (no diff) - Sidebar:handle_chat_content_received({ - chatId = 'chat-out', - content = { - type = 'toolCallPrepare', - id = 'tool-out', - name = 'test_tool', - summary = 'Test Tool', - argumentsText = '{"value": 1}', - details = {}, - }, - }) - - Sidebar:handle_chat_content_received({ - chatId = 'chat-out', - content = { - type = 'toolCallRunning', - id = 'tool-out', - }, - }) - - Sidebar:handle_chat_content_received({ - chatId = 'chat-out', - content = { - type = 'toolCalled', - id = 'tool-out', - name = 'test_tool', - summary = 'Test Tool', - outputs = { - { type = 'text', text = 'tool-output-123' }, - }, - }, - }) - ]]) - - flush(100) - - child.lua([[ - local Sidebar = _G.Sidebar - local call = Sidebar._tool_calls[1] - local chat = Sidebar.containers.chat - - if not call or not chat or not chat.bufnr then - _G.tool_details = { expanded = false, has_arguments = false, has_output = false, has_output_text = false } - return - end - - -- Expand the arguments/output block via the header - vim.api.nvim_win_set_cursor(chat.winid, { call.header_line, 0 }) - Sidebar:_toggle_tool_call_at_cursor() - - local buf = chat.bufnr - local lines = vim.api.nvim_buf_get_lines(buf, call.header_line, call.header_line + 20, false) - - local details = { - expanded = call.expanded, - has_arguments = false, - has_output = false, - has_output_text = false, - } - - for _, line in ipairs(lines) do - if line == 'Arguments:' then - details.has_arguments = true - elseif line == 'Output:' then - details.has_output = true - end - if string.find(line, 'tool-output-123', 1, true) then - details.has_output_text = true - end - end - - _G.tool_details = details - ]]) - - local info = child.lua_get("_G.tool_details") - - eq(info.expanded, true) - eq(info.has_arguments, true) - eq(info.has_output, true) - eq(info.has_output_text, true) -end - -T["tool call diffs"]["shows diff label and toggles diff block with "] = function() - child.lua([[ - local Sidebar = _G.Sidebar - local chat = Sidebar.containers.chat - - -- Simulate a tool call lifecycle with diff - Sidebar:handle_chat_content_received({ - chatId = 'chat-1', - content = { - type = 'toolCallPrepare', - id = 'tool-1', - name = 'test_tool', - summary = 'Test Tool', - argumentsText = '{"value": 1}', - details = {}, - }, - }) - - Sidebar:handle_chat_content_received({ - chatId = 'chat-1', - content = { - type = 'toolCallRunning', - id = 'tool-1', - }, - }) - - Sidebar:handle_chat_content_received({ - chatId = 'chat-1', - content = { - type = 'toolCalled', - id = 'tool-1', - name = 'test_tool', - summary = 'Test Tool', - details = { diff = '+added\n-removed' }, - }, - }) - ]]) - - flush(100) - - child.lua([[ - local Sidebar = _G.Sidebar - local call = Sidebar._tool_calls[1] - local buf = Sidebar.containers.chat.bufnr - _G.call_info = { - has_diff = call and call.has_diff or false, - header_line = call and call.header_line or 0, - label_line = call and call.label_line or 0, - header_text = call and vim.api.nvim_buf_get_lines(buf, call.header_line - 1, call.header_line, false)[1] or '', - label_text = call and vim.api.nvim_buf_get_lines(buf, call.label_line - 1, call.label_line, false)[1] or '', - } - ]]) - - local call_info = child.lua_get("_G.call_info") - - eq(call_info.has_diff, true) - eq(call_info.label_line > 0, true) - - -- Default collapsed label - eq(call_info.label_text, "+ view diff") - - -- Header should mention the summary - local has_summary = child.lua_get("string.find(..., 'Test Tool', 1, true) ~= nil", { call_info.header_text }) - eq(has_summary, true) - - -- Toggle on the diff label line should expand/collapse only the diff block - child.lua([[ - local Sidebar = _G.Sidebar - local call = Sidebar._tool_calls[1] - local chat = Sidebar.containers.chat - - vim.api.nvim_win_set_cursor(chat.winid, { call.label_line, 0 }) - Sidebar:_toggle_tool_call_at_cursor() -- expand diff - ]]) - - flush(50) - - child.lua([[ - local Sidebar = _G.Sidebar - local call = Sidebar._tool_calls[1] - local buf = Sidebar.containers.chat.bufnr - local first_diff = vim.api.nvim_buf_get_lines(buf, call.label_line, call.label_line + 1, false)[1] or '' - _G.expanded_info = { - diff_expanded = call.diff_expanded, - first_diff = first_diff, - } - ]]) - - local expanded = child.lua_get("_G.expanded_info") - - eq(expanded.diff_expanded, true) - eq(expanded.first_diff, "```diff") - - -- Collapse again - child.lua([[ - local Sidebar = _G.Sidebar - local call = Sidebar._tool_calls[1] - local chat = Sidebar.containers.chat - - vim.api.nvim_win_set_cursor(chat.winid, { call.label_line, 0 }) - Sidebar:_toggle_tool_call_at_cursor() -- collapse diff - ]]) - - flush(50) - - local collapsed = child.lua_get("_G.Sidebar._tool_calls[1].diff_expanded") - eq(collapsed, false) -end - -T["reasoning blocks"] = MiniTest.new_set() - -T["reasoning blocks"]["stream reasoning and toggle body"] = function() - child.lua([[ - local Sidebar = _G.Sidebar - - Sidebar:handle_chat_content_received({ - chatId = 'chat-r', - content = { type = 'reasonStarted', id = 'r1' }, - }) - - Sidebar:handle_chat_content_received({ - chatId = 'chat-r', - content = { type = 'reasonText', id = 'r1', text = 'First line.\nSecond line.' }, - }) - - Sidebar:handle_chat_content_received({ - chatId = 'chat-r', - content = { type = 'reasonFinished', id = 'r1', totalTimeMs = 1234 }, - }) - ]]) - - flush(100) - - child.lua([[ - local Sidebar = _G.Sidebar - local call = Sidebar._reasons['r1'] - local buf = Sidebar.containers.chat.bufnr - local header = call and vim.api.nvim_buf_get_lines(buf, call.header_line - 1, call.header_line, false)[1] or '' - _G.reason_info = { - has_reason = call ~= nil, - header_line = call and call.header_line or 0, - header = header, - } - ]]) - - local info = child.lua_get("_G.reason_info") - - eq(info.has_reason, true) - - -- Header should contain the finished label and elapsed time - local has_thought = child.lua_get("string.find(..., 'Thought', 1, true) ~= nil", { info.header }) - eq(has_thought, true) - - local has_secs = child.lua_get("string.find(..., 's', 1, true) ~= nil", { info.header }) - eq(has_secs, true) - - -- Toggle body via header line - child.lua([[ - local Sidebar = _G.Sidebar - local call = Sidebar._reasons['r1'] - local chat = Sidebar.containers.chat - vim.api.nvim_win_set_cursor(chat.winid, { call.header_line, 0 }) - Sidebar:_toggle_tool_call_at_cursor() - ]]) - - flush(80) - - child.lua([[ - local Sidebar = _G.Sidebar - local call = Sidebar._reasons['r1'] - local buf = Sidebar.containers.chat.bufnr - local first = vim.api.nvim_buf_get_lines(buf, call.header_line, call.header_line + 1, false)[1] or '' - _G.reason_body = { - expanded = call.expanded, - first = first, - } - ]]) - - local body = child.lua_get("_G.reason_body") - - eq(body.expanded, true) - local has_first_line = child.lua_get("string.find(..., 'First line.', 1, true) ~= nil", { body.first }) - eq(has_first_line, true) -end - -T["replace_text"] = MiniTest.new_set() - -T["replace_text"]["supports multi-line replacement"] = function() - child.lua([[ - local Sidebar = _G.Sidebar - local chat = Sidebar.containers.chat - - vim.api.nvim_buf_set_lines(chat.bufnr, 0, -1, false, { - 'prefix TARGET suffix', - 'other line', - }) - - _G.changed = Sidebar:_replace_text('TARGET', 'foo\nbar') - _G.lines = vim.api.nvim_buf_get_lines(chat.bufnr, 0, -1, false) - ]]) - - local changed = child.lua_get("_G.changed") - eq(changed, true) - - local lines = child.lua_get("_G.lines") - eq(lines[1], "prefix foo") - eq(lines[2], "bar suffix") - eq(lines[3], "other line") -end - -T["tool call config"] = MiniTest.new_set() - -T["tool call config"]["respects windows.chat.tool_call.diff labels and expanded flag"] = function() - child.lua([[ - local Config = require('eca.config') - Config.override({ - windows = { - chat = { - tool_call = { - diff = { - collapsed_label = '[open diff]', - expanded_label = '[close diff]', - expanded = true, - }, - }, - }, - }, - }) - - local Sidebar = _G.Sidebar - - Sidebar:handle_chat_content_received({ - chatId = 'chat-cfg', - content = { - type = 'toolCallPrepare', - id = 'cfg-tool', - name = 'cfg_tool', - summary = 'Config Tool', - argumentsText = '{"foo": 1}', - details = {}, - }, - }) - - Sidebar:handle_chat_content_received({ - chatId = 'chat-cfg', - content = { - type = 'toolCallRunning', - id = 'cfg-tool', - }, - }) - - Sidebar:handle_chat_content_received({ - chatId = 'chat-cfg', - content = { - type = 'toolCalled', - id = 'cfg-tool', - name = 'cfg_tool', - summary = 'Config Tool', - details = { diff = '+x\n-y' }, - }, - }) - ]]) - - flush(100) - - child.lua([[ - local Sidebar = _G.Sidebar - local call = Sidebar._tool_calls[1] - local buf = Sidebar.containers.chat.bufnr - _G.cfg_call = { - label_line = call and call.label_line or 0, - label_text = call and vim.api.nvim_buf_get_lines(buf, call.label_line - 1, call.label_line, false)[1] or '', - diff_expanded = call and call.diff_expanded or false, - first_diff = call and vim.api.nvim_buf_get_lines(buf, call.label_line, call.label_line + 1, false)[1] or '', - } - ]]) - - local cfg = child.lua_get("_G.cfg_call") - - eq(cfg.label_text, "[close diff]") - eq(cfg.diff_expanded, true) - eq(cfg.first_diff, "```diff") -end - -T["reasoning blocks"]["use configured labels"] = function() - child.lua([[ - local Config = require('eca.config') - Config.override({ - windows = { - chat = { - reasoning = { - running_label = 'Working...', - finished_label = 'Plan', - }, - }, - }, - }) - - local Sidebar = _G.Sidebar - - Sidebar:handle_chat_content_received({ - chatId = 'chat-r2', - content = { type = 'reasonStarted', id = 'r2' }, - }) - - Sidebar:handle_chat_content_received({ - chatId = 'chat-r2', - content = { type = 'reasonFinished', id = 'r2', totalTimeMs = 500 }, - }) - ]]) - - flush(80) - - child.lua([[ - local Sidebar = _G.Sidebar - local call = Sidebar._reasons['r2'] - local buf = Sidebar.containers.chat.bufnr - _G.reason_cfg = { - header = call and vim.api.nvim_buf_get_lines(buf, call.header_line - 1, call.header_line, false)[1] or '', - } - ]]) - - local rcfg = child.lua_get("_G.reason_cfg") - - local has_plan = child.lua_get("string.find(..., 'Plan', 1, true) ~= nil", { rcfg.header }) - eq(has_plan, true) -end - -T["reasoning blocks"]["start expanded when configured"] = function() - child.lua([[ - local Config = require('eca.config') - Config.override({ - windows = { - chat = { - reasoning = { - expanded = true, - }, - }, - }, - }) - - local Sidebar = _G.Sidebar - - Sidebar:handle_chat_content_received({ - chatId = 'chat-r3', - content = { type = 'reasonStarted', id = 'r3' }, - }) - - Sidebar:handle_chat_content_received({ - chatId = 'chat-r3', - content = { type = 'reasonText', id = 'r3', text = 'First line.' }, - }) - ]]) - - flush(80) - - child.lua([[ - local Sidebar = _G.Sidebar - local call = Sidebar._reasons['r3'] - local buf = Sidebar.containers.chat.bufnr - _G.reason_expanded = { - expanded = call and call.expanded or false, - first = call and vim.api.nvim_buf_get_lines(buf, call.header_line, call.header_line + 1, false)[1] or '', - } - ]]) - - local r = child.lua_get("_G.reason_expanded") - - eq(r.expanded, true) - local has_first = child.lua_get("string.find(..., 'First line.', 1, true) ~= nil", { r.first }) - eq(has_first, true) -end - -T["reasoning blocks"]["hide arrow until there is body text"] = function() - child.lua([[ - local Sidebar = _G.Sidebar - - Sidebar:handle_chat_content_received({ - chatId = 'chat-r0', - content = { type = 'reasonStarted', id = 'r0' }, - }) - ]]) - - flush(50) - - child.lua([[ - local Sidebar = _G.Sidebar - local call = Sidebar._reasons['r0'] - local buf = Sidebar.containers.chat.bufnr - _G.reason_header = call and vim.api.nvim_buf_get_lines(buf, call.header_line - 1, call.header_line, false)[1] or '' - ]]) - - local header = child.lua_get("_G.reason_header") - - -- With no streamed reasoning text yet, the header should not show - -- the expand/collapse arrow icon. - local has_arrow = child.lua_get("string.find(..., '▶', 1, true) ~= nil", { header }) - eq(has_arrow, false) -end - -T["mcps display"] = MiniTest.new_set() - -T["mcps display"]["shows active and registered counts with highlights"] = function() - child.lua([[ - local Sidebar = _G.Sidebar - local Mediator = _G.Mediator - - function Mediator:selected_model() return 'gpt' end - function Mediator:selected_behavior() return 'default' end - - function Mediator:mcps() - return { - a = { status = 'starting' }, - b = { status = 'running' }, - c = { status = 'failed' }, - } - end - - Sidebar:_update_config_display() - ]]) - - child.lua([[ - local Sidebar = _G.Sidebar - local buf = Sidebar.containers.config.bufnr - local ns = Sidebar.extmarks.config._ns - local marks = vim.api.nvim_buf_get_extmarks(buf, ns, 0, -1, { details = true }) - local virt = marks[1][4].virt_text - _G.mcps_info = { - active_text = virt[8][1], - active_hl = virt[8][2], - registered_text = virt[10][1], - registered_hl = virt[10][2], - } - ]]) - - local info = child.lua_get("_G.mcps_info") - - eq(info.active_text, "2") -- starting + running - eq(info.active_hl, "EcaLabel") - eq(info.registered_text, "3") - eq(info.registered_hl, "Exception") -end - -T["tool call summaries"] = MiniTest.new_set() - -T["tool call summaries"]["appends filename for fileChange details"] = function() - child.lua([[ - local Sidebar = _G.Sidebar - - -- Simulate a tool call lifecycle that reports a file change - Sidebar:handle_chat_content_received({ - chatId = 'chat-file', - content = { - type = 'toolCallPrepare', - id = 'tool-file', - name = 'write_file', - summary = 'Apply edit', - argumentsText = '{"value": 1}', - details = {}, - }, - }) - - Sidebar:handle_chat_content_received({ - chatId = 'chat-file', - content = { - type = 'toolCallRunning', - id = 'tool-file', - }, - }) - - Sidebar:handle_chat_content_received({ - chatId = 'chat-file', - content = { - type = 'toolCalled', - id = 'tool-file', - name = 'write_file', - summary = 'Apply edit', - details = { type = 'fileChange', path = '/tmp/example/foo.lua', diff = '+added' }, - }, - }) - ]]) - - flush(100) - - child.lua([[ - local Sidebar = _G.Sidebar - local call = Sidebar._tool_calls[1] - local buf = Sidebar.containers.chat.bufnr - _G.file_summary = { - header = call and vim.api.nvim_buf_get_lines(buf, call.header_line - 1, call.header_line, false)[1] or '', - } - ]]) - - local info = child.lua_get("_G.file_summary") - - -- Header should mention the basename of the changed file - local has_filename = child.lua_get("string.find(..., 'foo.lua', 1, true) ~= nil", { info.header }) - eq(has_filename, true) -end - -return T diff --git a/tests/test_state.lua b/tests/test_state.lua deleted file mode 100644 index 9f89a78..0000000 --- a/tests/test_state.lua +++ /dev/null @@ -1,255 +0,0 @@ -local MiniTest = require("mini.test") -local eq = MiniTest.expect.equality -local child = MiniTest.new_child_neovim() - -local T = MiniTest.new_set({ - hooks = { - pre_case = function() - child.restart({ "-u", "scripts/minimal_init.lua" }) - child.lua([[ - _G.captured = {} - local Observer = require('eca.observer') - -- Clear any prior subscriptions by reloading the module (defensive) - package.loaded['eca.observer'] = nil - Observer = require('eca.observer') - - -- Subscribe to capture all notifications - Observer.subscribe('test-capture', function(message) - table.insert(_G.captured, message) - end) - - -- Instantiate state singleton - _G.State = require('eca.state').new() - - -- Helper to filter captured messages by a predicate - _G.filter_msgs = function(pred) - local out = {} - for _, m in ipairs(_G.captured) do - if pred(m) then table.insert(out, m) end - end - return out - end - ]]) - end, - post_case = function() - child.lua([[require('eca.observer').unsubscribe('test-capture')]]) - end, - post_once = child.stop, - }, -}) - --- Ensure scheduled callbacks run (vim.schedule) -local function flush(ms) - vim.uv.sleep(ms or 50) - -- Force at least one main loop iteration - child.api.nvim_eval("1") -end - -T["singleton and defaults"] = MiniTest.new_set() - -T["singleton and defaults"]["returns same instance"] = function() - eq(child.lua_get("require('eca.state').new() == require('eca.state').new()"), true) -end - -T["singleton and defaults"]["has expected default values"] = function() - eq(child.lua_get("_G.State.status.state"), "idle") - eq(child.lua_get("_G.State.status.text"), "Idle") - - eq(child.lua_get("vim.tbl_isempty(_G.State.config.behaviors.list)"), true) - eq(child.lua_get("_G.State.config.behaviors.default"), vim.NIL) - eq(child.lua_get("_G.State.config.behaviors.selected"), vim.NIL) - - eq(child.lua_get("vim.tbl_isempty(_G.State.config.models.list)"), true) - eq(child.lua_get("_G.State.config.models.default"), vim.NIL) - eq(child.lua_get("_G.State.config.models.selected"), vim.NIL) - - eq(child.lua_get("_G.State.config.welcome_message"), vim.NIL) - - eq(child.lua_get("_G.State.usage.tokens.limit"), 0) - eq(child.lua_get("_G.State.usage.tokens.session"), 0) - eq(child.lua_get("_G.State.usage.costs.last_message"), "0.00") - eq(child.lua_get("_G.State.usage.costs.session"), "0.00") - - eq(child.lua_get("type(_G.State.tools)"), "table") -end - -T["updates via observer notifications"] = MiniTest.new_set() - -T["updates via observer notifications"]["updates status on progress content"] = function() - child.lua([[require('eca.observer').notify({ - method = 'chat/contentReceived', - params = { content = { type = 'progress', state = 'responding', text = 'Respondendo...' } }, - })]]) - flush() - - eq(child.lua_get("_G.State.status.state"), "responding") - eq(child.lua_get("_G.State.status.text"), "Respondendo...") - - -- Verify a state/updated notification was emitted for status - local updates = child.lua_get([[ _G.filter_msgs(function(m) - return type(m) == 'table' and m.type == 'state/updated' and type(m.content) == 'table' and m.content.status ~= nil - end) ]]) - eq(#updates >= 1, true) -end - -T["updates via observer notifications"]["updates usage on usage content"] = function() - child.lua([[require('eca.observer').notify({ - method = 'chat/contentReceived', - params = { content = { - type = 'usage', - limit = { context = 1024 }, - sessionTokens = 256, - lastMessageCost = '0.42', - sessionCost = '3.14', - } }, - })]]) - flush() - - eq(child.lua_get("_G.State.usage.tokens.limit"), 1024) - eq(child.lua_get("_G.State.usage.tokens.session"), 256) - eq(child.lua_get("_G.State.usage.costs.last_message"), "0.42") - eq(child.lua_get("_G.State.usage.costs.session"), "3.14") - - local updates = child.lua_get([[ _G.filter_msgs(function(m) - return type(m) == 'table' and m.type == 'state/updated' and type(m.content) == 'table' and m.content.usage ~= nil - end) ]]) - eq(#updates >= 1, true) -end - -T["updates via observer notifications"]["updates config on config/updated"] = function() - child.lua([[require('eca.observer').notify({ - method = 'config/updated', - params = { chat = { - behaviors = { 'agent', 'plan' }, - defaultBehavior = 'agent', - selectBehavior = 'plan', - models = { 'openai/gpt-5-mini', 'anthropic/claude' }, - defaultModel = 'openai/gpt-5-mini', - selectModel = 'anthropic/claude', - welcomeMessage = 'Bem-vindo ao ECA!', - } }, - })]]) - flush() - - eq(child.lua_get("_G.State.config.behaviors.list[1]"), "agent") - eq(child.lua_get("_G.State.config.behaviors.list[2]"), "plan") - eq(child.lua_get("_G.State.config.behaviors.default"), "agent") - eq(child.lua_get("_G.State.config.behaviors.selected"), "plan") - - eq(child.lua_get("_G.State.config.models.list[1]"), "openai/gpt-5-mini") - eq(child.lua_get("_G.State.config.models.list[2]"), "anthropic/claude") - eq(child.lua_get("_G.State.config.models.default"), "openai/gpt-5-mini") - eq(child.lua_get("_G.State.config.models.selected"), "anthropic/claude") - - eq(child.lua_get("_G.State.config.welcome_message"), "Bem-vindo ao ECA!") - - local updates = child.lua_get([[ _G.filter_msgs(function(m) - return type(m) == 'table' and m.type == 'state/updated' and type(m.content) == 'table' and m.content.config ~= nil - end) ]]) - eq(#updates >= 1, true) -end - -T["updates via observer notifications"]["updates tools on tool/serverUpdated"] = function() - -- Initial add - child.lua([[require('eca.observer').notify({ - method = 'tool/serverUpdated', - params = { name = 'server-1', type = 'mcp', status = 'connected' }, - })]]) - flush() - - eq(child.lua_get("_G.State.tools['server-1'].name"), "server-1") - eq(child.lua_get("_G.State.tools['server-1'].type"), "mcp") - eq(child.lua_get("_G.State.tools['server-1'].status"), "connected") - - -- Update only status, keep type - child.lua([[require('eca.observer').notify({ - method = 'tool/serverUpdated', - params = { name = 'server-1', status = 'disconnected' }, - })]]) - flush() - - eq(child.lua_get("_G.State.tools['server-1'].type"), "mcp") - eq(child.lua_get("_G.State.tools['server-1'].status"), "disconnected") - - -- Invalid: missing name should be ignored (no errors, no new entries) - local before = child.lua_get("vim.tbl_count(_G.State.tools)") - child.lua([[require('eca.observer').notify({ method = 'tool/serverUpdated', params = { status = 'x' } })]]) - flush() - local after = child.lua_get("vim.tbl_count(_G.State.tools)") - eq(after, before) - - local updates = child.lua_get([[ _G.filter_msgs(function(m) - return type(m) == 'table' and m.type == 'state/updated' and type(m.content) == 'table' and m.content.tools ~= nil - end) ]]) - eq(#updates >= 1, true) -end - -T["update selected model and behavior"] = MiniTest.new_set() - -T["update selected model and behavior"]["update_selected_model updates config"] = function() - child.lua([[ - _G.State.config.models.list = { "model1", "model2" } - _G.State.config.models.selected = "model1" - - _G.State:update_selected_model("model2") - ]]) - - eq(child.lua_get("_G.State.config.models.selected"), "model2") -end - -T["update selected model and behavior"]["update_selected_model handles nil"] = function() - child.lua([[ - _G.State.config.models.selected = "model1" - - -- Should not update if nil is passed - _G.State:update_selected_model(nil) - ]]) - - eq(child.lua_get("_G.State.config.models.selected"), "model1") -end - -T["update selected model and behavior"]["update_selected_model handles non-string"] = function() - child.lua([[ - _G.State.config.models.selected = "model1" - - -- Should not update if non-string is passed - _G.State:update_selected_model(123) - ]]) - - eq(child.lua_get("_G.State.config.models.selected"), "model1") -end - -T["update selected model and behavior"]["update_selected_behavior updates config"] = function() - child.lua([[ - _G.State.config.behaviors.list = { "helpful", "creative" } - _G.State.config.behaviors.selected = "helpful" - - _G.State:update_selected_behavior("creative") - ]]) - - eq(child.lua_get("_G.State.config.behaviors.selected"), "creative") -end - -T["update selected model and behavior"]["update_selected_behavior handles nil"] = function() - child.lua([[ - _G.State.config.behaviors.selected = "helpful" - - -- Should not update if nil is passed - _G.State:update_selected_behavior(nil) - ]]) - - eq(child.lua_get("_G.State.config.behaviors.selected"), "helpful") -end - -T["update selected model and behavior"]["update_selected_behavior handles non-string"] = function() - child.lua([[ - _G.State.config.behaviors.selected = "helpful" - - -- Should not update if non-string is passed - _G.State:update_selected_behavior(123) - ]]) - - eq(child.lua_get("_G.State.config.behaviors.selected"), "helpful") -end - -return T diff --git a/tests/test_stream_queue.lua b/tests/test_stream_queue.lua deleted file mode 100644 index 8cb293a..0000000 --- a/tests/test_stream_queue.lua +++ /dev/null @@ -1,619 +0,0 @@ -local MiniTest = require("mini.test") -local eq = MiniTest.expect.equality -local child = MiniTest.new_child_neovim() - -local T = MiniTest.new_set({ - hooks = { - pre_case = function() - child.restart({ "-u", "scripts/minimal_init.lua" }) - child.lua([[ - _G.StreamQueue = require('eca.stream_queue') - _G.output = "" - _G.chunks_received = {} - ]]) - end, - post_once = child.stop, - }, -}) - --- Ensure scheduled callbacks run (vim.schedule and vim.defer_fn) -local function flush(ms) - vim.uv.sleep(ms or 50) - -- Force at least one main loop iteration - child.api.nvim_eval("1") -end - -T["basic queue operations"] = MiniTest.new_set() - -T["basic queue operations"]["creates a new queue instance"] = function() - child.lua([[ - _G.queue = _G.StreamQueue.new(function(chunk, is_complete) - -- noop - end) - ]]) - - eq(child.lua_get("type(_G.queue)"), "table") - eq(child.lua_get("_G.queue:is_empty()"), true) - eq(child.lua_get("_G.queue:size()"), 0) -end - -T["basic queue operations"]["enqueue triggers processing"] = function() - child.lua([[ - _G.queue = _G.StreamQueue.new(function(chunk, is_complete) - -- noop - end) - _G.queue:enqueue("Hello") - _G.queue:enqueue("World") - ]]) - - -- When items are enqueued, the first starts processing immediately - -- So size will be 1 (second item waiting) and not empty (still processing) - local size = child.lua_get("_G.queue:size()") - local is_empty = child.lua_get("_G.queue:is_empty()") - - -- Either 1 item in queue (first being processed) or 2 items (depending on timing) - eq(size >= 0 and size <= 2, true) - eq(is_empty, false) -end - -T["basic queue operations"]["clear removes all items"] = function() - child.lua([[ - _G.queue = _G.StreamQueue.new(function(chunk, is_complete) - -- noop - end) - _G.queue:enqueue("Hello") - _G.queue:enqueue("World") - _G.queue:clear() - ]]) - - eq(child.lua_get("_G.queue:size()"), 0) - eq(child.lua_get("_G.queue:is_empty()"), true) -end - -T["queue processing"] = MiniTest.new_set() - -T["queue processing"]["processes single text chunk"] = function() - child.lua([[ - _G.output = "" - _G.queue = _G.StreamQueue.new(function(chunk, is_complete) - _G.output = _G.output .. chunk - end, { - chars_per_tick = 2, - tick_delay = 10, - }) - _G.queue:enqueue("Hi") - ]]) - - -- Wait for processing to complete - flush(100) - - eq(child.lua_get("_G.output"), "Hi") - eq(child.lua_get("_G.queue:is_empty()"), true) -end - -T["queue processing"]["processes multiple text chunks in order"] = function() - child.lua([[ - _G.output = "" - _G.queue = _G.StreamQueue.new(function(chunk, is_complete) - _G.output = _G.output .. chunk - end, { - chars_per_tick = 2, - tick_delay = 5, - }) - _G.queue:enqueue("Hello") - _G.queue:enqueue(" ") - _G.queue:enqueue("World") - _G.queue:enqueue("!") - ]]) - - -- Wait for all processing to complete - flush(300) - - eq(child.lua_get("_G.output"), "Hello World!") - eq(child.lua_get("_G.queue:is_empty()"), true) -end - -T["queue processing"]["respects chars_per_tick setting"] = function() - child.lua([[ - _G.chunks_received = {} - _G.queue = _G.StreamQueue.new(function(chunk, is_complete) - table.insert(_G.chunks_received, chunk) - end, { - chars_per_tick = 1, - tick_delay = 5, - }) - _G.queue:enqueue("ABC") - ]]) - - -- Wait for processing to complete - flush(100) - - -- With chars_per_tick = 1, "ABC" should be split into 3 chunks - local chunks = child.lua_get("_G.chunks_received") - eq(#chunks, 3) - eq(chunks[1], "A") - eq(chunks[2], "B") - eq(chunks[3], "C") -end - -T["queue processing"]["calls callback with is_complete flag"] = function() - child.lua([[ - _G.completion_flags = {} - _G.queue = _G.StreamQueue.new(function(chunk, is_complete) - table.insert(_G.completion_flags, is_complete) - end, { - chars_per_tick = 2, - tick_delay = 5, - }) - _G.queue:enqueue("AB") - _G.queue:enqueue("CD") - ]]) - - -- Wait for all processing to complete - flush(150) - - local flags = child.lua_get("_G.completion_flags") - -- The last chunk should have is_complete = true - eq(flags[#flags], true) -end - -T["queue processing"]["respects should_continue callback"] = function() - child.lua([[ - _G.output = "" - _G.should_continue = true - _G.queue = _G.StreamQueue.new(function(chunk, is_complete) - _G.output = _G.output .. chunk - end, { - chars_per_tick = 1, - tick_delay = 10, - should_continue = function() - return _G.should_continue - end, - }) - _G.queue:enqueue("ABCDEF") - ]]) - - -- Let it process a bit - flush(30) - - -- Stop processing - child.lua([[_G.should_continue = false]]) - - -- Wait to ensure it stops - flush(50) - - local output = child.lua_get("_G.output") - -- Should have processed some but not all characters - eq(#output < 6, true) - eq(#output > 0, true) -end - -T["edge cases"] = MiniTest.new_set() - -T["edge cases"]["handles empty text gracefully"] = function() - child.lua([[ - _G.callback_called = false - _G.queue = _G.StreamQueue.new(function(chunk, is_complete) - _G.callback_called = true - end) - _G.queue:enqueue("") - ]]) - - flush(50) - - -- Empty text should not trigger processing - eq(child.lua_get("_G.callback_called"), false) -end - -T["edge cases"]["handles nil text gracefully"] = function() - child.lua([[ - _G.callback_called = false - _G.queue = _G.StreamQueue.new(function(chunk, is_complete) - _G.callback_called = true - end) - _G.queue:enqueue(nil) - ]]) - - flush(50) - - -- Nil text should not trigger processing - eq(child.lua_get("_G.callback_called"), false) -end - -T["edge cases"]["processes queue even with rapid enqueues"] = function() - child.lua([[ - _G.output = "" - _G.queue = _G.StreamQueue.new(function(chunk, is_complete) - _G.output = _G.output .. chunk - end, { - chars_per_tick = 2, - tick_delay = 5, - }) - -- Rapidly enqueue multiple items - for i = 1, 10 do - _G.queue:enqueue(tostring(i)) - end - ]]) - - -- Wait for all processing to complete - flush(500) - - eq(child.lua_get("_G.output"), "12345678910") - eq(child.lua_get("_G.queue:is_empty()"), true) -end - -T["typing speed configuration"] = MiniTest.new_set() - -T["typing speed configuration"]["default speed processes at expected rate"] = function() - child.lua([[ - _G.start_time = vim.loop.hrtime() - _G.output = "" - _G.queue = _G.StreamQueue.new(function(chunk, is_complete) - _G.output = _G.output .. chunk - if is_complete then - _G.end_time = vim.loop.hrtime() - end - end, { - chars_per_tick = 1, -- Default: 1 char at a time - tick_delay = 10, -- Default: 10ms delay - }) - _G.queue:enqueue("ABCDE") -- 5 characters - ]]) - - -- With 1 char per tick and 10ms delay, 5 chars should take at least 40ms - flush(100) - - eq(child.lua_get("_G.output"), "ABCDE") - local duration_ns = child.lua_get("_G.end_time - _G.start_time") - local duration_ms = duration_ns / 1000000 - -- Should take at least 40ms (5 chars * 10ms - overhead for first char) - eq(duration_ms >= 30, true) -end - -T["typing speed configuration"]["fast speed processes quickly"] = function() - child.lua([[ - _G.output = "" - _G.chunks_count = 0 - _G.queue = _G.StreamQueue.new(function(chunk, is_complete) - _G.output = _G.output .. chunk - _G.chunks_count = _G.chunks_count + 1 - end, { - chars_per_tick = 3, -- Fast: 3 chars at a time - tick_delay = 2, -- Fast: 2ms delay - }) - _G.queue:enqueue("ABCDEFGHI") -- 9 characters - ]]) - - flush(50) - - eq(child.lua_get("_G.output"), "ABCDEFGHI") - -- With 3 chars per tick, 9 chars should take 3 chunks - eq(child.lua_get("_G.chunks_count"), 3) -end - -T["typing speed configuration"]["slow speed processes slowly"] = function() - child.lua([[ - _G.start_time = vim.loop.hrtime() - _G.output = "" - _G.queue = _G.StreamQueue.new(function(chunk, is_complete) - _G.output = _G.output .. chunk - if is_complete then - _G.end_time = vim.loop.hrtime() - end - end, { - chars_per_tick = 1, -- Slow: 1 char at a time - tick_delay = 30, -- Slow: 30ms delay - }) - _G.queue:enqueue("ABC") -- 3 characters - ]]) - - flush(150) - - eq(child.lua_get("_G.output"), "ABC") - local duration_ns = child.lua_get("_G.end_time - _G.start_time") - local duration_ms = duration_ns / 1000000 - -- Should take at least 60ms (3 chars * 30ms - overhead for first char) - eq(duration_ms >= 50, true) -end - -T["typing speed configuration"]["instant display with large chars_per_tick"] = function() - child.lua([[ - _G.output = "" - _G.chunks_count = 0 - _G.queue = _G.StreamQueue.new(function(chunk, is_complete) - _G.output = _G.output .. chunk - _G.chunks_count = _G.chunks_count + 1 - end, { - chars_per_tick = 1000, -- Instant: large batch - tick_delay = 0, -- Instant: no delay - }) - _G.queue:enqueue("Hello World!") -- 12 characters - ]]) - - flush(50) - - eq(child.lua_get("_G.output"), "Hello World!") - -- Should process in 1 chunk since chars_per_tick is larger than text - eq(child.lua_get("_G.chunks_count"), 1) -end - -T["typing speed configuration"]["different speeds for different queues"] = function() - child.lua([[ - _G.output_fast = "" - _G.output_slow = "" - - _G.queue_fast = _G.StreamQueue.new(function(chunk, is_complete) - _G.output_fast = _G.output_fast .. chunk - end, { - chars_per_tick = 5, - tick_delay = 1, - }) - - _G.queue_slow = _G.StreamQueue.new(function(chunk, is_complete) - _G.output_slow = _G.output_slow .. chunk - end, { - chars_per_tick = 1, - tick_delay = 20, - }) - - _G.queue_fast:enqueue("FAST") - _G.queue_slow:enqueue("SLOW") - ]]) - - -- Fast should complete quickly - flush(50) - eq(child.lua_get("_G.output_fast"), "FAST") - - -- Slow may still be processing - flush(150) - eq(child.lua_get("_G.output_slow"), "SLOW") -end - --- Integration tests with Sidebar -T["sidebar integration"] = MiniTest.new_set({ - hooks = { - pre_case = function() - child.restart({ "-u", "scripts/minimal_init.lua" }) - child.lua([[ - -- Setup complete environment with Server, State, Mediator, Sidebar - _G.Server = require('eca.server').new() - _G.State = require('eca.state').new() - _G.Mediator = require('eca.mediator').new(_G.Server, _G.State) - _G.Sidebar = require('eca.sidebar').new(1, _G.Mediator) - _G.Sidebar:open() - ]]) - end, - post_case = function() - child.lua([[ if _G.Sidebar then _G.Sidebar:close() end ]]) - end, - }, -}) - -T["sidebar integration"]["initializes stream queue with default config"] = function() - child.lua([[ - local Sidebar = _G.Sidebar - _G.queue_info = { - exists = Sidebar._stream_queue ~= nil, - is_empty = Sidebar._stream_queue and Sidebar._stream_queue:is_empty() or false, - } - ]]) - - local info = child.lua_get("_G.queue_info") - eq(info.exists, true) - eq(info.is_empty, true) -end - -T["sidebar integration"]["streams text with typing effect when enabled"] = function() - child.lua([[ - local Config = require('eca.config') - Config.override({ - windows = { - chat = { - typing = { - enabled = true, - chars_per_tick = 2, - tick_delay = 5, - }, - }, - }, - }) - - -- Recreate sidebar with new config - _G.Sidebar:close() - _G.Sidebar = require('eca.sidebar').new(1, _G.Mediator) - _G.Sidebar:open() - - local Sidebar = _G.Sidebar - - -- Simulate streaming text - Sidebar:handle_chat_content_received({ - chatId = 'chat-typing', - content = { - type = 'text', - text = 'Hello', - }, - }) - - -- Add another chunk (simulates multiple streaming updates) - Sidebar:handle_chat_content_received({ - chatId = 'chat-typing', - content = { - type = 'text', - text = ' World', - }, - }) - ]]) - - -- Wait for typing to complete with faster settings - flush(200) - - child.lua([[ - local Sidebar = _G.Sidebar - local total = Sidebar._current_response_buffer or "" - _G.typing_info = { - total = total, - total_len = #total, - queue_empty = Sidebar._stream_queue:is_empty(), - } - ]]) - - local info = child.lua_get("_G.typing_info") - eq(info.total_len, 11) -- "Hello World" - eq(info.queue_empty, true) -end - -T["sidebar integration"]["displays instantly when typing disabled"] = function() - child.lua([[ - local Config = require('eca.config') - Config.override({ - windows = { - chat = { - typing = { - enabled = false, - }, - }, - }, - }) - - -- Recreate sidebar with new config - _G.Sidebar:close() - _G.Sidebar = require('eca.sidebar').new(1, _G.Mediator) - _G.Sidebar:open() - - local Sidebar = _G.Sidebar - - -- Simulate streaming text - Sidebar:handle_chat_content_received({ - chatId = 'chat-instant', - content = { - type = 'text', - text = 'Instant Display', - }, - }) - ]]) - - -- With typing disabled, text should appear immediately - flush(50) - - child.lua([[ - local Sidebar = _G.Sidebar - _G.instant_info = { - visible = Sidebar._stream_visible_buffer or "", - total = Sidebar._current_response_buffer or "", - } - ]]) - - local info = child.lua_get("_G.instant_info") - eq(info.visible, "Instant Display") - eq(info.total, "Instant Display") -end - -T["sidebar integration"]["respects custom typing speed"] = function() - child.lua([[ - local Config = require('eca.config') - Config.override({ - windows = { - chat = { - typing = { - enabled = true, - chars_per_tick = 3, - tick_delay = 5, - }, - }, - }, - }) - - -- Recreate sidebar with new config - _G.Sidebar:close() - _G.Sidebar = require('eca.sidebar').new(1, _G.Mediator) - _G.Sidebar:open() - - local Sidebar = _G.Sidebar - - -- Simulate streaming text - Sidebar:handle_chat_content_received({ - chatId = 'chat-fast', - content = { - type = 'text', - text = 'ABCDEFGHI', - }, - }) - ]]) - - -- With chars_per_tick=3, should type faster - flush(80) - - local final = child.lua_get("_G.Sidebar._stream_visible_buffer") - eq(final, "ABCDEFGHI") -end - -T["sidebar integration"]["clears queue on new chat"] = function() - child.lua([[ - local Sidebar = _G.Sidebar - - -- Start streaming - Sidebar:handle_chat_content_received({ - chatId = 'chat-1', - content = { - type = 'text', - text = 'First message', - }, - }) - ]]) - - flush(30) - - child.lua([[ - local Sidebar = _G.Sidebar - _G.queue_size_before = Sidebar._stream_queue:size() - - -- Reset for new chat - Sidebar:new_chat() - - _G.queue_size_after = Sidebar._stream_queue:size() - ]]) - - local size_after = child.lua_get("_G.queue_size_after") - - eq(size_after, 0) - eq(child.lua_get("_G.Sidebar._stream_queue:is_empty()"), true) -end - -T["sidebar integration"]["handles multiple text chunks in sequence"] = function() - child.lua([[ - local Sidebar = _G.Sidebar - - -- Simulate multiple streaming chunks - Sidebar:handle_chat_content_received({ - chatId = 'chat-multi', - content = { - type = 'text', - text = 'First ', - }, - }) - - Sidebar:handle_chat_content_received({ - chatId = 'chat-multi', - content = { - type = 'text', - text = 'Second ', - }, - }) - - Sidebar:handle_chat_content_received({ - chatId = 'chat-multi', - content = { - type = 'text', - text = 'Third', - }, - }) - ]]) - - -- Wait for all chunks to be processed - flush(300) - - local final = child.lua_get("_G.Sidebar._current_response_buffer") - eq(final, "First Second Third") -end - -return T diff --git a/tests/test_utils.lua b/tests/test_utils.lua deleted file mode 100644 index ec6671a..0000000 --- a/tests/test_utils.lua +++ /dev/null @@ -1,70 +0,0 @@ -local MiniTest = require("mini.test") -local eq = MiniTest.expect.equality -local child = MiniTest.new_child_neovim() - -local T = MiniTest.new_set({ - hooks = { - pre_case = function() - child.restart({ "-u", "scripts/minimal_init.lua" }) - end, - post_once = child.stop, - }, -}) - -T["utils"] = MiniTest.new_set() - -T["utils"]["shorten_tokens formats numbers correctly"] = function() - child.lua([[ - local Utils = require('eca.utils') - _G.results = { - small = Utils.shorten_tokens(999), - exact_k = Utils.shorten_tokens(1000), - over_k = Utils.shorten_tokens(1500), - large = Utils.shorten_tokens(42000), - very_large = Utils.shorten_tokens(1234567), - nil_input = Utils.shorten_tokens(nil), - string_input = Utils.shorten_tokens("1500"), - } - ]]) - - local results = child.lua_get("_G.results") - - eq(results.small, "999") - eq(results.exact_k, "1k") - eq(results.over_k, "2k") -- Rounds 1500 to 2k - eq(results.large, "42k") - eq(results.very_large, "1235k") - eq(results.nil_input, "0") - eq(results.string_input, "2k") -end - -T["utils"]["split_lines handles various line endings"] = function() - child.lua([[ - local Utils = require('eca.utils') - _G.results = { - unix = Utils.split_lines("line1\nline2\nline3"), - empty = Utils.split_lines(""), - single = Utils.split_lines("single"), - trailing = Utils.split_lines("line1\nline2\n"), - } - ]]) - - local results = child.lua_get("_G.results") - - eq(#results.unix, 3) - eq(results.unix[1], "line1") - eq(results.unix[2], "line2") - eq(results.unix[3], "line3") - - eq(#results.empty, 1) - eq(results.empty[1], "") - - eq(#results.single, 1) - eq(results.single[1], "single") - - -- Trailing newline should create an empty last line - eq(#results.trailing, 3) - eq(results.trailing[3], "") -end - -return T