Skip to content

Commit d2d792d

Browse files
committed
Editor can jump to line number in vim/nvim
1 parent 1d6f46e commit d2d792d

File tree

2 files changed

+50
-6
lines changed

2 files changed

+50
-6
lines changed

internal/editor/editor.go

+49-5
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,63 @@
11
package editor
22

33
import (
4+
"fmt"
5+
"os"
46
"os/exec"
7+
"strings"
58

69
tea "github.com/charmbracelet/bubbletea"
710
"github.com/muesli/coral"
811
)
912

10-
var (
11-
program = "vim"
12-
)
13+
var program = func() string {
14+
if editor := os.Getenv("EDITOR"); editor != "" {
15+
return editor
16+
}
17+
return "vim"
18+
}()
1319

1420
// Opens the current slide as a split window in tmux.
15-
func OpenNewWindow(fileName string) tea.Cmd {
16-
return tea.ExecProcess(exec.Command(program, fileName), nil)
21+
func OpenNewWindow(fileName string, slide string) tea.Cmd {
22+
var c *exec.Cmd
23+
24+
switch program {
25+
case "vim", "nvim":
26+
c = exec.Command(program, fmt.Sprintf("+%d", GetLineNumber(fileName, slide)), fileName)
27+
case "code":
28+
c = exec.Command(program, fileName, "--go-to", fmt.Sprintf("+%d", GetLineNumber(fileName, slide)))
29+
default:
30+
c = exec.Command(program, fileName)
31+
}
32+
33+
return tea.ExecProcess(c, nil)
34+
}
35+
36+
func linesMatch(lines []string, sLines []string, start int) bool {
37+
for j := range sLines {
38+
if strings.TrimSpace(lines[start+j]) != strings.TrimSpace(sLines[j]) {
39+
return false
40+
}
41+
}
42+
return true
43+
}
44+
45+
func GetLineNumber(fileName string, slide string) int {
46+
b, err := os.ReadFile(fileName)
47+
if err != nil {
48+
return -1
49+
}
50+
51+
lines := strings.Split(string(b), "\n")
52+
sLines := strings.Split(slide, "\n")
53+
54+
for i := range lines {
55+
if linesMatch(lines, sLines, i) {
56+
return i
57+
}
58+
}
59+
60+
return -1
1761
}
1862

1963
func InitEditorFlag(rootCmd *coral.Command) {

internal/model/model.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -180,7 +180,7 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
180180
return m, tea.Quit
181181
case "ctrl+o":
182182
// Opens the current slide in an editor
183-
return m, editor.OpenNewWindow(m.FileName)
183+
return m, editor.OpenNewWindow(m.FileName, m.Slides[m.Page])
184184
default:
185185
newState := navigation.Navigate(navigation.State{
186186
Buffer: m.buffer,

0 commit comments

Comments
 (0)