7 luar "layeh.com/gopher-luar"
9 lua "github.com/yuin/gopher-lua"
10 "github.com/zyedidia/micro/internal/buffer"
11 "github.com/zyedidia/micro/internal/config"
12 "github.com/zyedidia/micro/internal/display"
13 ulua "github.com/zyedidia/micro/internal/lua"
14 "github.com/zyedidia/micro/internal/screen"
15 "github.com/zyedidia/tcell"
18 type BufKeyAction func(*BufPane) bool
19 type BufMouseAction func(*BufPane, *tcell.EventMouse) bool
21 var BufKeyBindings map[Event]BufKeyAction
22 var BufKeyStrings map[Event]string
23 var BufMouseBindings map[MouseEvent]BufMouseAction
26 BufKeyBindings = make(map[Event]BufKeyAction)
27 BufKeyStrings = make(map[Event]string)
28 BufMouseBindings = make(map[MouseEvent]BufMouseAction)
31 func LuaAction(fn string) func(*BufPane) bool {
32 luaFn := strings.Split(fn, ".")
36 plName, plFn := luaFn[0], luaFn[1]
37 pl := config.FindPlugin(plName)
41 return func(h *BufPane) bool {
42 val, err := pl.Call(plFn, luar.New(ulua.L, h))
44 screen.TermMessage(err)
46 if v, ok := val.(lua.LBool); !ok {
54 // BufMapKey maps a key event to an action
55 func BufMapKey(k Event, action string) {
56 BufKeyStrings[k] = action
57 var actionfns []func(*BufPane) bool
65 // TODO: fix problem when complex bindings have these
66 // characters (escape them?)
67 idx := strings.IndexAny(action, "&|,")
71 types = append(types, action[idx])
72 action = action[idx+1:]
74 types = append(types, ' ')
78 var afn func(*BufPane) bool
79 if strings.HasPrefix(a, "command:") {
80 a = strings.SplitN(a, ":", 2)[1]
81 afn = CommandAction(a)
82 names = append(names, "")
83 } else if strings.HasPrefix(a, "command-edit:") {
84 a = strings.SplitN(a, ":", 2)[1]
85 afn = CommandEditAction(a)
86 names = append(names, "")
87 } else if strings.HasPrefix(a, "lua:") {
88 a = strings.SplitN(a, ":", 2)[1]
91 screen.TermMessage("Lua Error:", a, "does not exist")
94 names = append(names, "")
95 } else if f, ok := BufKeyActions[a]; ok {
97 names = append(names, a)
99 screen.TermMessage("Error:", a, "does not exist")
102 actionfns = append(actionfns, afn)
104 BufKeyBindings[k] = func(h *BufPane) bool {
105 cursors := h.Buf.GetCursors()
107 for i, a := range actionfns {
108 for j, c := range cursors {
109 h.Buf.SetCurCursor(c.Num)
111 if i == 0 || (success && types[i-1] == '&') || (!success && types[i-1] == '|') || (types[i-1] == ',') {
112 success = h.execAction(a, names[i], j)
122 // BufMapMouse maps a mouse event to an action
123 func BufMapMouse(k MouseEvent, action string) {
124 if f, ok := BufMouseActions[action]; ok {
125 BufMouseBindings[k] = f
127 delete(BufMouseBindings, k)
132 // The BufPane connects the buffer and the window
133 // It provides a cursor (or multiple) and defines a set of actions
134 // that can be taken on the buffer
135 // The ActionHandler can access the window for necessary info about
136 // visual positions for mouse clicks and scrolling
137 type BufPane struct {
142 Cursor *buffer.Cursor // the active cursor
144 // Since tcell doesn't differentiate between a mouse release event
145 // and a mouse move event with no keys pressed, we need to keep
146 // track of whether or not the mouse was pressed (or not released) last event to determine
147 // mouse release events
150 // We need to keep track of insert key press toggle
152 // This stores when the last click was
153 // This is useful for detecting double and triple clicks
154 lastClickTime time.Time
157 // lastCutTime stores when the last ctrl+k was issued.
158 // It is used for clearing the clipboard to replace it with fresh cut lines.
159 lastCutTime time.Time
161 // freshClip returns true if the clipboard has never been pasted.
164 // Was the last mouse event actually a double click?
165 // Useful for detecting triple clicks -- if a double click is detected
166 // but the last mouse event was actually a double click, it's a triple click
168 // Same here, just to keep track for mouse move events
171 // Last search stores the last successful search for FindNext and FindPrev
173 // Should the current multiple cursor selection search based on word or
174 // based on selection (false for selection, true for word)
179 // remember original location of a search in case the search is canceled
180 searchOrig buffer.Loc
183 func NewBufPane(buf *buffer.Buffer, win display.BWindow) *BufPane {
188 h.Cursor = h.Buf.GetActiveCursor()
189 h.mouseReleased = true
191 config.RunPluginFn("onBufPaneOpen", luar.New(ulua.L, h))
196 func NewBufPaneFromBuf(buf *buffer.Buffer) *BufPane {
197 w := display.NewBufWindow(0, 0, 0, 0, buf)
198 return NewBufPane(buf, w)
201 // PluginCB calls all plugin callbacks with a certain name and
202 // displays an error if there is one and returns the aggregrate
204 func (h *BufPane) PluginCB(cb string) bool {
205 b, err := config.RunPluginFnBool(cb, luar.New(ulua.L, h))
207 screen.TermMessage(err)
212 // PluginCBRune is the same as PluginCB but also passes a rune to
214 func (h *BufPane) PluginCBRune(cb string, r rune) bool {
215 b, err := config.RunPluginFnBool(cb, luar.New(ulua.L, h), luar.New(ulua.L, string(r)))
217 screen.TermMessage(err)
222 func (h *BufPane) OpenBuffer(b *buffer.Buffer) {
225 h.BWindow.SetBuffer(b)
226 h.Cursor = b.GetActiveCursor()
227 h.Resize(h.GetView().Width, h.GetView().Height)
228 v := new(display.View)
231 // Set mouseReleased to true because we assume the mouse is not being pressed when
232 // the editor is opened
233 h.mouseReleased = true
234 // Set isOverwriteMode to false, because we assume we are in the default mode when editor
236 h.isOverwriteMode = false
237 h.lastClickTime = time.Time{}
240 func (h *BufPane) ID() uint64 {
244 func (h *BufPane) SetID(i uint64) {
248 func (h *BufPane) Name() string {
249 return h.Buf.GetName()
252 // HandleEvent executes the tcell event properly
253 func (h *BufPane) HandleEvent(event tcell.Event) {
254 if h.Buf.ExternallyModified() {
255 InfoBar.YNPrompt("The file on disk has changed. Reload file? (y,n)", func(yes, canceled bool) {
256 if !yes || canceled {
257 h.Buf.UpdateModTime()
265 switch e := event.(type) {
266 case *tcell.EventRaw:
271 case *tcell.EventKey:
278 done := h.DoKeyEvent(ke)
279 if !done && e.Key() == tcell.KeyRune {
280 h.DoRuneInsert(e.Rune())
282 case *tcell.EventMouse:
284 case tcell.ButtonNone:
285 // Mouse event with no click
286 if !h.mouseReleased {
287 // Mouse was just released
289 mx, my := e.Position()
290 mouseLoc := h.LocFromVisual(buffer.Loc{X: mx, Y: my})
292 // Relocating here isn't really necessary because the cursor will
293 // be in the right place from the last mouse event
294 // However, if we are running in a terminal that doesn't support mouse motion
295 // events, this still allows the user to make selections, except only after they
298 if !h.doubleClick && !h.tripleClick {
299 h.Cursor.Loc = mouseLoc
300 h.Cursor.SetSelectionEnd(h.Cursor.Loc)
301 h.Cursor.CopySelection("primary")
303 h.mouseReleased = true
311 h.DoMouseEvent(me, e)
316 // Display any gutter messages for this line
317 c := h.Buf.GetActiveCursor()
319 for _, m := range h.Buf.Messages {
320 if c.Y == m.Start.Y || c.Y == m.End.Y {
321 InfoBar.GutterMessage(m.Msg)
326 if none && InfoBar.HasGutter {
327 InfoBar.ClearGutter()
332 // DoKeyEvent executes a key event by finding the action it is bound
333 // to and executing it (possibly multiple times for multiple cursors)
334 func (h *BufPane) DoKeyEvent(e Event) bool {
335 if action, ok := BufKeyBindings[e]; ok {
341 func (h *BufPane) execAction(action func(*BufPane) bool, name string, cursor int) bool {
342 if name != "Autocomplete" {
343 h.Buf.HasSuggestions = false
346 _, isMulti := MultiActions[name]
347 if (!isMulti && cursor == 0) || isMulti {
348 if h.PluginCB("pre" + name) {
349 asuccess := action(h)
350 psuccess := h.PluginCB("on" + name)
354 if name != "ToggleMacro" && name != "PlayMacro" {
355 curmacro = append(curmacro, action)
360 return asuccess && psuccess
367 func (h *BufPane) HasKeyEvent(e Event) bool {
368 _, ok := BufKeyBindings[e]
372 // DoMouseEvent executes a mouse event by finding the action it is bound
373 // to and executing it
374 func (h *BufPane) DoMouseEvent(e MouseEvent, te *tcell.EventMouse) bool {
375 if action, ok := BufMouseBindings[e]; ok {
380 } else if h.HasKeyEvent(e) {
381 return h.DoKeyEvent(e)
386 // DoRuneInsert inserts a given rune into the current buffer
387 // (possibly multiple times for multiple cursors)
388 func (h *BufPane) DoRuneInsert(r rune) {
389 cursors := h.Buf.GetCursors()
390 for _, c := range cursors {
391 // Insert a character
392 h.Buf.SetCurCursor(c.Num)
394 if !h.PluginCBRune("preRune", r) {
397 if c.HasSelection() {
402 if h.isOverwriteMode {
405 h.Buf.Replace(c.Loc, next, string(r))
407 h.Buf.Insert(c.Loc, string(r))
410 curmacro = append(curmacro, r)
412 h.PluginCBRune("onRune", r)
416 func (h *BufPane) VSplitBuf(buf *buffer.Buffer) *BufPane {
417 e := NewBufPaneFromBuf(buf)
418 e.splitID = MainTab().GetNode(h.splitID).VSplit(h.Buf.Settings["splitright"].(bool))
419 MainTab().Panes = append(MainTab().Panes, e)
421 MainTab().SetActive(len(MainTab().Panes) - 1)
424 func (h *BufPane) HSplitBuf(buf *buffer.Buffer) *BufPane {
425 e := NewBufPaneFromBuf(buf)
426 e.splitID = MainTab().GetNode(h.splitID).HSplit(h.Buf.Settings["splitbottom"].(bool))
427 MainTab().Panes = append(MainTab().Panes, e)
429 MainTab().SetActive(len(MainTab().Panes) - 1)
432 func (h *BufPane) Close() {
436 func (h *BufPane) SetActive(b bool) {
437 h.BWindow.SetActive(b)
439 // Display any gutter messages for this line
440 c := h.Buf.GetActiveCursor()
442 for _, m := range h.Buf.Messages {
443 if c.Y == m.Start.Y || c.Y == m.End.Y {
444 InfoBar.GutterMessage(m.Msg)
449 if none && InfoBar.HasGutter {
450 InfoBar.ClearGutter()
456 // BufKeyActions contains the list of all possible key actions the bufhandler could execute
457 var BufKeyActions = map[string]BufKeyAction{
458 "CursorUp": (*BufPane).CursorUp,
459 "CursorDown": (*BufPane).CursorDown,
460 "CursorPageUp": (*BufPane).CursorPageUp,
461 "CursorPageDown": (*BufPane).CursorPageDown,
462 "CursorLeft": (*BufPane).CursorLeft,
463 "CursorRight": (*BufPane).CursorRight,
464 "CursorStart": (*BufPane).CursorStart,
465 "CursorEnd": (*BufPane).CursorEnd,
466 "SelectToStart": (*BufPane).SelectToStart,
467 "SelectToEnd": (*BufPane).SelectToEnd,
468 "SelectUp": (*BufPane).SelectUp,
469 "SelectDown": (*BufPane).SelectDown,
470 "SelectLeft": (*BufPane).SelectLeft,
471 "SelectRight": (*BufPane).SelectRight,
472 "WordRight": (*BufPane).WordRight,
473 "WordLeft": (*BufPane).WordLeft,
474 "SelectWordRight": (*BufPane).SelectWordRight,
475 "SelectWordLeft": (*BufPane).SelectWordLeft,
476 "DeleteWordRight": (*BufPane).DeleteWordRight,
477 "DeleteWordLeft": (*BufPane).DeleteWordLeft,
478 "SelectLine": (*BufPane).SelectLine,
479 "SelectToStartOfLine": (*BufPane).SelectToStartOfLine,
480 "SelectToEndOfLine": (*BufPane).SelectToEndOfLine,
481 "ParagraphPrevious": (*BufPane).ParagraphPrevious,
482 "ParagraphNext": (*BufPane).ParagraphNext,
483 "InsertNewline": (*BufPane).InsertNewline,
484 "Backspace": (*BufPane).Backspace,
485 "Delete": (*BufPane).Delete,
486 "InsertTab": (*BufPane).InsertTab,
487 "Save": (*BufPane).Save,
488 "SaveAll": (*BufPane).SaveAll,
489 "SaveAs": (*BufPane).SaveAs,
490 "Find": (*BufPane).Find,
491 "FindNext": (*BufPane).FindNext,
492 "FindPrevious": (*BufPane).FindPrevious,
493 "Center": (*BufPane).Center,
494 "Undo": (*BufPane).Undo,
495 "Redo": (*BufPane).Redo,
496 "Copy": (*BufPane).Copy,
497 "Cut": (*BufPane).Cut,
498 "CutLine": (*BufPane).CutLine,
499 "DuplicateLine": (*BufPane).DuplicateLine,
500 "DeleteLine": (*BufPane).DeleteLine,
501 "MoveLinesUp": (*BufPane).MoveLinesUp,
502 "MoveLinesDown": (*BufPane).MoveLinesDown,
503 "IndentSelection": (*BufPane).IndentSelection,
504 "OutdentSelection": (*BufPane).OutdentSelection,
505 "Autocomplete": (*BufPane).Autocomplete,
506 "OutdentLine": (*BufPane).OutdentLine,
507 "Paste": (*BufPane).Paste,
508 "PastePrimary": (*BufPane).PastePrimary,
509 "SelectAll": (*BufPane).SelectAll,
510 "OpenFile": (*BufPane).OpenFile,
511 "Start": (*BufPane).Start,
512 "End": (*BufPane).End,
513 "PageUp": (*BufPane).PageUp,
514 "PageDown": (*BufPane).PageDown,
515 "SelectPageUp": (*BufPane).SelectPageUp,
516 "SelectPageDown": (*BufPane).SelectPageDown,
517 "HalfPageUp": (*BufPane).HalfPageUp,
518 "HalfPageDown": (*BufPane).HalfPageDown,
519 "StartOfLine": (*BufPane).StartOfLine,
520 "EndOfLine": (*BufPane).EndOfLine,
521 "ToggleHelp": (*BufPane).ToggleHelp,
522 "ToggleKeyMenu": (*BufPane).ToggleKeyMenu,
523 "ToggleRuler": (*BufPane).ToggleRuler,
524 "ClearStatus": (*BufPane).ClearStatus,
525 "ShellMode": (*BufPane).ShellMode,
526 "CommandMode": (*BufPane).CommandMode,
527 "ToggleOverwriteMode": (*BufPane).ToggleOverwriteMode,
528 "Escape": (*BufPane).Escape,
529 "Quit": (*BufPane).Quit,
530 "QuitAll": (*BufPane).QuitAll,
531 "AddTab": (*BufPane).AddTab,
532 "PreviousTab": (*BufPane).PreviousTab,
533 "NextTab": (*BufPane).NextTab,
534 "NextSplit": (*BufPane).NextSplit,
535 "PreviousSplit": (*BufPane).PreviousSplit,
536 "Unsplit": (*BufPane).Unsplit,
537 "VSplit": (*BufPane).VSplitAction,
538 "HSplit": (*BufPane).HSplitAction,
539 "ToggleMacro": (*BufPane).ToggleMacro,
540 "PlayMacro": (*BufPane).PlayMacro,
541 "Suspend": (*BufPane).Suspend,
542 "ScrollUp": (*BufPane).ScrollUpAction,
543 "ScrollDown": (*BufPane).ScrollDownAction,
544 "SpawnMultiCursor": (*BufPane).SpawnMultiCursor,
545 "SpawnMultiCursorSelect": (*BufPane).SpawnMultiCursorSelect,
546 "RemoveMultiCursor": (*BufPane).RemoveMultiCursor,
547 "RemoveAllMultiCursors": (*BufPane).RemoveAllMultiCursors,
548 "SkipMultiCursor": (*BufPane).SkipMultiCursor,
549 "JumpToMatchingBrace": (*BufPane).JumpToMatchingBrace,
550 "None": (*BufPane).None,
552 // This was changed to InsertNewline but I don't want to break backwards compatibility
553 "InsertEnter": (*BufPane).InsertNewline,
556 // BufMouseActions contains the list of all possible mouse actions the bufhandler could execute
557 var BufMouseActions = map[string]BufMouseAction{
558 "MousePress": (*BufPane).MousePress,
559 "MouseMultiCursor": (*BufPane).MouseMultiCursor,
562 // MultiActions is a list of actions that should be executed multiple
563 // times if there are multiple cursors (one per cursor)
564 // Generally actions that modify global editor state like quitting or
565 // saving should not be included in this list
566 var MultiActions = map[string]bool{
569 "CursorPageUp": true,
570 "CursorPageDown": true,
575 "SelectToStart": true,
583 "SelectWordRight": true,
584 "SelectWordLeft": true,
585 "DeleteWordRight": true,
586 "DeleteWordLeft": true,
588 "SelectToStartOfLine": true,
589 "SelectToEndOfLine": true,
590 "ParagraphPrevious": true,
591 "ParagraphNext": true,
592 "InsertNewline": true,
597 "FindPrevious": true,
600 "DuplicateLine": true,
603 "MoveLinesDown": true,
604 "IndentSelection": true,
605 "OutdentSelection": true,
608 "PastePrimary": true,
609 "SelectPageUp": true,
610 "SelectPageDown": true,
613 "JumpToMatchingBrace": true,