wezterm sessionizer

November 1, 2024

Since moving from tmux to WezTerm native multiplexer the only thing I missed was the tmux-sessionizer script from ThePrimeagen that I have adopted as quite central to my workflow. So I rebuilt it in Lua in WezTerm natively.

How it works

It’s basically a carbon clone of the original tmux-sessionizer script with a couple of notable exceptions:

  1. It uses fd as the underlying search engine (it’s faster than find).
  2. It looks for folders that are .git repositories as opposed to folders at a certain level of nesting. I found that git repositories are my basic unit of work.

Installing

In your ~/.config/wezterm folder create a sessionizer.lua and make sure to update the fd and rootPath values according to your system.

local wezterm = require("wezterm")
local act = wezterm.action

local M = {}

local fd = "/usr/local/bin/fd"

M.toggle = function(window, pane)
  local projects = {}

  local success, stdout, stderr = wezterm.run_child_process({
    fd,
    "-HI",
    "^.git$",
    "--max-depth=4",
    "--prune",
    os.getenv("HOME") .. "/Code",
  })

  if not success then
    wezterm.log_error("Failed to run fd: " .. stderr)
    return
  end

  for line in stdout:gmatch("([^\n]*)\n?") do
    local project = line:gsub("/.git.*$", "")
    local label = project
    local id = project:gsub(".*/", "")
    table.insert(projects, { label = tostring(label), id = tostring(id) })
  end

  window:perform_action(
    act.InputSelector({
      action = wezterm.action_callback(function(win, _, id, label)
        if not id and not label then
          wezterm.log_info("Cancelled")
        else
          wezterm.log_info("Selected " .. label)
          win:perform_action(
            act.SwitchToWorkspace({ name = id, spawn = { cwd = label } }),
            pane
          )
        end
      end),
      fuzzy = true,
      title = "Select project",
      choices = projects,
    }),
    pane
  )
end

return M

And then in your main wezterm.lua config require the sessionizer.lua and assign keybindings of your preference. Example:

local wezterm = require("wezterm")
local sessionizer = require("sessionizer")

return {
  -- ...
  keys = {
    -- ...
    { key = "f", mods = "LEADER", action = wezterm.action_callback(sessionizer.toggle) },
  },
}

< Back