Problem: transstr() has comments that do not add anything to what the
code says, and it casts a length to int only to cast it back to
size_t.
Solution: Drop the comments and keep the length in a size_t
(Hirohito Higashi).
related: vim/vim#20925
closes: vim/vim#21026fe65307d49
Co-authored-by: Hirohito Higashi <h.east.727@gmail.com>
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Problem: sort() with "n", "N" or "f" converts an item to its number on
every comparison. For "n" that is a tv2string() plus strtod()
per comparison, so sorting a list of numbers turns each number
into a string and back O(n log n) times, dwarfing the sort.
Solution: Compute the numeric key of each item once, before the sort,
and compare the stored key (Samuel Schlesinger). Only the
builtin numeric compare modes are affected; uniq(), which
passes a bare list item to the compare function, and the
string and user-function paths are unchanged.
Sorting a list of 100000 numbers (min of 3, macOS arm64):
- sort(l, 'n'): 0.205s -> 0.017s
- sort(l, 'N'): 0.017s -> 0.010s
- sort(l, 'f'): 0.014s -> 0.010s
The result is identical, including that a string is still treated as 0
in "n" mode and that "N" keeps full 64-bit precision.
Add Test_sort_numeric_precomputed(): a large shuffled list sorted with
"n", mixed integers and floats, int64 values beyond the exact range of
a double for "N", and uniq() over the non-precomputed path.
closes: vim/vim#21003c8c59db9df
Co-authored-by: Samuel Schlesinger <sgschlesinger@gmail.com>
Co-authored-by: Claude <noreply@anthropic.com>
Problem: Reading an undo file resolves every stored sequence number
with a linear scan over all headers, making loading
quadratic in the number of undo states.
Solution: Sort uhp_table on uh_seq once and resolve each reference
with a binary search; the duplicate uh_seq check becomes a
single pass over the sorted table (Samuel Schlesinger).
At the default 'undolevels' of 1000 the quadratic cost is not
measurable; it takes 'undolevels' in the tens of thousands to matter.
Loading an undo file with 20000 states and 50 alternate branches with
:rundo goes from 1.49s to 0.11s (min of 3, macOS arm64), with the
same undotree().
Also make old_idx/new_idx/cur_idx and the loop index "i" long instead
of short/int: they index uhp_table, whose length num_head is a long
read from the file. A short index truncated above 32767 headers,
making the restored b_u_oldhead/b_u_newhead/b_u_curhead pointers
wrong in exactly the many-headers case this change is about.
Add tests: a round-trip test with alternate branches that compares
the entries of the tree and the text at every sequence number, a
corruption test with a duplicated uh_seq, and a test for reading an
undo file with zero headers, which is written when only the line for
the "U" command is saved.
closes: vim/vim#20942fccf613c8f
Co-authored-by: Samuel Schlesinger <sgschlesinger@gmail.com>
Co-authored-by: Claude <noreply@anthropic.com>
Problem: In diff mode with 'cursorbind' the cursor in the other window is
not updated after an undo that changes which lines correspond.
Solution: Also check whether the text changed before skipping the update
(Hirohito Higashi).
fixes: vim/vim#20982
related: vim/vim#13219
related: vim/vim#13210
closes: vim/vim#210042045a20d4b
Co-authored-by: Hirohito Higashi <h.east.727@gmail.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Problem:
`1-` does nothing from a directory buffer, because we are already in the
buffer-local CWD. It's also unintuitive that this mapping behaves
differently based on the resolved CWD.
Solution:
Have `1-` open the global CWD.
Now this was a cargo cult anti-pattern to write home about.
Doing painful save-and-restore bookkeeping around a separate
`magic_overruled` decoy global is just as messy as doing painful
save-and-restore logic around `p_magic` itself. only that now you need
to wrap every access to the effective value in a function call.
This replaces this with a marvellous new Clean Code technique™:
passing in the intended behavior as a function parameter to functions
where either the option or an explicit value might be used.
Problem:
A mark moved by nvim_buf_set_extmark() during an edit is misplaced by
undo and redo. Only splices ("edits") are recorded, and replaying them
reproduces the shifts they caused, never the explicit set: the mark ends
up wherever the text pushed it.
Solution:
When an open undo block moves an existing mark, record both positions.
Undo restores the pre-set position, redo re-applies the set.
Partially reverts 18334a4a0c ; ExtmarkSavePos.row/col were unused
because nothing recorded an explicit move, but now `extmark_set()` does.
Problem:
After #40270, events are no longer emitted from the automatic background
detection. This applies not just during startup, but also if the user
manually changes the background of their terminal.
Solution:
Set the background as normal, assuming that a normal terminal will
respond within 100 ms. Change test to match expected behavior:
- BG set during startup won't trigger user autocmds since it runs before
any user config
- If the terminal takes longer than 100 ms to respond to initial OSC 11,
it does trigger the OptionSet, but it is triggered through the normal
path to ensure values like v:option_new are set #38551
- BG change after startup still triggers autocmds #41146
Problem: Crash when getcompletiontype()/getcompletion() gets a NULL string
(dvaave2025).
Solution: Do not write the NUL terminator in set_cmd_context() when the
cursor column is at or past the end of the string, since the
string may be a read-only literal.
fixes: vim/vim#20963closes: vim/vim#20964
Supported by AI.
e2dcefa0d8
Co-authored-by: Christian Brabandt <cb@256bit.org>
Problem: Closing the current tab page resets the alternate tab page, even
when that is another tab page which still exists, so that
CTRL-Tab stops working (igorlfs).
Solution: Restore the last used tab page after entering another one to
close the current one (Hirohito Higashi).
related: vim/vim#20965
closes: vim/vim#20973a05bd64c1d
Co-authored-by: Hirohito Higashi <h.east.727@gmail.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
FAILED …/terminal/ex_terminal_spec.lua @ 270: :terminal (fake shell) spawns in CWD effective at time of invocation
Expected values to differ.
Value:
"~/work/neovim/neovim/build/Xtest_xdg_terminal"
stack traceback:
…/terminal/ex_terminal_spec.lua:276: in function <…/terminal/ex_terminal_spec.lua:270>
Problem:
The insert-mode completion progress-message is in "running" state while
the user is selecting an item. That is noisy and unwanted UX; it was
only intended for the "Scanning..." task.
Solution:
End the progress-msg just after `ins_compl_show_statusmsg`.
Problem:
Some builtin features emit progress-messages which never "complete".
- On failure, `:write` does not complete the progress-msg it started.
- ins-completion never ends its "Scanning..." message.
Solution:
- `buf_write()` emits "failed" status on failure.
- `ins_compl_stop()` ends the completion one.
Problem:
filemess() treats an empty suffix as "a buffer write is starting", but
readfile() calls it that way too. So ":read" (and ":edit", …) opens a
`nvim.bufwrite "<file>"` progress that is never completed.
Users of e.g. ghostty will see a stuck "progress" spinner.
Solution:
Only `buf_write()` starts the progress, via `filemess_progress()`.
Problem:
:bcd (buffer-local directory) is not preserved after
`nvim_open_win` or `nvim_win_set_buf`
Analysis:
set_curbuf() ends with update_cwd(), which falls back to
os_chdir(globaldir) when the target buffer has no b_localdir.
Solution:
Pass kCtxKeepCwd to ctx_switch().
Problem: Messages from tests were not always displayed.
Solution: Always show messages, the timing is always useful. (Ken Takata,
closesvim/vim#6792)
6e3aeec846
Co-authored-by: Bram Moolenaar <Bram@vim.org>
Problem:
Re-editing a buffer (`:edit!`, re-reading a dir.lua buffer, etc.) drops
its `:bcd` directory, so the CWD falls back to the global one. Whereas
other buffer-local state (`b:` vars, local options) survives a reload.
Solution:
Don't clear buf dir in `buf_freeall()`; `do_ecmd()` calls that when
reloading/re-editing. `free_buffer_stuff()` still clears them when
a buffer is freed or reused for another file.
Problem:
`:terminal` does not respect the invocation-time CWD.
This wasn't noticeable with `:lcd` because the window-local CWD gets
applied to the new terminal buffer. But it is noticeable with `:bcd`.
Solution:
Specify `cwd` in the job spec.
Problem:
'linebreak' filler and 'breakindent'/'showbreak' padding are screen
cells with no buffer character behind them, yet a decoration draws over
them whether or not it asked to cover such cells. A highlight bounded to
its text then paints a tail out to the edge of the row, most visible on
inline code spans from plugins. That same highlight already leaves the
cells past the end of a line alone, so it treats identical cells two
different ways.
Solution:
Only a decoration with 'hl_eol' draws the gaps, which is what the flag
already means at the end of a line. A full-width background such as a
fenced code block sets it and still covers them. Classic :syntax has no
such flag and is unchanged.
Problem:
- buf-local CWD scope is lower priority than :lcd, which is weird.
```
win > buf > tab > global
```
- No way to clear current CWD at a given scope.
Solution:
- Rerrange scope precedence to:
```
buf > win > tab > global
```
- Introduce "bang" variants (`:bcd!`/`:lcd!`/`:tcd!`) which clears the
local CWD for the given scope.
Problem:
Evaluating 'statuscolumn' overwrites transchar_charbuf[], which breaks
the drawing of an unprintable char if p_extra points there.
Solution:
Make a copy in wlv.extra so that it won't be overwritten.
Problem:
Giving a window a status line when `'laststatus'` starts requiring one
takes the row from a resizable frame found by walking up the frame
tree, but only the window's own leaf frame is grown back. Every frame
between the leaf and the donor keeps its old height, so a later resize
hands out a row that does not exist and a window's status line ends up
on the command line.
Solution:
Grow the window's frame with `frame_setheight()`, which takes the row
from a neighbouring frame and keeps every enclosing frame consistent.
Problem:
- Explicit `:bcd` (etc.) persists from `nvim_buf_call()` but not from an
autocmd handler targeting a hidden buf (`LspAttach`, `TermRequest`, …),
which needs a `vim.schedule()` workaround.
- `vim._with()` is supposed to work as a "sandbox", discarding
side-effects, but it leaks CWD changes: `:lcd` from a `win` context,
any chdir from a visible-buffer context.
Solution:
- Explicit :cd/:tcd/:bcd during a temp context persists by default.
- "Ambient" directory changes ('autochdir', existing win-local CWD,
etc.) are still undone, as before.
- Add `kCtxKeepDirs`: snapshot/restore the target's full CWD state
(w/b/tp-local, global, cwd). Used by `vim._with()` and `'inccommand'`,
which must not leak state.
Problem: After :diffget into an empty buffer, undo does not restore the
empty buffer, the last line stays behind (Narendran
Gopalakrishnan)
Solution: Include the empty line of the empty buffer in the undo
information, it is deleted once the first line was obtained
(Hirohito Higashi).
fixes: vim/vim#20950closes: vim/vim#20951c44f35ca1a
Co-authored-by: Hirohito Higashi <h.east.727@gmail.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Problem: ins_compl_add() checks for a duplicate by scanning the whole
match list, making collection of N matches quadratic.
Solution: Look matches up in a hashtab instead; each entry counts the
matches with that string (Samuel Schlesinger).
closes: vim/vim#2092631b7b1a7da
Co-authored-by: Samuel Schlesinger <sgschlesinger@gmail.com>
Co-authored-by: Claude <noreply@anthropic.com>
`opts.plain=true` does not expand tildes in addition to environment
variables, unlike `opts.expand_env=false`.
`opts.expand_env=false` is soft-deprecated.
- Avoid shared state. Pass `focus` to set_pos()/expand_msg() instead of
a shared `pager_focus` flag: the flag is only cleared when set_pos()
actually enters the pager, so ":messages" from inside the pager left
it set.
- pager_shown(): the pager window is invalid after leaving it with "q".
- Reuse pager_shown() in expand_msg().
Problem: A message emitted while a previous expanded message is still
visible opens the pager and enters it, moving focus away from
the buffer window without an explicit request (#41061).
Solution: Only enter the pager when it was explicitly requested ("g<",
:messages, or entered from the expanded cmdline). An unfocused
pager is dismissed by the cmdline key handler, which stays armed
across the cmdline and no longer dismisses on non-typed keys
(#39221).
Problem:
During insert-mode / replace-mode, `autowrite` may trigger. If it does, the
cursor position can shift due to the automatic removal of trailing spaces on the
current line. When I resume typing, the space between the last word and the new
word is suddenly gone.
Solution:
Disable the "remove trailing spaces" handler during Insert (or a similar) mode.
Autosave logic is not affected.
Problem:
With `laststatus=3`, a pager float shares the main grid's statusline
row. Setting a diagnostic fires `DiagnosticChanged`, whose handler calls
`nvim__redraw({ statusline = true })`.
Analysis:
Inside the autocmd, `curwin` is temporarily switched to the tiled window
showing that buffer, so `win_redr_status()` paints its statusline over
the pager's `[Pager]` statusline on the shared row. After the autocmd,
`curwin` is restored but the pager statusline is never repainted.
Solution:
Use `ctx_saved_curwin()` decide whether to draw the global statusline,
matching `win_redr_stl_expr()` and `update_screen()`. No behavior change
if no buffer-context switch is active.
Problem: An OSC 52 sequence from a :terminal job passes the decoded
payload to the clipboard provider as a single list item. Command-line
providers (pbcopy, xclip, ...) receive it with channel semantics, where
a newline inside an item is sent as NUL (:h chansend()), so multiline
copies arrive with NUL bytes instead of newlines.
Solution: Split the payload on newlines into a proper list of lines.
A trailing newline yields a final empty item, which chansend() turns
back into a newline, so payloads round-trip exactly.
Problem: A winbar-only window with zero text height still occupies one row,
but win_update() returns early on w_view_height == 0 and skips the
vertical separator.
Solution: Also draw the vertical separator in the early return path.
Problem:
Several subsystems need to derive a short, filesystem-safe identifier from an
arbitrary path, and each reinvents it ad-hoc:
- `'undodir'` and `swapfiles` encode the full path into a single filename, which
may exceed filesystem length-limits.
- `:connect ssh://` needs the SSH ControlPath socket name to stay under the
104-byte `sun_path` limit on macOS; today the path overflows it.
- the upcoming :terminal state dir.
- arbitrary plugin purposes.
Solution:
Provide `vim.fs.slug()`, which generates a bounded, one-way filename from an
arbitrary string. The input is normalized so equivalent paths produce the
same result. An 8-char hash is appended for uniqueness
Problem:
Buffer-local CWD (:bcd) is "sticky", similar to window-local CWD (:lcd).
But this contradicts one of its main benefits: per-buffer "project root"
for LSP, OSC7.
Other problems:
- A buffer created with :edit/:enew/:new silently inherits b_localdir
(and b_prevdir) from the previous buffer.
- curbuf_reusable() refuses to recycle a scratch buffer that has
`b_localdir`.
- After :new/:vnew/:tabnew the CWD sticks to previous buffer's
`b_localdir` even though the new curbuf has none, so :new is not
equivalent to ":split | enew", and getcwd() disagrees with
haslocaldir().
- Requires "which buffer spawned this buffer" semantics that no other
buffer-local state has.
Solution:
Drop sticky/inherit behavior of buffer-local CWD (:bcd).
- do_ecmd: always apply the new curbuf's dir (`fix_current_dir`), like
`do_autochdir` already does. :tabnew from a :bcd buffer now reverts to
global CWD (and fires DirChanged), same as :tabnew from a :lcd window.
- curbuf_reusable(): recycling a scratch buffer frees its b_localdir.
To get sticky/inherit behavior of CWD, use `:lcd`.
Problem:
No way to set a buffer-local directory.
Use-cases:
- "Root dir" for LSP (and the "project" concept).
- `:terminal` OSC 7
Solution:
Add `:bcd` command.
- Extend `getcwd()` to take a third arg; `getcwd(-1, -1, bunfr)` returns
the buffer-local working directory.
- Buffer-local directories have less priority than window-local
ones, and more priority than tab-local ones.
Co-authored-by: Justin M. Keyes <justinkz@gmail.com>
Problem:
FAILED …/plugin/zip_spec.lua @ 442: nvim.zip reports an incorrect archive password
Expected values to be equal.
Expected:
true
Actual:
false
stack traceback:
…/plugin/zip_spec.lua:453: in function <…/plugin/zip_spec.lua:442>
Solution:
The message is scheduled, so poll for it.
Problem:
Ignore is linked to Normal by default, making the text visible instead
of hidden.
Solution:
Replace the default link with an explicit highlight definition using
ctermfg=0 guifg=bg.