5 "github.com/gdamore/tcell"
6 "github.com/go-errors/errors"
7 "github.com/mattn/go-isatty"
13 tabSize = 4 // This should be configurable
14 synLinesUp = 75 // How many lines up to look to do syntax highlighting
15 synLinesDown = 75 // How many lines down to look to do syntax highlighting
19 var screen tcell.Screen
21 // LoadInput loads the file input for the editor
22 func LoadInput() (string, []byte, error) {
23 // There are a number of ways micro should start given its input
24 // 1. If it is given a file in os.Args, it should open that
26 // 2. If there is no input file and the input is not a terminal, that means
27 // something is being piped in and the stdin should be opened in an
30 // 3. If there is no input file and the input is a terminal, an empty buffer
33 // These are empty by default so if we get to option 3, we can just returns the
42 // Check that the file exists
43 if _, err := os.Stat(filename); err == nil {
44 input, err = ioutil.ReadFile(filename)
46 } else if !isatty.IsTerminal(os.Stdin.Fd()) {
48 // The input is not a terminal, so something is being piped in
49 // and we should read from stdin
50 input, err = ioutil.ReadAll(os.Stdin)
53 // Option 3, or just return whatever we got
54 return filename, input, err
58 filename, input, err := LoadInput()
64 // Should we enable true color?
65 truecolor := os.Getenv("MICRO_TRUECOLOR") == "1"
67 // In order to enable true color, we have to set the TERM to `xterm-truecolor` when
68 // initializing tcell, but after that, we can set the TERM back to whatever it was
69 oldTerm := os.Getenv("TERM")
71 os.Setenv("TERM", "xterm-truecolor")
74 // Load the syntax files, including the colorscheme
78 screen, err = tcell.NewScreen()
83 if err = screen.Init(); err != nil {
88 // Now we can put the TERM back to what it was before
90 os.Setenv("TERM", oldTerm)
93 // This is just so if we have an error, we can exit cleanly and not completely
94 // mess up the terminal being worked in
96 if err := recover(); err != nil {
98 fmt.Println("Micro encountered an error:", err)
99 // Print the stack trace too
100 fmt.Print(errors.Wrap(err, 2).ErrorStack())
106 defStyle := tcell.StyleDefault.
107 Foreground(tcell.ColorDefault).
108 Background(tcell.ColorDefault)
110 // There may be another default style defined in the colorscheme
111 if style, ok := colorscheme["default"]; ok {
115 screen.SetStyle(defStyle)
118 messenger := new(Messenger)
119 view := NewView(NewBuffer(string(input), filename), messenger)
122 // Display everything
130 // Wait for the user's action
131 event := screen.PollEvent()
133 // Check if we should quit
134 switch e := event.(type) {
135 case *tcell.EventKey:
136 if e.Key() == tcell.KeyCtrlQ {
137 // Make sure not to quit if there are unsaved changes
138 if view.CanClose("Quit anyway? ") {
145 // Send it to the view
146 view.HandleEvent(event)