Skip to content

Commit

Permalink
Editor can jump to line number in vim/nvim
Browse files Browse the repository at this point in the history
  • Loading branch information
waelmahrous committed Oct 31, 2024
1 parent 1d6f46e commit b860333
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 6 deletions.
54 changes: 49 additions & 5 deletions internal/editor/editor.go
Original file line number Diff line number Diff line change
@@ -1,19 +1,63 @@
package editor

import (
"fmt"
"os"
"os/exec"
"strings"

tea "github.com/charmbracelet/bubbletea"
"github.com/muesli/coral"
)

var (
program = "vim"
)
var program = func() string {
if editor := os.Getenv("EDITOR"); editor != "" {
return editor
}
return "vim"
}()

// Opens the current slide as a split window in tmux.
func OpenNewWindow(fileName string) tea.Cmd {
return tea.ExecProcess(exec.Command(program, fileName), nil)
func OpenNewWindow(fileName string, slide string) tea.Cmd {
var c *exec.Cmd

switch program {
case "vim", "nvim":
c = exec.Command(program, fmt.Sprintf("+%d", GetLineNumber(fileName, slide)), fileName)
case "code":
c = exec.Command(program, fileName, "--go-to", fmt.Sprintf("+%d", GetLineNumber(fileName, slide)))
default:
c = exec.Command(program, fileName)
}

return tea.ExecProcess(c, nil)
}

func linesMatch(lines []string, sLines []string, start int) bool {
for j := range sLines {
if strings.TrimSpace(lines[start+j]) != strings.TrimSpace(sLines[j]) {
return false
}
}
return true
}

func GetLineNumber(fileName string, slide string) int {
b, err := os.ReadFile(fileName)
if err != nil {
return -1
}

lines := strings.Split(string(b), "\n")
sLines := strings.Split(slide, "\n")

for i := 0; i <= len(lines)-len(sLines); i++ {
if linesMatch(lines, sLines, i) {
return i
}
}

return -1
}

func InitEditorFlag(rootCmd *coral.Command) {
Expand Down
2 changes: 1 addition & 1 deletion internal/model/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
return m, tea.Quit
case "ctrl+o":
// Opens the current slide in an editor
return m, editor.OpenNewWindow(m.FileName)
return m, editor.OpenNewWindow(m.FileName, m.Slides[m.Page])
default:
newState := navigation.Navigate(navigation.State{
Buffer: m.buffer,
Expand Down

0 comments on commit b860333

Please sign in to comment.