Skip to content

Commit ac27fa2

Browse files
committed
refactor: make VirtualIndent start_watch_org_indent idempotent
This ensures we can call `start_watch_org_indent` as much as we want without starting a bunch of timers in the background. This enforces the use of `start_watch_org_indent` and `stop_watch_org_indent` for managing the timer.
1 parent e5482df commit ac27fa2

File tree

1 file changed

+21
-15
lines changed

1 file changed

+21
-15
lines changed

lua/orgmode/ui/virtual_indent.lua

+21-15
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ local tree_utils = require('orgmode.utils.treesitter')
55
---@field private _attached boolean Whether or not VirtualIndent is attached for its buffer
66
---@field private _bufnrs {integer: boolean} Buffers with VirtualIndent attached
77
---@field private _timer uv_timer_t Timer used for tracking `org_indent_mode`
8+
---@field private _watcher_running boolean Whether or not VirtualIndent is reacting to `vim.borg_indent_mode`
89
local VirtualIndent = {
910
_ns_id = vim.api.nvim_create_namespace('orgmode.ui.indent'),
1011
_bufnrs = {},
@@ -29,6 +30,7 @@ function VirtualIndent:new(bufnr)
2930
new._bufnr = bufnr
3031
new._attached = false
3132
VirtualIndent._bufnrs[new._bufnr] = new
33+
new._watcher_running = false
3234
new._timer = vim.uv.new_timer()
3335
return new
3436
end
@@ -92,27 +94,31 @@ function VirtualIndent:set_indent(start_line, end_line, ignore_ts)
9294
end
9395
end
9496

95-
--- Begins a timer to check `vim.b.org_indent_mode` and correctly attach or detatch VirtualIndent as
96-
--- necessary
97+
--- Begins a timer to check `vim.b.org_indent_mode` if `vim.b.org_indent_mode` is not already being
98+
--- monitored
9799
function VirtualIndent:start_watch_org_indent()
98-
self._timer:start(
99-
50,
100-
50,
101-
vim.schedule_wrap(function()
102-
local success, indent_mode_enabled = pcall(vim.api.nvim_buf_get_var, self._bufnr, 'org_indent_mode')
103-
if success and indent_mode_enabled then
104-
if not self._attached then
105-
self:attach()
100+
if not self._watcher_running then
101+
self._watcher_running = true
102+
self._timer:start(
103+
50,
104+
50,
105+
vim.schedule_wrap(function()
106+
local success, indent_mode_enabled = pcall(vim.api.nvim_buf_get_var, self._bufnr, 'org_indent_mode')
107+
if success and indent_mode_enabled then
108+
if not self._attached then
109+
self:attach()
110+
end
111+
elseif self._attached then
112+
self:detach()
106113
end
107-
elseif self._attached then
108-
self:detach()
109-
end
110-
end)
111-
)
114+
end)
115+
)
116+
end
112117
end
113118

114119
--- Stops the current VirtualIndent instance from reacting to changes in `vim.b.org_indent_mode`
115120
function VirtualIndent:stop_watch_org_indent()
121+
self._watcher_running = false
116122
self._timer:stop()
117123
end
118124

0 commit comments

Comments
 (0)