|
1 | 1 | package editor
|
2 | 2 |
|
3 | 3 | import (
|
| 4 | + "fmt" |
| 5 | + "os" |
4 | 6 | "os/exec"
|
| 7 | + "strings" |
5 | 8 |
|
6 | 9 | tea "github.com/charmbracelet/bubbletea"
|
7 | 10 | "github.com/muesli/coral"
|
8 | 11 | )
|
9 | 12 |
|
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 | +}() |
13 | 19 |
|
14 | 20 | // 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 |
17 | 61 | }
|
18 | 62 |
|
19 | 63 | func InitEditorFlag(rootCmd *coral.Command) {
|
|
0 commit comments