Skip to content
mrsharpobluntoPublic

About

Use midi controllers in NeoVim to edit values in text files

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

19 Commits

Folders and files

Repository files navigation

Knobby

CI License: MIT

Knobby captures numbers in Neovim buffers and lets physical rotary encoders edit them. Press an encoder button while the cursor is on a number to capture it; press the same button anywhere to release it.

Captured ranges are stored as Neovim extmarks, so they follow insertions, deletions, line changes, and undo operations. Knobby highlights each captured number and displays its encoder and step inline:

timeout = 42.75 ⟦E4 ±0.01⟧

Requirements

  • Neovim 0.10 or newer
  • Linux/WSL: amidi from alsa-utils and an ALSA raw MIDI input
  • macOS: ReceiveMIDI and a CoreMIDI input
  • Native Windows: receivemidi.exe and a Windows MIDI input

Knobby selects the appropriate backend automatically. On macOS, install ReceiveMIDI with Homebrew. On Windows, download receivemidi.exe from the ReceiveMIDI releases and put it on PATH.

brew install gbevin/tools/receivemidi

Installation

lazy.nvim

Add this entry to the plugin-spec table passed to Lazy:

{
  "mrsharpoblunto/knobby",
  lazy = false,
  opts = {},
}

Lazy infers the knobby Lua module and calls setup() with opts.

For local development, register the working tree as a local plugin instead of prepending it to runtimepath before lazy.setup():

{
  dir = "/home/gconner/dev/knobby",
  name = "knobby",
  lazy = false,
  opts = {},
}

Remove any earlier manual runtimepath:prepend() and setup() calls from init.lua. Lazy will add the complete plugin directory to runtimepath, which is required for runtime features such as :checkhealth knobby discovery.

Native packages

Clone Knobby into Neovim's native start package directory:

git clone https://github.com/mrsharpoblunto/knobby.git \
  ~/.local/share/nvim/site/pack/plugins/start/knobby

Then configure it in init.lua:

require("knobby").setup()

Other plugin managers can install mrsharpoblunto/knobby as a standard runtimepath plugin; call require("knobby").setup() in their configuration hook.

Configuration

Call setup() from init.lua or your plugin manager:

require("knobby").setup({
  midi = {
    backend = "auto",
    command = "auto",
    line_buffered = true,
    port = "auto",
    match = {
      -- name = "^Grid",
      -- Linux/WSL only: usb_id = "303a:8123",
      -- Linux/WSL only: serial = "123456",
    },
    reconnect = true,
  },

  coordination = {
    enabled = true,
    address = "auto",
    scope = "default",
    activation = "focus",
    reconnect_interval_ms = 150,
    broker_timeout_ms = 2000,
  },

  controller = {
    -- Requires Encoder Mode 2 (2's Complement) in Grid Editor.
    profile = "intech_en16",
    turn_flush_ms = 8,
    button_guard_ms = 25,
    roles = {
      navigation = {
        index = false,
        captured_only = false,
        wrap = true,
      },
      step = {
        index = false,
        reset_on_press = true,
      },
    },
  },

  keys = {
    step_down = "[k",
    step_up = "]k",
    step_reset = false,
  },
})

The EN16 profiles map channel 1 CC and note numbers 32 through 47 to encoders 1 through 16. Grid Editor configurations can change those messages; use a custom controller mapping when needed.

Knobby uses the EN16 as an unbounded relative controller. The Grid factory default is Absolute encoder mode, which stops at 0 and 127 and is not supported by the EN16 profile. In Grid Editor, add an Encoder Mode action to each encoder's Setup event and select mode 2 — 2's Complement.

Available EN16 profiles are:

intech_en16                  Relative mode 2 (2's Complement); default
intech_en16_binary_offset    Relative mode 1 (Binary Offset)

Turns are accumulated briefly for turn_flush_ms before being applied. A button press discards the most recent pending turn inside button_guard_ms, applies any earlier movement, and briefly suppresses new rotation. This prevents a push-induced encoder tick from changing a value immediately before capture or release without swallowing a legitimate batch of turns. Both timings are configurable.

Multiple Neovim instances and tmux

Multi-instance coordination is enabled by default. All Knobby instances in the same scope elect one local broker, and only that broker opens the MIDI device. It forwards each event to the active Neovim instance over a Unix-domain socket on Linux/macOS or a named pipe on Windows. Captures remain local to each Neovim instance. If the broker exits, a surviving instance takes over and reopens MIDI automatically.

With activation = "focus", FocusGained makes that Neovim active and FocusLost stops routing to it. This also means the controller does nothing while focus is in a shell pane, another terminal, or another application.

For tmux, enable focus forwarding in ~/.tmux.conf:

set-option -g focus-events on

Reload the file or restart/detach and reattach tmux, then verify it with:

tmux show-options -gv focus-events

It should print on. The outer terminal must also support focus reporting, which current versions of the common terminals do. If focus reporting is not reliable in a particular environment, use manual activation:

require("knobby").setup({
  coordination = {
    activation = "manual",
  },
})

Then use :KnobbyActivate in the instance that should receive events and :KnobbyDeactivate to leave no active recipient. :KnobbyStatus shows the broker/client role, active state, connected instance count, and endpoint.

address = "auto" is normally best. Use a distinct scope for each physical controller or independent Knobby group; automatic endpoint and lock names are derived from it. An explicit address is available for unusual runtime layouts. reconnect_interval_ms controls client election/reconnection, and broker_timeout_ms controls stale-broker takeover.

Special encoder roles

Encoders can optionally be reserved for navigation and step adjustment. For example, this assigns encoder 16 to numeric navigation and encoder 15 to step size:

require("knobby").setup({
  controller = {
    profile = "intech_en16_binary_offset",
    roles = {
      navigation = {
        index = 16,
        captured_only = false,
        wrap = true,
      },
      step = {
        index = 15,
        reset_on_press = true,
      },
    },
  },
})

Turning the navigation encoder clockwise moves to the next capturable number in the current buffer; counterclockwise moves to the previous one. It wraps at the beginning and end by default. Pressing it toggles between all capturable numbers and only numbers that are currently captured. captured_only selects the initial mode, and :KnobbyStatus shows the current mode.

Turning the step encoder clockwise multiplies the captured value's current step by ten; counterclockwise divides it by ten. The cursor must be on a captured number. Its button resets that number to its precision-derived step when reset_on_press = true.

Both roles are disabled when their index is false. A physical encoder can have only one special role, and role indices are reserved from normal MIDI capture/release behavior.

Device selection

midi.backend = "auto" selects amidi on Linux/WSL and receivemidi on macOS and native Windows. midi.command = "auto" uses amidi, receivemidi, or receivemidi.exe as appropriate. Both can be overridden, including with a command list:

midi = {
  backend = "receivemidi",
  command = "/opt/homebrew/bin/receivemidi",
}

USB/IP's Windows BUSID is not part of plugin configuration. It describes a physical Windows USB topology and can change. Knobby discovers the ALSA device inside WSL using its USB ID, serial, card, and MIDI name.

On the development machine, this stable explicit port also works:

require("knobby").setup({
  midi = {
    port = "hw:Grid,0,0",
  },
})

With port = "auto", Knobby chooses a device only when exactly one device matches. An ambiguous match is reported instead of selecting arbitrarily. Use :KnobbyDevices to inspect the available identities. ReceiveMIDI discovery on macOS and Windows exposes port names rather than ALSA USB, serial, and card metadata, so midi.match.name and midi.match.port are the useful selectors.

On the amidi backend, line_buffered = true uses stdbuf when available so long-running amidi processes deliver each MIDI event immediately instead of retaining output in a stdio buffer.

Custom controllers

Contiguous controls can be described compactly:

require("knobby").setup({
  controller = {
    profile = "custom",
    channel = 1,
    controls = {
      count = 8,
      turn = { message = "cc", first_number = 20 },
      press = { message = "note", first_number = 40, minimum_velocity = 1 },
      rotary = { encoding = "twos_complement" },
    },
  },
  midi = {
    match = { name = "^My Controller" },
  },
})

Noncontiguous message layouts use an explicit control list:

controller = {
  profile = "custom",
  controls = {
    {
      index = 1,
      turn = { message = "cc", number = 74 },
      press = { message = "note", number = 48 },
      rotary = { encoding = "inc_dec" },
    },
  },
}

Built-in rotary encodings are absolute_wrap, twos_complement, binary_offset, sign_magnitude, and inc_dec. encoding may also be a function receiving (value, previous_value, options) and returning a signed delta.

Capture behavior and UI

require("knobby").setup({
  capture = {
    duplicate = "reject",       -- or "transfer"
    invalid_number = "release", -- or "keep"
    undo_join_ms = 250,
  },
  ui = {
    highlight = "KnobbyCapture",
    label_highlight = "KnobbyLabel",
    notifications = true,
    virtual_text = {
      enabled = true,
      position = "inline",
      format = " ⟦E%d ±%s⟧",
    },
  },
})

The default step is the power of ten represented by the least-significant displayed digit: 42 uses 1, 42.0 uses 0.1, and 42.750 uses 0.001. Knobby uses exact decimal string arithmetic and preserves displayed precision.

[k divides the step by ten and ]k multiplies it by ten when the cursor is on a captured number. Counts are supported, so 3]k multiplies the step by 1000. The plugin also defines these remapping targets:

<Plug>(KnobbyStepDown)
<Plug>(KnobbyStepUp)
<Plug>(KnobbyStepReset)

Commands

:KnobbyToggle {encoder}  Capture or release an encoder
:KnobbyRelease [encoder] Release one encoder, or all when omitted
:KnobbyStepUp            Multiply the current capture's step by ten
:KnobbyStepDown          Divide the current capture's step by ten
:KnobbyStepReset         Reset from the number's displayed precision
:KnobbyDevices           List discovered raw MIDI inputs
:KnobbyStatus            Show connection and capture state
:KnobbyReconnect         Restart MIDI discovery and input
:KnobbyEnable            Start MIDI input
:KnobbyDisable           Stop MIDI input
:KnobbyActivate          Route MIDI to this Neovim instance
:KnobbyDeactivate        Stop routing MIDI to this Neovim instance
:checkhealth knobby      Diagnose dependencies and device access

For statusline plugins, require("knobby").statusline() returns a compact connection and capture summary. ▶ means this instance is active and · means another instance is active or no instance currently receives MIDI.

macOS setup

macOS provides CoreMIDI, so it does not need USB/IP, ALSA, /dev/snd, or audio-group configuration.

Install ReceiveMIDI and verify that the controller appears:

brew install gbevin/tools/receivemidi
receivemidi list
receivemidi dev "Grid" nn

Turn an encoder or press its button; ReceiveMIDI should print channel 1 control-change ... and channel 1 note-on ... messages. Press Ctrl-C to stop it. The default Knobby configuration then discovers the Grid input by name. If its CoreMIDI port uses a different name, inspect it with :KnobbyDevices and configure either a Lua name pattern or the exact port:

require("knobby").setup({
  midi = {
    match = { name = "^Grid" },
    -- port = "Grid",
  },
})

Native Windows setup

Native Windows Neovim can read the controller directly through Windows MIDI; WSL, USB/IP, ALSA, and an audio group are not involved.

Download the Windows build from the ReceiveMIDI releases, place receivemidi.exe in a directory on PATH, and open a new terminal. Verify the controller in PowerShell:

receivemidi.exe list
receivemidi.exe dev "Grid MIDI" nn

Turning or pressing an encoder should print channel 1 control-change ... or channel 1 note-on .... Press Ctrl-C to stop the monitor. Knobby's default backend = "auto" and command = "auto" settings will now select receivemidi.exe automatically.

If the executable is not on PATH, configure its full path:

require("knobby").setup({
  midi = {
    command = [[C:\Tools\ReceiveMIDI\receivemidi.exe]],
  },
})

The controller cannot be attached to WSL and used by Windows simultaneously. If it is currently attached, detach it before starting native Neovim:

usbipd detach --busid 5-8

When the auto-attach watcher described in Automatic attach on logon is running, it will reclaim the controller for WSL within seconds. Stop it first:

Stop-ScheduledTask -TaskName 'MIDI controller to WSL'

Unplugging and reconnecting the controller also returns it to Windows. It does not need to be unbound from USB/IP when it is not attached to WSL.

Windows and WSL setup

The controller is connected to Windows, while Neovim runs inside WSL. USB/IP passes the complete USB device through to WSL so it can be read as a native ALSA raw MIDI device.

The controller detected during initial setup had these identifiers:

Device:  Intech Grid MIDI device
USB ID:  303a:8123
BUSID:   5-8

5-8 means USB bus 5, port 8; it is one address, not a range. The BUSID can change if the controller is plugged into a different USB port, so match the 303a:8123 USB ID and device name when running usbipd list.

1. Install USB/IP on Windows

Run in PowerShell:

winget install --interactive --exact dorssel.usbipd-win

Open a new PowerShell window afterward so that usbipd is on PATH.

2. Share and attach the controller

In an administrator PowerShell window, list the devices and bind the EN16:

usbipd list
usbipd bind --busid 5-8

Binding is persistent. In a regular PowerShell window, attach it to WSL:

usbipd attach --wsl --busid 5-8

Attachment is not persistent across unplugging the controller, restarting Windows, or shutting down WSL. Repeat the attach command when necessary, or set up Automatic attach on logon below. While attached, the controller's composite MIDI, HID, and serial interfaces belong to WSL rather than Windows.

Automatic attach on logon

Because attachment is not persistent, a small watcher script keeps the controller attached across unplugging, WSL shutdown, and Windows restarts. It is registered as a scheduled task that starts at logon.

Add a one-time USB/IP policy so the device can be bound without elevation whenever Windows re-enumerates it. Run this once in an administrator PowerShell window:

usbipd policy add --effect allow --operation AutoBind --hardware-id 303a:8123

Save the watcher as C:\Users\<user>\bin\MidiUsbipd.ps1:

param(
    [ValidatePattern('^[0-9A-Fa-f]{4}:[0-9A-Fa-f]{4}$')]
    [string] $HardwareId = '303a:8123',

    [string] $Distro = 'Ubuntu',

    [int] $RetrySeconds = 5
)

$ErrorActionPreference = 'Continue'
$usbipd = (Get-Command usbipd.exe -ErrorAction Stop).Source

while ($true) {
    # Make sure the distro is up; usbipd needs a running WSL 2 instance to attach into.
    & wsl.exe -d $Distro --exec /bin/true 2>&1 | Out-Null

    # Blocks for as long as the device stays attached. Exits non-zero when the
    # device is absent, which is the normal case before it is plugged in.
    & $usbipd attach --wsl $Distro --auto-attach --hardware-id $HardwareId 2>&1 |
        ForEach-Object { "[{0}] {1}" -f (Get-Date -Format 'HH:mm:ss'), $_ }

    Start-Sleep -Seconds $RetrySeconds
}

The script matches the controller by its 303a:8123 USB ID rather than by BUSID, so it survives moving the controller to a different USB port. usbipd attach --auto-attach blocks while the device is attached and reattaches it after a detach or unplug. It cannot be started while the device is unplugged unless --busid is used, so the surrounding loop supplies that case: the attach exits immediately when the controller is absent, and the loop retries until it appears.

Register the watcher to run at logon as the interactive user. WSL distributions are per-user, so the task must not run as SYSTEM:

$u = [Security.Principal.WindowsIdentity]::GetCurrent().Name

$action = New-ScheduledTaskAction -Execute 'powershell.exe' `
    -Argument '-NoProfile -WindowStyle Hidden -File "C:\Users\<user>\bin\MidiUsbipd.ps1"'

$trigger = New-ScheduledTaskTrigger -AtLogOn -User $u

$principal = New-ScheduledTaskPrincipal -UserId $u `
    -LogonType Interactive -RunLevel Limited

$settings = New-ScheduledTaskSettingsSet `
    -ExecutionTimeLimit ([TimeSpan]::Zero) `
    -RestartCount 99 `
    -RestartInterval (New-TimeSpan -Minutes 1) `
    -MultipleInstances IgnoreNew `
    -AllowStartIfOnBatteries `
    -DontStopIfGoingOnBatteries

Register-ScheduledTask -TaskName 'MIDI controller to WSL' `
    -Action $action -Trigger $trigger -Principal $principal -Settings $settings -Force

Start-ScheduledTask -TaskName 'MIDI controller to WSL'

Verify it by unplugging and reconnecting the controller, then confirming that it returns to Attached within a few seconds:

usbipd list

usbipd policy requires usbipd-win 5.2 or newer. Stop the watcher with Stop-ScheduledTask -TaskName 'MIDI controller to WSL' and remove it with Unregister-ScheduledTask -TaskName 'MIDI controller to WSL'.

3. Install the ALSA utilities in WSL

sudo apt update
sudo apt install alsa-utils

4. Grant MIDI device access

ALSA creates the raw MIDI endpoint as /dev/snd/midiC0D0, owned by the audio group. Add the current WSL user to that group:

sudo usermod -aG audio "$USER"

The new group membership requires a fresh WSL login. From PowerShell, shut down WSL:

wsl --shutdown

Start WSL again and reattach the controller with usbipd attach if needed.

5. Verify MIDI input

In WSL, confirm that audio appears in the group list:

id -nG

Then list the raw MIDI endpoints:

amidi --list-devices

The EN16 should appear as an Intech Studio Grid endpoint. Use the hardware port reported by amidi to dump incoming messages; during initial setup it was hw:0,0,0:

amidi --port hw:0,0,0 --dump

Turning encoders and pressing their buttons should now print MIDI bytes. Press Ctrl-C to stop the dump.

aconnect limitation

The current Microsoft WSL kernel does not include the ALSA snd-seq module, so aconnect fails because /dev/snd/seq does not exist. This is expected and does not prevent Knobby from working: the plugin can consume MIDI directly from the raw /dev/snd/midiC*D* endpoint. Enabling aconnect would require a custom WSL kernel with ALSA sequencer support.

Development

Run the headless test suite from the repository root:

nvim --clean --headless -u tests/minimal_init.lua -l tests/run.lua

Generate local help tags after editing doc/knobby.txt with:

nvim --clean --headless -u NONE --cmd 'helptags doc' +qa

License

MIT © 2026 Glenn Conner

About

Use midi controllers in NeoVim to edit values in text files

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages