13 "github.com/go-errors/errors"
14 "github.com/layeh/gopher-luar"
15 "github.com/mattn/go-isatty"
16 "github.com/mitchellh/go-homedir"
17 "github.com/yuin/gopher-lua"
18 "github.com/zyedidia/clipboard"
19 "github.com/zyedidia/tcell"
20 "github.com/zyedidia/tcell/encoding"
24 synLinesUp = 75 // How many lines up to look to do syntax highlighting
25 synLinesDown = 75 // How many lines down to look to do syntax highlighting
26 doubleClickThreshold = 400 // How many milliseconds to wait before a second click is not a double click
27 undoThreshold = 500 // If two events are less than n milliseconds apart, undo both of them
28 autosaveTime = 8 // Number of seconds to wait before autosaving
35 // Object to send messages and prompts to the user
38 // The default highlighting style
39 // This simply defines the default foreground and background colors
42 // Where the user's configuration is
43 // This should be $XDG_CONFIG_HOME/micro
44 // If $XDG_CONFIG_HOME is not set, it is ~/.config/micro
47 // Version is the version number or commit hash
48 // These variables should be set by the linker when compiling
50 CommitHash = "Unknown"
51 CompileDate = "Unknown"
54 // This is the VM that runs the plugins
59 // This is the currently open tab
60 // It's just an index to the tab in the tabs array
63 // Channel of jobs running in the background
66 events chan tcell.Event
70 // LoadInput determines which files should be loaded into buffers
71 // based on the input stored in flag.Args()
72 func LoadInput() []*Buffer {
73 // There are a number of ways micro should start given its input
75 // 1. If it is given a files in flag.Args(), it should open those
77 // 2. If there is no input file and the input is not a terminal, that means
78 // something is being piped in and the stdin should be opened in an
81 // 3. If there is no input file and the input is a terminal, an empty buffer
89 if len(flag.Args()) > 0 {
91 // We go through each file and load it
92 for i := 0; i < len(flag.Args()); i++ {
93 filename = flag.Args()[i]
95 // Check that the file exists
96 if _, e := os.Stat(filename); e == nil {
97 // If it exists we load it into a buffer
98 input, err = ioutil.ReadFile(filename)
105 // If the file didn't exist, input will be empty, and we'll open an empty buffer
106 buffers = append(buffers, NewBuffer(input, filename))
108 } else if !isatty.IsTerminal(os.Stdin.Fd()) {
110 // The input is not a terminal, so something is being piped in
111 // and we should read from stdin
112 input, err = ioutil.ReadAll(os.Stdin)
114 TermMessage("Error reading from stdin: ", err)
117 buffers = append(buffers, NewBuffer(input, filename))
119 // Option 3, just open an empty buffer
120 buffers = append(buffers, NewBuffer(input, filename))
126 // InitConfigDir finds the configuration directory for micro according to the XDG spec.
127 // If no directory is found, it creates one.
128 func InitConfigDir() {
129 xdgHome := os.Getenv("XDG_CONFIG_HOME")
131 // The user has not set $XDG_CONFIG_HOME so we should act like it was set to ~/.config
132 home, err := homedir.Dir()
134 TermMessage("Error finding your home directory\nCan't load config files")
137 xdgHome = home + "/.config"
139 configDir = xdgHome + "/micro"
141 if _, err := os.Stat(xdgHome); os.IsNotExist(err) {
142 // If the xdgHome doesn't exist we should create it
143 err = os.Mkdir(xdgHome, os.ModePerm)
145 TermMessage("Error creating XDG_CONFIG_HOME directory: " + err.Error())
149 if _, err := os.Stat(configDir); os.IsNotExist(err) {
150 // If the micro specific config directory doesn't exist we should create that too
151 err = os.Mkdir(configDir, os.ModePerm)
153 TermMessage("Error creating configuration directory: " + err.Error())
158 // InitScreen creates and initializes the tcell screen
160 // Should we enable true color?
161 truecolor := os.Getenv("MICRO_TRUECOLOR") == "1"
163 // In order to enable true color, we have to set the TERM to `xterm-truecolor` when
164 // initializing tcell, but after that, we can set the TERM back to whatever it was
165 oldTerm := os.Getenv("TERM")
167 os.Setenv("TERM", "xterm-truecolor")
172 screen, err = tcell.NewScreen()
177 if err = screen.Init(); err != nil {
182 // Now we can put the TERM back to what it was before
184 os.Setenv("TERM", oldTerm)
187 screen.SetStyle(defStyle)
191 // RedrawAll redraws everything -- all the views and the messenger
194 for _, v := range tabs[curTab].views {
202 // Passing -version as a flag will have micro print out the version number
203 var flagVersion = flag.Bool("version", false, "Show the version number and information")
204 var flagStartPos = flag.String("startpos", "", "LINE,COL to start the cursor at when opening a buffer.")
207 flag.Usage = func() {
208 fmt.Println("Usage: micro [OPTIONS] [FILE]...")
209 fmt.Print("Micro's options can be set via command line arguments for quick adjustments. For real configuration, please use the bindings.json file (see 'help options').\n\n")
213 optionFlags := make(map[string]*string)
215 for k, v := range DefaultGlobalSettings() {
216 optionFlags[k] = flag.String(k, "", fmt.Sprintf("The %s option. Default value: '%v'", k, v))
222 // If -version was passed
223 fmt.Println("Version:", Version)
224 fmt.Println("Commit hash:", CommitHash)
225 fmt.Println("Compiled on", CompileDate)
229 // Start the Lua VM for running plugins
233 // Some encoding stuff in case the user isn't using UTF-8
235 tcell.SetEncodingFallback(tcell.EncodingFallbackASCII)
237 // Find the user's configuration directory (probably $XDG_CONFIG_HOME/micro)
240 // Build a list of available Extensions (Syntax, Colorscheme etc.)
243 // Load the user's settings
252 // This is just so if we have an error, we can exit cleanly and not completely
253 // mess up the terminal being worked in
254 // In other words we need to shut down tcell before the program crashes
256 if err := recover(); err != nil {
258 fmt.Println("Micro encountered an error:", err)
259 // Print the stack trace too
260 fmt.Print(errors.Wrap(err, 2).ErrorStack())
265 // Create a new messenger
266 // This is used for sending the user messages in the bottom of the editor
267 messenger = new(Messenger)
268 messenger.history = make(map[string][]string)
270 // Now we load the input
271 buffers := LoadInput()
272 for _, buf := range buffers {
273 // For each buffer we create a new tab and place the view in that tab
274 tab := NewTabFromView(NewView(buf))
275 tab.SetNum(len(tabs))
276 tabs = append(tabs, tab)
277 for _, t := range tabs {
278 for _, v := range t.views {
280 if globalSettings["syntax"].(bool) {
289 for k, v := range optionFlags {
295 // Load all the plugin stuff
296 // We give plugins access to a bunch of variables here which could be useful to them
297 L.SetGlobal("OS", luar.New(L, runtime.GOOS))
298 L.SetGlobal("tabs", luar.New(L, tabs))
299 L.SetGlobal("curTab", luar.New(L, curTab))
300 L.SetGlobal("messenger", luar.New(L, messenger))
301 L.SetGlobal("GetOption", luar.New(L, GetOption))
302 L.SetGlobal("AddOption", luar.New(L, AddOption))
303 L.SetGlobal("SetOption", luar.New(L, SetOption))
304 L.SetGlobal("SetLocalOption", luar.New(L, SetLocalOption))
305 L.SetGlobal("BindKey", luar.New(L, BindKey))
306 L.SetGlobal("MakeCommand", luar.New(L, MakeCommand))
307 L.SetGlobal("CurView", luar.New(L, CurView))
308 L.SetGlobal("IsWordChar", luar.New(L, IsWordChar))
309 L.SetGlobal("HandleCommand", luar.New(L, HandleCommand))
310 L.SetGlobal("HandleShellCommand", luar.New(L, HandleShellCommand))
311 L.SetGlobal("GetLeadingWhitespace", luar.New(L, GetLeadingWhitespace))
312 L.SetGlobal("MakeCompletion", luar.New(L, MakeCompletion))
313 L.SetGlobal("NewBuffer", luar.New(L, NewBuffer))
314 L.SetGlobal("RuneStr", luar.New(L, func(r rune) string {
317 L.SetGlobal("Loc", luar.New(L, func(x, y int) Loc {
320 L.SetGlobal("JoinPaths", luar.New(L, filepath.Join))
321 L.SetGlobal("configDir", luar.New(L, configDir))
323 // Used for asynchronous jobs
324 L.SetGlobal("JobStart", luar.New(L, JobStart))
325 L.SetGlobal("JobSend", luar.New(L, JobSend))
326 L.SetGlobal("JobStop", luar.New(L, JobStop))
329 L.SetGlobal("ReadRuntimeFile", luar.New(L, PluginReadRuntimeFile))
330 L.SetGlobal("ListRuntimeFiles", luar.New(L, PluginListRuntimeFiles))
331 L.SetGlobal("AddRuntimeFile", luar.New(L, PluginAddRuntimeFile))
332 L.SetGlobal("AddRuntimeFilesFromDirectory", luar.New(L, PluginAddRuntimeFilesFromDirectory))
334 jobs = make(chan JobFunction, 100)
335 events = make(chan tcell.Event, 100)
336 autosave = make(chan bool)
340 // Load the syntax files, including the colorscheme
343 for _, t := range tabs {
344 for _, v := range t.views {
347 for _, pl := range loadedPlugins {
348 _, err := Call(pl+".onViewOpen", v)
349 if err != nil && !strings.HasPrefix(err.Error(), "function does not exist") {
354 if v.Buf.Settings["syntax"].(bool) {
360 // Here is the event loop which runs in a separate thread
363 events <- screen.PollEvent()
369 time.Sleep(autosaveTime * time.Second)
370 if globalSettings["autosave"].(bool) {
377 // Display everything
380 var event tcell.Event
382 // Check for new events
385 // If a new job has finished while running in the background we should execute the callback
386 f.function(f.output, f.args...)
390 case event = <-events:
394 switch e := event.(type) {
395 case *tcell.EventMouse:
396 if e.Buttons() == tcell.Button1 {
397 // If the user left clicked we check a couple things
398 _, h := screen.Size()
400 if y == h-1 && messenger.message != "" && globalSettings["infobar"].(bool) {
401 // If the user clicked in the bottom bar, and there is a message down there
402 // we copy it to the clipboard.
403 // Often error messages are displayed down there so it can be useful to easily
405 clipboard.WriteAll(messenger.message, "primary")
409 if CurView().mouseReleased {
410 // We loop through each view in the current tab and make sure the current view
411 // is the one being clicked in
412 for _, v := range tabs[curTab].views {
413 if x >= v.x && x < v.x+v.width && y >= v.y && y < v.y+v.height {
414 tabs[curTab].curView = v.Num
421 // This function checks the mouse event for the possibility of changing the current tab
422 // If the tab was changed it returns true
423 if TabbarHandleMouseEvent(event) {
428 // Since searching is done in real time, we need to redraw every time
429 // there is a new event in the search bar so we need a special function
430 // to run instead of the standard HandleEvent.
431 HandleSearchEvent(event, CurView())
433 // Send it to the view
434 CurView().HandleEvent(event)
438 case event = <-events: