Skip to content

Commit 90c81c4

Browse files
authored
fix: remove local for top-level variable declarations only (#14)
* fix: remove locals for top-level declarations only * specs: update
1 parent e9e7777 commit 90c81c4

18 files changed

Lines changed: 110 additions & 388 deletions

.busted

Lines changed: 0 additions & 15 deletions
This file was deleted.

.github/workflows/test_develop.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
---
2-
name: develop
2+
name: Tests
33
on:
44
pull_request: ~
55
push:

.github/workflows/test_main.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
---
2-
name: main
2+
name: Tests
33
on:
44
pull_request: ~
55
push:

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
.todo.md
2+
.tests

Makefile

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,5 @@
1-
set_lua_paths = eval $$(luarocks path --lua-version 5.1 --bin)
2-
busted = $$(find /usr/local/lib/luarocks/*/busted/* -name busted)
3-
set_luals_path = PATH="$$PATH:/home/yaro/.local/share/nvim/mason/bin/lua-language-server"
4-
5-
test_unit = busted --run=unit
6-
test_nvim = nvim --headless -i NONE -n -u spec/minimal_init.lua -l $(busted) --run=unit
1+
test=nvim -l tests/minit.lua tests -o utfTerminal -Xoutput --color -v
2+
#--shuffle-tests
73

84
tag ?= wip
95
watch = '*.lua'
@@ -19,19 +15,19 @@ llscheck:
1915
@$(set_luals_path) && llscheck --configpath .luarc.json .
2016

2117
luacheck:
22-
luacheck lua spec scripts
18+
luacheck lua tests scripts
2319

2420
stylua:
2521
stylua --check lua scripts spec
2622

2723
test:
28-
@$(set_lua_paths); $(test_unit)
24+
@$(test)
2925

3026
watch:
31-
@$(set_lua_paths); while sleep 0.1; do find . -name $(watch) | entr -d -c $(test_unit); done
27+
@while sleep 0.1; do find . -name $(watch) | entr -d -c $(test); done
3228

3329
watch_tag:
34-
@$(set_lua_paths); while sleep 0.1; do find . -name $(watch) | entr -d -c $(test_unit) --tags=$(tag); done
30+
@while sleep 0.1; do find . -name $(watch) | entr -d -c $(test) --tags=$(tag); done
3531

3632
test_nvim:
3733
@$(test_nvim) spec/unit

README.md

Lines changed: 14 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,10 @@
11
# 💻 Lua console ![main](https://github.com/yarospace/lua-console.nvim/actions/workflows/test_main.yml/badge.svg?branch=main) ![develop](https://github.com/yarospace/lua-console.nvim/actions/workflows/test_develop.yml/badge.svg?branch=develop) [![LuaRocks](https://img.shields.io/luarocks/v/YaroSpace/lua-console.nvim?logo=lua&color=purple)](https://luarocks.org/modules/YaroSpace/lua-console.nvim)
22

3-
**lua-console.nvim** - is a handy scratch pad / REPL / debug console for Lua development and Neovim exploration and configuration.
4-
Acts as a user friendly replacement of command mode - messages loop and as a handy scratch pad to store and test your code gists.
5-
6-
7-
**Update:** although it originated as a tool for Lua development, it has now evolved into supporting other languages too. See [`evaluating other languages`](#evaluating-other-languages).
3+
**lua-console.nvim** - is a REPL / scratch pad / debug console for Neovim.
4+
Supports Lua natively and can be extended for other languages.
85

96
<br/><img src="https://github.com/YaroSpace/assets/blob/main/lua-console.nvim/demo.gif">
107

11-
## 💡 Motivation
12-
13-
After installing Neovim, it took me some time to configure it, learn its settings, structure and API, while learning Lua in the process.
14-
I got fed up of constantly hitting `:`, typing `lua= command`, then typing `:messages` to see the output, only to find out that a made a typo or a
15-
syntax error and retyping the whole thing again, copying the paths from error stacktraces and so on. I needed something better, so there it is.
16-
17-
<br>
18-
198
## ✨ Features
209

2110
- Evaluate single line expressions and statements, visually selected lines or characters of code or the whole buffer
@@ -28,8 +17,6 @@ syntax error and retyping the whole thing again, copying the paths from error st
2817
- Use as a scratch pad for code gists
2918
- Attach code evaluators to any buffer
3019

31-
<br>
32-
3320
## 📦 Installation
3421

3522
With [lazy.nvim](https://github.com/folke/lazy.nvim):
@@ -58,8 +45,8 @@ require('lua-console').setup { your_custom_options }
5845
> [!NOTE]
5946
> All settings are self explanatory, but please read below about [`preserve_context`](#-notes-on-globals-locals-and-preserving-execution-context) option.
6047
61-
Mappings are local to the console, except the ones for toggling the console - `` ` `` and attaching to a buffer - ``<Leader>` ``. All mappings can be overridden in your custom
62-
config. If you want to delete a mapping - set its value to `false`.
48+
Mappings are local to the console, except the ones for toggling the console - `` ` `` and attaching to a buffer - ``<Leader>` ``.
49+
All mappings can be overridden in your custom config. If you want to delete a mapping - set its value to `false`.
6350

6451
<details><summary>Default Settings</summary>
6552

@@ -74,7 +61,7 @@ opts = {
7461
autosave = true, -- autosave on console hide / close
7562
load_on_start = true, -- load saved session on start
7663
preserve_context = true, -- preserve results between evaluations
77-
strip_local = true, -- remove local identifier from source code
64+
strip_local = true, -- strip `local` from top-level variable declarations
7865
show_one_line_results = true, -- prints one line results, even if already shown as virtual text
7966
notify_result = false, -- notify result
8067
clear_before_eval = false, -- clear output below result prefix before evaluation of the whole buffer
@@ -105,14 +92,12 @@ opts = {
10592

10693
</details>
10794

108-
<br>
109-
11095
## 🚀 Basic usage (with default mappings)
11196

11297
- Install, press the mapped key `` ` `` and start exploring.
11398
- Enter code as normal, in insert mode.
11499
- Hit `Enter` in normal mode to evaluate a variable, statement or an expression in the current line.
115-
- Visually select a region or a range of lines and press `Enter` to evaluate the code in the range or use `<S-Enter>` to evaluate the whole console.
100+
- Visually select a region or a range of lines and press `Enter` to evaluate the code in the range or use `<S-Enter>` to evaluate the whole buffer.
116101
- The evaluation of the last line is returned and printed, so no `return` is needed in most cases.
117102
To avoid noise, if the return of your execution is `nil`, e.g. from a loop or a function without return, it will not be printed, but shown as virtual text.
118103
The result of assignments on the last line will be also shown as virtual text.
@@ -136,11 +121,14 @@ opts = {
136121
> [!IMPORTANT]
137122
> By default, the option `preserve_context` is on, which means that the execution context is preserved between evaluations.
138123
139-
All the code executed in the console is evaluated in isolated environment. This means that any variables you declare without the `local` keyword will not be persisted
140-
in Neovim's global environment, although all global variables are accessible. If you want purposefully to alter the global state, use `_G.My_variable = ..`.
124+
All the code executed in the console is evaluated in isolated environment, which means that any global variables that you declare will not be persisted in Neovim's global environment.
125+
If you purposefully want to alter the global state, use `_G.My_variable = ..`.
126+
127+
The option `preserve_context` implies that variables without `local` will be stored in the console's local context and preserved between executions.
141128

142-
The option `preserve_context` means that although you declare variables without `local`, they will be stored in console's local context and preserved between separate executions.
143-
So, if you first execute `a = 1`, then `a = a + 1` and then `a` - you will get `2`. Variables with `local` are also preserved, unless you set the `strip_local` option to `false`.
129+
So, if you first execute `a = 1`, then `a = a + 1` and then `a` - you will get `2`.
130+
131+
Also, by default, the option `strip_local` is on, which means that `local` modifier is stripped from top-level variable declarations and these variables are also stored in the context.
144132

145133
If you want the context to be cleared before every execution, set `preserve_context = false`.
146134

@@ -149,8 +137,6 @@ There are two functions available within the console:
149137
- `_ctx` - will print the contents of the context
150138
- `_ctx_clear()` - clears the context
151139

152-
<br>
153-
154140
## ⭐ Extra features
155141

156142
### Attaching code evaluator to other buffers
@@ -162,8 +148,7 @@ There are two functions available within the console:
162148

163149
#### Setting up
164150

165-
- It is possible to setup external code executors for other languages. Evaluators for `ruby`,`racket` and `python` are working out of the box, support for other languages is coming.
166-
Meanwhile, you can easily setup your own language.
151+
- It is possible to setup external code executors for other languages. Evaluators for `ruby`,`racket` and `python` are working out of the box, support for other can be easily added.
167152
- Below is the default configuration, which can be overridden or extended by your custom config, where `default_process_opts` will be
168153
replaced by language specific opts, e.g. a possible config for `python` could be:
169154

@@ -291,7 +276,6 @@ There are a number of alternatives available, notably:
291276
- [Luadev](https://github.com/bfredl/nvim-luadev)
292277
- [SnipRun](https://github.com/michaelb/sniprun)
293278

294-
Initially, when starting with Lua and Neovim, I tried all the REPLs/code runners I could find. However, I was not satisfied with all of them in one way or another.
295279
Lua-console is an attempt to combine the best features of all of them, like REPL / scratch pad / code runner / debug console, while leaving the UX and config simple.
296280

297281
<br>

lua/lua-console/config.lua

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ local default_config = {
77
autosave = true, -- autosave on console hide / close
88
load_on_start = true, -- load saved session on start
99
preserve_context = true, -- preserve results between evaluations
10-
strip_local = true, -- remove local identifier from source code
10+
strip_local = true, -- strip "local" modifier from top level variables
1111
show_one_line_results = true, -- prints one line results, even if already shown as virtual text
1212
notify_result = false, -- notify result
1313
clear_before_eval = false, -- clear output below result prefix before evaluation of the whole buffer

lua/lua-console/utils.lua

Lines changed: 30 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,7 @@ end
153153
local get_line_assignment = function(line)
154154
if not line or #line == 0 then return end
155155

156-
local lhs = line[1]:match('^(.-)%s*=')
156+
local lhs = line[1]:gsub('^%s*local%s+', ''):match('^(.-)%s*=')
157157
local ret
158158

159159
if lhs then
@@ -177,6 +177,7 @@ local get_last_assignment = function()
177177

178178
for i = lnum - 1, 0, -1 do
179179
line = vim.api.nvim_buf_get_lines(0, i, i + 1, false)[1]
180+
line = line:gsub('^%s*local%s+', '')
180181

181182
if line:match('^%s*' .. last_var .. '%s*,?[^=]-=') then break end
182183
offset = offset + 1
@@ -265,12 +266,6 @@ local append_current_buffer = function(buf, lines, lnum)
265266
vim.api.nvim_buf_set_lines(buf, lnum, lnum, false, lines)
266267
end
267268

268-
local function remove_empty_lines(tbl)
269-
return vim.tbl_filter(function(el)
270-
return vim.fn.trim(el) ~= ''
271-
end, tbl)
272-
end
273-
274269
local function trim_empty_lines(tbl)
275270
if #tbl == 0 then return tbl end
276271

@@ -358,6 +353,32 @@ local function run_code(code)
358353
return result
359354
end
360355

356+
local function strip_local(lines)
357+
lines = vim.split(lines, '\n')
358+
359+
local ts = vim.treesitter
360+
local ret = {}
361+
362+
local start_row = math.max(0, vim.fn.line('.') - 1 - #lines)
363+
364+
for i, line in ipairs(lines) do
365+
local cs, ce = 1, 1
366+
367+
while cs do
368+
cs, ce = line:find('local%s', ce)
369+
370+
if cs then
371+
local node = ts.get_node { pos = { start_row + i - 1, cs } }
372+
if node and node:parent():type() == 'chunk' then line = line:sub(1, cs - 1) .. line:sub(ce + 1) end
373+
end
374+
end
375+
376+
table.insert(ret, line)
377+
end
378+
379+
return table.concat(ret, '\n')
380+
end
381+
361382
--- Evaluates Lua code and returns pretty printed result with errors if any
362383
--- @param lines string[] table with lines of Lua code
363384
--- @param ctx? table environment to execute code in
@@ -378,7 +399,7 @@ function lua_evaluator(lines, ctx)
378399
end
379400

380401
lines = to_string(lines)
381-
lines = config.buffer.strip_local and lines:gsub('local ', '') or lines
402+
lines = config.buffer.strip_local and strip_local(lines) or lines
382403

383404
local code, errors = load(lines, 'Lua console: ', 't', env)
384405
if errors then return to_table(errors) end
@@ -453,6 +474,7 @@ local get_external_evaluator = function(buf, lang)
453474
local fun = opts.on_exit
454475
opts.on_exit = function(system_completed)
455476
vim.schedule(function()
477+
if not vim.api.nvim_buf_is_valid(buf) then return end
456478
vim.api.nvim_buf_del_extmark(buf, ns, 10)
457479
_ = fun and fun(system_completed)
458480
end)
@@ -549,7 +571,6 @@ local eval_code_in_buffer = function(buf, full)
549571
vim.fn.cursor(v_end, 0)
550572

551573
lines = lines or vim.api.nvim_buf_get_lines(buf, v_start - 1, v_end, false)
552-
lines = remove_empty_lines(lines)
553574
if #lines == 0 then return end
554575

555576
local evaluator = get_evaluator(buf, v_start - 1)

spec/log.lua

Lines changed: 0 additions & 46 deletions
This file was deleted.

spec/minimal_init.lua

Lines changed: 0 additions & 2 deletions
This file was deleted.

0 commit comments

Comments
 (0)