vim again, and tmux too

This commit is contained in:
Jana Dönszelmann 2026-03-10 20:47:24 +01:00
parent 397fb19e0b
commit 5f5daf1047
No known key found for this signature in database
15 changed files with 451 additions and 231 deletions

View file

@ -19,134 +19,32 @@ local esc = vim.api.nvim_replace_termcodes(
)
local api = require('Comment.api')
vim.keymap.set("n", "<C-_>", ":lua require('Comment.api').toggle.linewise.current()<CR> j", { remap = true })
vim.keymap.set("n", "<C-_>", ":lua require('Comment.api').toggle.linewise.current()<CR>j", { remap = true })
vim.keymap.set("i", "<C-_>", "<c-o>:lua require('Comment.api').toggle.linewise.current()<CR>", { remap = true })
vim.keymap.set("x", "<C-_>", function()
vim.api.nvim_feedkeys(esc, 'nx', false)
api.toggle.linewise(vim.fn.visualmode())
end, { remap = true })
vim.keymap.set('n', 'gr', (function() builtin.lsp_references({jump_type="vsplit"}) end), {})
vim.keymap.set('n', 'gd', (function() builtin.lsp_definitions({jump_type="vsplit"}) end), {})
vim.keymap.set('n', 'gt', (function() builtin.lsp_type_definitions({jump_type="vsplit"}) end), {})
local barbar_state = require("barbar.state")
function find_windows_with_buffer(bufnum)
windows = {}
local window_list = vim.api.nvim_list_wins()
-- vim.keymap.set('n', 'gr', (function() builtin.lsp_references({jump_type="vsplit"}) end), {})
-- vim.keymap.set('n', 'gd', (function() builtin.lsp_definitions({jump_type="vsplit"}) end), {})
-- vim.keymap.set('n', 'gt', (function() builtin.lsp_type_definitions({jump_type="vsplit"}) end), {})
-- vim.keymap.set('n', 'gt', (function() builtin.lsp_type_definitions({jump_type="vsplit"}) end), {})
for _, window in ipairs(window_list) do
local win_info = vim.fn.getwininfo(window)
if win_info ~= nil then
for _, buf in ipairs(win_info) do
if buf.bufnr == bufnum then
table.insert(windows, window)
end
end
end
end
return windows
end
function num_useful_windows()
local window_list = vim.api.nvim_tabpage_list_wins(0)
local num = 0
for _, window in ipairs(window_list) do
local win_info = vim.fn.getwininfo(window)
if win_info ~= nil then
for _, win_info in ipairs(win_info) do
if buf_is_useful(win_info.bufnr) then
num = num + 1
end
end
end
end
return num
end
function buf_is_useful(bufnr)
local bufname = vim.api.nvim_buf_get_name(bufnr)
-- if the window's buffer has no name, it's not useful
if bufname == '' then
return false
end
-- print("bufname: ", bufname)
-- if the window's buffer is read only, it's not useful
local readonly = vim.api.nvim_buf_get_option(bufnr, 'readonly')
if readonly then
-- print("=readonly")
return false
end
-- -- if the buffer is not listed, it's not useful
local listed = vim.api.nvim_buf_get_option(bufnr, 'buflisted')
if not listed then
-- print("=unlisted")
return false
end
local buftype = vim.api.nvim_buf_get_option(bufnr, 'buftype')
if buftype == "quickfix" then
-- print("=readonly")
return false
end
local lines = vim.api.nvim_buf_get_lines(bufnr, 0, -1, false)
if #lines > 1 or (#lines == 1 and #lines[1] > 0) then
return true -- If the buffer has content, return false
else
return false
end
-- the window contains a useful buffer
return true
end
function quit_window(window)
vim.api.nvim_win_call(window, function()
vim.cmd "quit"
end)
end
vim.api.nvim_create_user_command('CloseBuffer', function (opts)
if num_useful_windows() > 1 then
vim.cmd {
cmd = "quit",
bang = opts.bang,
}
else
vim.cmd {
cmd = "BufferDelete",
bang = opts.bang,
}
if not buf_is_useful(vim.api.nvim_get_current_buf()) then
vim.cmd {
cmd = "quit",
bang = opts.bang,
}
end
end
end, { desc = "Close Current Buffer", bang = true, })
local function close_floating()
for _, win in ipairs(vim.api.nvim_list_wins()) do
local config = vim.api.nvim_win_get_config(win)
if config.relative ~= "" then
vim.api.nvim_win_close(win, false)
end
end
end
vim.keymap.set("n", "<Esc>", close_floating, { desc = "Close floats, clear highlights" })
-- local function close_floating()
-- for _, win in ipairs(vim.api.nvim_list_wins()) do
-- local config = vim.api.nvim_win_get_config(win)
-- if config.relative ~= "" then
-- vim.api.nvim_win_close(win, false)
-- end
-- end
-- end
--
-- vim.keymap.set("n", "<Esc>", close_floating, { desc = "Close floats, clear highlights" })
local builtin = require('telescope.builtin')

View file

@ -1,15 +1,64 @@
_: {
custom.program.nvim.requirements = [ "cli" ];
custom.program.nvim.home-config =
{ pkgs, flakes, ... }:
{
pkgs,
flakes,
lib,
...
}:
let
nvim_mime_types = [
"application/x-zerosize"
"text/english"
"text/plain"
"text/x-makefile"
"text/x-c++hdr"
"text/x-c++src"
"text/x-chdr"
"text/x-csrc"
"text/x-java"
"text/x-moc"
"text/x-pascal"
"text/x-tcl"
"text/x-tex"
"application/x-shellscript"
"text/x-c"
"text/x-c++"
];
desktop-entry-name = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaanvim";
desktop-entry = pkgs.makeDesktopItem {
name = desktop-entry-name;
desktopName = "neovim";
exec = "${./editor-hax.py} %F";
tryExec = "${./editor-hax.py}";
terminal = false;
type = "Application";
categories = [
"Utility"
"TextEditor"
];
icon = "terminal";
mimeTypes = nvim_mime_types;
};
in
{
home = {
sessionVariables = {
EDITOR = "nvim";
};
};
home.file.".local/share/applications/${desktop-entry-name}.desktop" = {
source = "${desktop-entry}/share/applications/${desktop-entry-name}.desktop";
};
xdg.mimeApps.associations.added = lib.mergeAttrsList (
map (mime: {
${mime} = [ "${desktop-entry-name}.desktop" ];
}) nvim_mime_types
);
imports = [
flakes.nixvim.homeModules.nixvim
./options.nix
@ -98,7 +147,9 @@ _: {
# lspconfig.noteslsp.setup{}
# ''
+ (builtins.readFile ./config.lua);
extraConfigLuaPost = ''
'';
};
};
}

119
programs/nvim/editor-hax.py Executable file
View file

@ -0,0 +1,119 @@
#!/usr/bin/env python
import subprocess
import os
import sys
import re
from urllib.parse import urlsplit
extract_line_regex = re.compile(r"(.*?)(?::([0-9]+))?(?::([0-9]+))?(:)?$")
main_editor = "nvim"
editors = [main_editor, "vim", "vi"]
real_editor = os.environ.get("REAL_EDITOR", None)
editor_command = main_editor
if real_editor is not None:
editors.append(real_editor)
editor_command = real_editor
def run(cmd, only_stdout=True):
res = subprocess.run(cmd, capture_output=True, text=True, shell=True)
if only_stdout:
return str(res.stdout)
else:
return res
def find_pane(window):
for editor in editors:
pane = run(f"tmux list-panes -a -f '#{{&&:#{{==:#{{window_id}},{window}}},#{{==:#{{pane_current_command}},{editor}}}}}' -F '#{{pane_id}}'").strip();
if pane != "":
return pane
def create_pane(args):
run(f'tmux split-window -h -P -F "#{{pane_id}}" {editor_command} {args}')
def find_or_create_pane(window, args):
if pane := find_pane(window):
# exit copy mode so we don't send these commands directly to tmux
run(f"tmux send-keys -t {pane} -X cancel")
# Escape for some reason doesn't get sent as the escape key if it shows up next to any other keys???
run(f"tmux send-keys -t {pane} Escape")
# note the space, this tells nvim not to save it in history
run(f"tmux send-keys -t {pane} \": drop {args}\" Enter")
run(f"tmux select-pane -t {pane} -Z")
else:
create_pane(args)
def split_line(filename):
mtch = extract_line_regex.match(filename)
file = mtch.group(1)
line = mtch.group(2)
column = mtch.group(3)
url = urlsplit(line)
if url.scheme == "file" and url.path != file:
file = url.path
file = os.path.abspath(file)
print(f"opening {file}:{line}:{column}")
return file, line, column
def join_line(filename, maybe_line, maybe_column):
assert not (maybe_line is None and maybe_column is not None)
if maybe_line is None:
return filename
if maybe_column is None:
maybe_column = "0"
return f"+normal!{maybe_line}G{maybe_column} {filename}"
def trim(arg):
if arg.startswith("\"") and not arg.endswith("\""):
arg = arg.lstrip("\"")
if arg.endswith("\"") and not arg.startswith("\""):
arg = arg.rstrip("\"")
return arg.strip()
def editor_hax(filename):
args = split_line(trim(filename))
current_window = run("tmux display-message -p \"#{window_id}\"").strip();
find_or_create_pane(current_window, join_line(*args))
def xdg_open(arg):
subprocess.run(f"xdg-open {trim(arg)}", shell=True)
def xdg_open_proxy(*args):
for arg in args:
try:
_file, line, _column = split_line(arg)
if line is not None:
editor_hax(arg)
else:
xdg_open(arg)
except:
xdg_open(arg)
def usage():
print(f"usage: {sys.argv[0]} filename:(line):(column)")
print(" Opens a file with line number and colum in the editor in another pane of the current tmux window")
print(f"usage: {sys.argv[0]} xdg-open-proxy filename:(line):(column)")
print(" Calls xdg-open on the given parameters. However, if any part contains a line number and or column, opens in nvim like editor-hax")
exit(1)
if __name__ == "__main__":
if len(sys.argv) < 2:
usage()
elif sys.argv[1] == "xdg-open-proxy":
if len(sys.argv) < 3:
usage()
else:
xdg_open_proxy(*sys.argv[1:])
elif len(sys.argv) > 2:
usage()
else:
editor_hax(sys.argv[1])

View file

@ -17,39 +17,23 @@ in
# splitting
(map "n" "<leader>s" "<cmd>vertical sb<cr>")
# closing
(map "n" "<leader>w" "<cmd>BufferClose<cr>") # single buffer
(map "n" "<leader>cb" "<cmd>BufferClose<cr>") # single buffer
(map "n" "<leader>ct" "<cmd>CloseBuffer<cr>") # buffer or extra tab
(map "n" "<leader>q" "<cmd>CloseBuffer<cr>") # buffer or extra tab
(map "n" "<leader>co" "<cmd>silent! BufferCloseAllButVisible<cr>") # other buffers
(map "n" "<leader>cl" "<cmd>silent! BufferCloseBuffersLeft<cr>") # other buffers (left)
(map "n" "<leader>cr" "<cmd>silent! BufferCloseBuffersRight<cr>") # other buffers (right)
# moving
(map "n" "mL" "<cmd>BufferMovePrevious<cr>") # left
(map "n" "mr" "<cmd>BufferMoveNext<cr>") # right
(map "n" "m0" "<cmd>BufferMoveStart<cr>") # start
(map "n" "m$" "<cmd>BufferMoveEnd<cr>") # end
(map "n" "<leader>jb" "<cmd>BufferPick<cr>") # jump to tab
# jumplist
# (map "n" "<leader><Tab>" "<C-o>")
# (map "n" "<leader><S-Tab>" "<C-i>")
(map "" "<C-a>" "<C-i>") # note: C-a is actually C-i, remapped through kitty.
(luamap "n" "<leader>r" "${telescope}.jumplist()")
(luamap "n" "<leader>R" "${telescope}.loclist()")
# pickers
(luamap "n" "<leader><leader>" "${telescope}.find_files()")
(luamap "n" "<leader>f" "${telescope}.live_grep()")
(luamap "n" "<leader>t" "${telescope}.lsp_document_symbols()")
(luamap "n" "<leader>T" "${telescope}.lsp_dynamic_workspace_symbols()")
(luamap "n" "<leader>/" "${telescope}.current_buffer_fuzzy_find()")
# last used pickers/searches
(luamap "n" "<leader>h" "${telescope}.pickers()")
(luamap "n" "<leader>p" "${telescope}.pickers()")
(luamap "n" "<leader>m" "${telescope}.search_history()")
# open buffers
(luamap "n" "<leader>b" "${telescope}.buffers({sort_mru = true})")
(luamap "n" "<leader><Tab>" "${telescope}.buffers({sort_mru = true})")
# diagnostics
(map "n" "<leader>d" "<cmd>Trouble diagnostics toggle filter.buf=0<cr>")
@ -69,26 +53,25 @@ in
# expand macro
(map "n" "<leader>em" "<cmd>RustLsp expandMacro<cr>")
# easier quitting etc
(map "ca" "W" "w")
(map "ca" "X" "x")
(map "ca" "Q" "CloseBuffer")
(map "ca" "q" "CloseBuffer")
# navigation
(map "" "<leader><Left>" "<C-w><Left>")
(map "" "<leader><Right>" "<C-w><Right>")
(map "" "<leader><Up>" "<C-w><Up>")
(map "" "<leader><Down>" "<C-w><Down>")
(map "" "<leader><Down>" "<C-w><Down>")
(map "" "<leader>h" "<C-w><Left>")
(map "" "<leader>l" "<C-w><Right>")
(map "" "<leader>k" "<C-w><Up>")
(map "" "<leader>j" "<C-w><Down>")
# close buffer
(map "" "<leader>c" "<cmd>bd<cr>")
# {
# key = "/";
# action = "<cmd>lua require('spectre').open_file_search({select_word=true})<CR>";
# }
(map "n" "t" "<cmd>Neotree toggle<cr>")
# (map "n" "t" "<cmd>Neotree toggle<cr>")
# tab for indent/dedent
(map "n" "<tab>" ">>_")
@ -98,6 +81,9 @@ in
(map "v" "<S-tab>" "<gv")
# to avoid many typos
# easier quitting etc
(map "n" ";" ":")
(map "ca" "W" "w")
(map "ca" "X" "x")
];
}

View file

@ -84,5 +84,9 @@ _: {
"noselect"
"noinsert"
];
# disable auto-folding
foldlevel = 99;
foldlevelstart = 99;
};
}

View file

@ -10,15 +10,6 @@ let
};
};
in
# fzy-lua-native = pkgs.vimUtils.buildVimPlugin {
# name = "fzy-lua-native";
# src = pkgs.fetchFromGitHub {
# owner = "romgrk";
# repo = "fzy-lua-native";
# rev = "9d720745d5c2fb563c0d86c17d77612a3519c506";
# hash = "sha256-pBV5iGa1+5gtM9BcDk8I5SKoQ9sydOJHsmyoBcxAct0=";
# };
# };
{
programs.nixvim = {
plugins = {
@ -168,7 +159,11 @@ in
crates.enable = true;
fidget.enable = true;
nvim-autopairs.enable = true;
# nvim-highlight-colors.enable = true;
spider.enable = true;
origami = {
enable = true;
settings.autofold.enabled = false;
};
cmp = {
enable = true;
@ -221,11 +216,15 @@ in
"<C-Space>" = "cmp.mapping.complete()";
"<CR>" = "cmp.mapping.confirm({ select = true })";
"<C-d>" = ''
function()
if cmp.visible_docs() then
cmp.close_docs()
function(fallback)
if cmp.visible() then
if cmp.visible_docs() then
cmp.close_docs()
else
cmp.open_docs()
end
else
cmp.open_docs()
fallback()
end
end
'';
@ -270,7 +269,7 @@ in
};
auto-session = {
enable = true;
enable = false;
settings = {
auto_save_enabled = true;
auto_restore_enabled = true;
@ -288,7 +287,7 @@ in
};
neo-tree = {
enable = true;
enable = false;
settings = {
close_if_last_window = true;
enable_git_status = false;
@ -660,7 +659,7 @@ in
return wilder.renderer_mux({
[':'] = popupmenu_renderer,
['/'] = wildmenu_renderer,
substitute = wildmenu_renderer,
substitute = wildmenu_enderer,
})
end)()
'';
@ -695,7 +694,7 @@ in
];
defaults = {
path_display = [ "smart" ];
layout_strategy = "horizontal";
layout_strategy = "flex";
layout_config = {
width = 0.99;
height = 0.99;
@ -709,15 +708,6 @@ in
enable = true;
};
# tabs
barbar = {
enable = true;
settings = {
options.diagnostics = "nvim_lsp";
focus_on_close = "previous";
};
};
# for lsp/cmp inside markdown code blocks
otter = {
enable = true;