Helix keybinding: copy file location + selected code for coding agents
I have been using a small Helix keybinding that has turned out to be very useful when working with coding agents.
The idea is simple: select some code, press a key, and copy both:
- the current file location, including line range
- the selected text, wrapped in a Markdown code fence
This makes it easy to paste precise context into ChatGPT, Codex, Claude, GitHub issues, or review comments.
For example, selecting a few lines and pressing Space l copies something like this:
src/main.rs:L42-L44
```
fn main() {
println!("hello");
}
```
Space L does the same thing, but expands the file path to an absolute path.
Requirements
This depends on current Helix preview/master because it uses :set-register.
The keybinding also uses Helix expansion variables such as %{buffer_name}, %{selection_line_start}, %{selection_line_end}, and %{selection}.
I use Nushell as the editor shell so the small script can stay reasonably cross-platform:
[editor]
shell = ["nu", "-c"]
Configuration
[editor]
shell = ["nu", "-c"]
[keys.normal]
# Copy the current primary selection together with its relative file location.
space.l = [
"extend_to_line_bounds",
''':set-register l %sh{
let file = "%{buffer_name}"
let start = ("%{selection_line_start}" | into int)
let end = ("%{selection_line_end}" | into int)
let first_line = ([$start, $end] | math min)
let last_line = ([$start, $end] | math max)
if $first_line == $last_line {
print -n $"($file):L($first_line)"
} else {
print -n $"($file):L($first_line)-L($last_line)"
}
}''',
''':set-register + %reg{l}
```
%{selection}```''',
":clear-register l",
]
# Same as Space-l, but expand the file location to an absolute path.
space.L = [
"extend_to_line_bounds",
''':set-register l %sh{
let file = ("%{buffer_name}" | path expand)
let start = ("%{selection_line_start}" | into int)
let end = ("%{selection_line_end}" | into int)
let first_line = ([$start, $end] | math min)
let last_line = ([$start, $end] | math max)
if $first_line == $last_line {
print -n $"($file):L($first_line)"
} else {
print -n $"($file):L($first_line)-L($last_line)"
}
}''',
''':set-register + %reg{l}
```
%{selection}```''',
":clear-register l",
]
Notes
extend_to_line_bounds is intentional here. When I send code to an agent, I usually want complete lines rather than a partial character selection.
The temporary l register is only used to build the location string. The final result is written to the system clipboard register +, then the temporary register is cleared.
The relative-path version is better for repository-local discussion. The absolute-path version is useful when the receiving tool has access to the same local filesystem and can open the exact file directly.