"Life is all about sharing. If we are good at something, pass it on." - Mary Berry

How I run code in Helix editor?

2023-07-14

Categories: Development Environment

In my previous post, I mentioned that I’ve made the switch to WezTerm and Helix, and today I want to share how I run my code in this setup.

Previously, I would split Wezterm into two panes and run the code in a new pane. However, I found it cumbersome to type different commands for each programming language (Go, C, Racket, and so on). While auto-completion helped to some extent, or using control-p to run the previous command, it still took up a little time.

That’s when I started exploring the possibility of running my code directly from Helix based on the file extension. Unfortunately, Helix didn’t have a variable for the current filename, I have to compile a specific PR to use %val{filename}.

To streamline the process, I created a script that executes different commands based on the file extension:

 1#!/bin/sh
 2
 3pane_id=$(wezterm cli get-pane-direction down)
 4if [ -z "${pane_id}"]; then
 5  pane_id=$(wezterm cli split-pane)
 6fi
 7
 8filename="$1"
 9basedir=$(dirname "$filename")
10basename=$(basename "$filename")
11basename_without_extension="${basename%.*}"
12extension="${filename##*.}"
13
14case "$extension" in
15  "c")
16    run_command="clang -Wall -g -O3 $filename -o $basedir/$basename_without_extension && $basedir/$basename_without_extension"
17    ;;
18  "go")
19    run_command="go run $filename"
20    ;;
21  "rkt")
22    run_command="racket $filename"
23    ;;
24esac
25
26echo "${run_command}" | wezterm cli send-text --pane-id $pane_id --no-paste

Then I made the following addition to the Helix’s config file:

1[keys.normal.";"]
2r = ":sh run.sh %val{filename}"

With this setup, you can now simply press ;, followed by r to run your code directly from Helix.

Additionally, I enabled auto-save by adding the following lines to ~/.config/helix/config.toml

1[editor]
2auto-save=true

Tags: helix wezterm

Edit on GitHub

Related Posts: