Skip to content

Commit 7de24f7

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

File tree

2 files changed

+57
-6
lines changed

2 files changed

+57
-6
lines changed

internal/editor/editor.go

Lines changed: 56 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,70 @@
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+
editorName := GetEditorName(program)
25+
26+
switch editorName {
27+
case "vim", "nvim":
28+
c = exec.Command(program, fmt.Sprintf("+%d", GetLineNumber(fileName, slide)), fileName)
29+
case "code":
30+
c = exec.Command(program, fileName, "--go-to", fmt.Sprintf("+%d", GetLineNumber(fileName, slide)))
31+
default:
32+
c = exec.Command(program, fileName)
33+
}
34+
35+
return tea.ExecProcess(c, nil)
36+
}
37+
38+
func linesMatch(lines []string, sLines []string, start int) bool {
39+
for j := range sLines {
40+
if strings.TrimSpace(lines[start+j]) != strings.TrimSpace(sLines[j]) {
41+
return false
42+
}
43+
}
44+
return true
45+
}
46+
47+
func GetLineNumber(fileName string, slide string) int {
48+
b, err := os.ReadFile(fileName)
49+
if err != nil {
50+
return -1
51+
}
52+
53+
lines := strings.Split(string(b), "\n")
54+
sLines := strings.Split(slide, "\n")
55+
56+
for i := range lines {
57+
if linesMatch(lines, sLines, i) {
58+
return i
59+
}
60+
}
61+
62+
return -1
63+
}
64+
65+
func GetEditorName(editorPath string) string {
66+
parts := strings.Split(editorPath, "/")
67+
return parts[len(parts)-1]
1768
}
1869

1970
func InitEditorFlag(rootCmd *coral.Command) {

internal/model/model.go

Lines changed: 1 addition & 1 deletion
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)