|
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 | + 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] |
17 | 68 | } |
18 | 69 |
|
19 | 70 | func InitEditorFlag(rootCmd *coral.Command) { |
|
0 commit comments