58 lines
1.3 KiB
Go
58 lines
1.3 KiB
Go
// Package editor opens files in the user's preferred text editor.
|
|
package editor
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"os/exec"
|
|
"runtime"
|
|
)
|
|
|
|
// commonEditors mirrors utils.py's fallback editor list.
|
|
var commonEditors = []string{"code", "subl", "atom", "vim", "nano", "notepad"}
|
|
|
|
// GetEditorCommand returns the command for the system's default editor,
|
|
// prioritizing EDITOR/VISUAL env vars, then falling back to common editors.
|
|
func GetEditorCommand() string {
|
|
if editor := os.Getenv("EDITOR"); editor != "" {
|
|
return editor
|
|
}
|
|
if editor := os.Getenv("VISUAL"); editor != "" {
|
|
return editor
|
|
}
|
|
|
|
editors := commonEditors
|
|
if runtime.GOOS == "windows" {
|
|
editors = append([]string{"notepad"}, editors...)
|
|
}
|
|
|
|
for _, cmd := range editors {
|
|
if path, err := exec.LookPath(cmd); err == nil {
|
|
return path
|
|
}
|
|
}
|
|
|
|
return ""
|
|
}
|
|
|
|
// OpenFileInEditor opens a file in the system default editor. Returns true
|
|
// if successful, false otherwise.
|
|
func OpenFileInEditor(filePath string) bool {
|
|
editor := GetEditorCommand()
|
|
if editor == "" {
|
|
fmt.Println("❌ No editor found. Please set EDITOR or VISUAL environment variable")
|
|
return false
|
|
}
|
|
|
|
cmd := exec.Command(editor, filePath)
|
|
cmd.Stdin = os.Stdin
|
|
cmd.Stdout = os.Stdout
|
|
cmd.Stderr = os.Stderr
|
|
|
|
if err := cmd.Run(); err != nil {
|
|
fmt.Printf("❌ Failed to open editor: %v\n", err)
|
|
return false
|
|
}
|
|
return true
|
|
}
|