Major cleanup

This commit is contained in:
Zachary Yedidia 2016-03-25 12:14:22 -04:00
parent 8994690b5b
commit 339cdad594
12 changed files with 509 additions and 349 deletions

View file

@ -6,6 +6,7 @@ import (
"io/ioutil" "io/ioutil"
"os/user" "os/user"
"regexp" "regexp"
"strconv"
"strings" "strings"
) )
@ -45,6 +46,9 @@ func LoadColorscheme(colorschemeName, dir string) {
} }
// ParseColorscheme parses the text definition for a colorscheme and returns the corresponding object // ParseColorscheme parses the text definition for a colorscheme and returns the corresponding object
// Colorschemes are made up of color-link statements linking a color group to a list of colors
// For example, color-link keyword (blue,red) makes all keywords have a blue foreground and
// red background
func ParseColorscheme(text string) Colorscheme { func ParseColorscheme(text string) Colorscheme {
parser := regexp.MustCompile(`color-link\s+(\S*)\s+"(.*)"`) parser := regexp.MustCompile(`color-link\s+(\S*)\s+"(.*)"`)
@ -74,6 +78,8 @@ func ParseColorscheme(text string) Colorscheme {
} }
// StringToStyle returns a style from a string // StringToStyle returns a style from a string
// The strings must be in the format "extra foregroundcolor,backgroundcolor"
// The 'extra' can be bold, reverse, or underline
func StringToStyle(str string) tcell.Style { func StringToStyle(str string) tcell.Style {
var fg string var fg string
var bg string var bg string
@ -83,6 +89,8 @@ func StringToStyle(str string) tcell.Style {
} else { } else {
fg = split[0] fg = split[0]
} }
fg = strings.TrimSpace(fg)
bg = strings.TrimSpace(bg)
style := tcell.StyleDefault.Foreground(StringToColor(fg)).Background(StringToColor(bg)) style := tcell.StyleDefault.Foreground(StringToColor(fg)).Background(StringToColor(bg))
if strings.Contains(str, "bold") { if strings.Contains(str, "bold") {
@ -98,6 +106,7 @@ func StringToStyle(str string) tcell.Style {
} }
// StringToColor returns a tcell color from a string representation of a color // StringToColor returns a tcell color from a string representation of a color
// We accept either bright... or light... to mean the brighter version of a color
func StringToColor(str string) tcell.Color { func StringToColor(str string) tcell.Color {
switch str { switch str {
case "black": case "black":
@ -116,25 +125,46 @@ func StringToColor(str string) tcell.Color {
return tcell.ColorTeal return tcell.ColorTeal
case "white": case "white":
return tcell.ColorSilver return tcell.ColorSilver
case "brightblack": case "brightblack", "lightblack":
return tcell.ColorGray return tcell.ColorGray
case "brightred": case "brightred", "lightred":
return tcell.ColorRed return tcell.ColorRed
case "brightgreen": case "brightgreen", "lightgreen":
return tcell.ColorLime return tcell.ColorLime
case "brightyellow": case "brightyellow", "lightyellow":
return tcell.ColorYellow return tcell.ColorYellow
case "brightblue": case "brightblue", "lightblue":
return tcell.ColorBlue return tcell.ColorBlue
case "brightmagenta": case "brightmagenta", "lightmagenta":
return tcell.ColorFuchsia return tcell.ColorFuchsia
case "brightcyan": case "brightcyan", "lightcyan":
return tcell.ColorAqua return tcell.ColorAqua
case "brightwhite": case "brightwhite", "lightwhite":
return tcell.ColorWhite return tcell.ColorWhite
case "default": case "default":
return tcell.ColorDefault return tcell.ColorDefault
default: default:
// Check if this is a 256 color
if num, err := strconv.Atoi(str); err == nil {
return GetColor256(num)
}
// Probably a truecolor hex value
return tcell.GetColor(str) return tcell.GetColor(str)
} }
} }
// GetColor256 returns the tcell color for a number between 0 and 255
func GetColor256(color int) tcell.Color {
ansiColors := []tcell.Color{tcell.ColorBlack, tcell.ColorMaroon, tcell.ColorGreen,
tcell.ColorOlive, tcell.ColorNavy, tcell.ColorPurple,
tcell.ColorTeal, tcell.ColorSilver, tcell.ColorGray,
tcell.ColorRed, tcell.ColorLime, tcell.ColorYellow,
tcell.ColorBlue, tcell.ColorFuchsia, tcell.ColorAqua,
tcell.ColorWhite}
if color >= 0 && color <= 15 {
return ansiColors[color]
}
return tcell.GetColor("Color" + strconv.Itoa(color))
}

View file

@ -149,7 +149,7 @@ func (c *Cursor) Start() {
// GetCharPosInLine gets the char position of a visual x y coordinate (this is necessary because tabs are 1 char but 4 visual spaces) // GetCharPosInLine gets the char position of a visual x y coordinate (this is necessary because tabs are 1 char but 4 visual spaces)
func (c *Cursor) GetCharPosInLine(lineNum, visualPos int) int { func (c *Cursor) GetCharPosInLine(lineNum, visualPos int) int {
visualLine := strings.Replace(c.v.buf.lines[lineNum], "\t", "\t"+EmptyString(tabSize-1), -1) visualLine := strings.Replace(c.v.buf.lines[lineNum], "\t", "\t"+Spaces(tabSize-1), -1)
if visualPos > Count(visualLine) { if visualPos > Count(visualLine) {
visualPos = Count(visualLine) visualPos = Count(visualLine)
} }
@ -213,10 +213,8 @@ func (c *Cursor) Distance(x, y int) int {
// Display draws the cursor to the screen at the correct position // Display draws the cursor to the screen at the correct position
func (c *Cursor) Display() { func (c *Cursor) Display() {
if c.y-c.v.topline < 0 || c.y-c.v.topline > c.v.height-1 { if c.y-c.v.topline < 0 || c.y-c.v.topline > c.v.height-1 {
c.v.s.HideCursor() screen.HideCursor()
} else { } else {
c.v.s.ShowCursor(c.GetVisualX()+c.v.lineNumOffset, c.y-c.v.topline) screen.ShowCursor(c.GetVisualX()+c.v.lineNumOffset, c.y-c.v.topline)
// cursorStyle := tcell.StyleDefault.Reverse(true)
// c.v.s.SetContent(c.x+voffset, c.y-c.v.topline, c.runeUnder(), nil, cursorStyle)
} }
} }

View file

@ -5,6 +5,8 @@ import (
) )
const ( const (
// Opposite and undoing events must have opposite values
// TextEventInsert repreasents an insertion event // TextEventInsert repreasents an insertion event
TextEventInsert = 1 TextEventInsert = 1
// TextEventRemove represents a deletion event // TextEventRemove represents a deletion event

View file

@ -10,13 +10,17 @@ import (
"strings" "strings"
) )
// FileTypeRules represents a complete set of syntax rules for a filetype
type FileTypeRules struct { type FileTypeRules struct {
filetype string filetype string
rules []SyntaxRule rules []SyntaxRule
} }
// SyntaxRule represents a regex to highlight in a certain style
type SyntaxRule struct { type SyntaxRule struct {
// What to highlight
regex *regexp.Regexp regex *regexp.Regexp
// How to highlight it
style tcell.Style style tcell.Style
} }
@ -154,11 +158,12 @@ func GetRules(buf *Buffer) ([]SyntaxRule, string) {
return nil, "Unknown" return nil, "Unknown"
} }
// Match takes a buffer and returns a map specifying how it should be syntax highlighted // SyntaxMatches is an alias to a map from character numbers to styles,
// The map is from character numbers to styles, so map[3] represents the style change // so map[3] represents the style of the third character
// at the third character in the buffer type SyntaxMatches map[int]tcell.Style
// Note that this map only stores changes in styles, not each character's style
func Match(rules []SyntaxRule, buf *Buffer, v *View) map[int]tcell.Style { // Match takes a buffer and returns the syntax matches a map specifying how it should be syntax highlighted
func Match(rules []SyntaxRule, buf *Buffer, v *View) SyntaxMatches {
start := v.topline - synLinesUp start := v.topline - synLinesUp
end := v.topline + v.height + synLinesDown end := v.topline + v.height + synLinesDown
if start < 0 { if start < 0 {

View file

@ -1,28 +1,43 @@
package main package main
import ( import (
"bufio"
"fmt"
"github.com/gdamore/tcell" "github.com/gdamore/tcell"
"os"
) )
// Messenger is an object that can send messages to the user and get input from the user (with a prompt) // TermMessage sends a message to the user in the terminal. This usually occurs before
type Messenger struct { // micro has been fully initialized -- ie if there is an error in the syntax highlighting
hasPrompt bool // regular expressions
hasMessage bool // The function must be called when the screen is not initialized
// This will write the message, and wait for the user
// to press and key to continue
func TermMessage(msg string) {
fmt.Println(msg)
fmt.Print("\nPress enter to continue")
message string reader := bufio.NewReader(os.Stdin)
response string reader.ReadString('\n')
style tcell.Style
cursorx int
s tcell.Screen
} }
// NewMessenger returns a new Messenger struct // Messenger is an object that makes it easy to send messages to the user
func NewMessenger(s tcell.Screen) *Messenger { // and get input from the user
m := new(Messenger) type Messenger struct {
m.s = s // Are we currently prompting the user?
return m hasPrompt bool
// Is there a message to print
hasMessage bool
// Message to print
message string
// The user's response to a prompt
response string
// style to use when drawing the message
style tcell.Style
// We have to keep track of the cursor for prompting
cursorx int
} }
// Message sends a message to the user // Message sends a message to the user
@ -61,7 +76,7 @@ func (m *Messenger) Prompt(prompt string) (string, bool) {
m.Clear() m.Clear()
m.Display() m.Display()
event := m.s.PollEvent() event := screen.PollEvent()
switch e := event.(type) { switch e := event.(type) {
case *tcell.EventKey: case *tcell.EventKey:
@ -124,23 +139,23 @@ func (m *Messenger) Reset() {
// Clear clears the line at the bottom of the editor // Clear clears the line at the bottom of the editor
func (m *Messenger) Clear() { func (m *Messenger) Clear() {
w, h := m.s.Size() w, h := screen.Size()
for x := 0; x < w; x++ { for x := 0; x < w; x++ {
m.s.SetContent(x, h-1, ' ', nil, tcell.StyleDefault) screen.SetContent(x, h-1, ' ', nil, tcell.StyleDefault)
} }
} }
// Display displays and messages or prompts // Display displays messages or prompts
func (m *Messenger) Display() { func (m *Messenger) Display() {
_, h := m.s.Size() _, h := screen.Size()
if m.hasMessage { if m.hasMessage {
runes := []rune(m.message + m.response) runes := []rune(m.message + m.response)
for x := 0; x < len(runes); x++ { for x := 0; x < len(runes); x++ {
m.s.SetContent(x, h-1, runes[x], nil, m.style) screen.SetContent(x, h-1, runes[x], nil, m.style)
} }
} }
if m.hasPrompt { if m.hasPrompt {
m.s.ShowCursor(Count(m.message)+m.cursorx, h-1) screen.ShowCursor(Count(m.message)+m.cursorx, h-1)
m.s.Show() screen.Show()
} }
} }

View file

@ -10,100 +10,136 @@ import (
) )
const ( const (
tabSize = 4 tabSize = 4 // This should be configurable
synLinesUp = 75 synLinesUp = 75 // How many lines up to look to do syntax highlighting
synLinesDown = 75 synLinesDown = 75 // How many lines down to look to do syntax highlighting
) )
func main() { // The main screen
var input []byte var screen tcell.Screen
// LoadInput loads the file input for the editor
func LoadInput() (string, []byte, error) {
// There are a number of ways micro should start given its input
// 1. If it is given a file in os.Args, it should open that
// 2. If there is no input file and the input is not a terminal, that means
// something is being piped in and the stdin should be opened in an
// empty buffer
// 3. If there is no input file and the input is a terminal, an empty buffer
// should be opened
// These are empty by default so if we get to option 3, we can just returns the
// default values
var filename string var filename string
var input []byte
var err error
if len(os.Args) > 1 { if len(os.Args) > 1 {
// Option 1
filename = os.Args[1] filename = os.Args[1]
// Check that the file exists
if _, err := os.Stat(filename); err == nil { if _, err := os.Stat(filename); err == nil {
var err error
input, err = ioutil.ReadFile(filename) input, err = ioutil.ReadFile(filename)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
} }
} else if !isatty.IsTerminal(os.Stdin.Fd()) { } else if !isatty.IsTerminal(os.Stdin.Fd()) {
bytes, err := ioutil.ReadAll(os.Stdin) // Option 2
if err != nil { // The input is not a terminal, so something is being piped in
fmt.Println("Error reading stdin") // and we should read from stdin
os.Exit(1) input, err = ioutil.ReadAll(os.Stdin)
}
input = bytes
} }
LoadSyntaxFiles() // Option 3, or just return whatever we got
return filename, input, err
}
func main() {
filename, input, err := LoadInput()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// Should we enable true color?
truecolor := os.Getenv("MICRO_TRUECOLOR") == "1" truecolor := os.Getenv("MICRO_TRUECOLOR") == "1"
// In order to enable true color, we have to set the TERM to `xterm-truecolor` when
// initializing tcell, but after that, we can set the TERM back to whatever it was
oldTerm := os.Getenv("TERM") oldTerm := os.Getenv("TERM")
if truecolor { if truecolor {
os.Setenv("TERM", "xterm-truecolor") os.Setenv("TERM", "xterm-truecolor")
} }
s, e := tcell.NewTerminfoScreen() // Initilize tcell
if e != nil { screen, err = tcell.NewScreen()
fmt.Fprintf(os.Stderr, "%v\n", e) if err != nil {
fmt.Println(err)
os.Exit(1) os.Exit(1)
} }
if e := s.Init(); e != nil { if err = screen.Init(); err != nil {
fmt.Fprintf(os.Stderr, "%v\n", e) fmt.Println(err)
os.Exit(1) os.Exit(1)
} }
// Now we can put the TERM back to what it was before
if truecolor { if truecolor {
os.Setenv("TERM", oldTerm) os.Setenv("TERM", oldTerm)
} }
// This is just so if we have an error, we can exit cleanly and not completely
// mess up the terminal being worked in
defer func() { defer func() {
if err := recover(); err != nil { if err := recover(); err != nil {
s.Fini() screen.Fini()
fmt.Println("Micro encountered an error:", err) fmt.Println("Micro encountered an error:", err)
// Print the stack trace too
fmt.Print(errors.Wrap(err, 2).ErrorStack()) fmt.Print(errors.Wrap(err, 2).ErrorStack())
os.Exit(1) os.Exit(1)
} }
}() }()
// Default style
defStyle := tcell.StyleDefault. defStyle := tcell.StyleDefault.
Background(tcell.ColorDefault). Foreground(tcell.ColorDefault).
Foreground(tcell.ColorDefault) Background(tcell.ColorDefault)
if _, ok := colorscheme["default"]; ok { // There may be another default style defined in the colorscheme
defStyle = colorscheme["default"] if style, ok := colorscheme["default"]; ok {
defStyle = style
} }
s.SetStyle(defStyle) screen.SetStyle(defStyle)
s.EnableMouse() screen.EnableMouse()
m := NewMessenger(s) messenger := new(Messenger)
v := NewView(NewBuffer(string(input), filename), m, s) view := NewView(NewBuffer(string(input), filename), messenger)
// Initially everything needs to be drawn
redraw := 2
for { for {
if redraw == 2 { // Display everything
v.matches = Match(v.buf.rules, v.buf, v) screen.Clear()
s.Clear()
v.Display() view.Display()
v.cursor.Display() messenger.Display()
v.sl.Display()
m.Display() screen.Show()
s.Show()
} else if redraw == 1 { // Wait for the user's action
v.cursor.Display() event := screen.PollEvent()
v.sl.Display()
m.Display() // Check if we should quit
s.Show() switch e := event.(type) {
case *tcell.EventKey:
if e.Key() == tcell.KeyCtrlQ {
// Make sure not to quit if there are unsaved changes
if view.CanClose("Quit anyway? ") {
screen.Fini()
os.Exit(0)
}
}
} }
event := s.PollEvent() // Send it to the view
redraw = v.HandleEvent(event) view.HandleEvent(event)
} }
} }

View file

@ -2,7 +2,6 @@ package main
import ( import (
"math" "math"
"unicode/utf8"
) )
const ( const (
@ -13,22 +12,6 @@ const (
// RopeRebalanceRatio = 1.2 // RopeRebalanceRatio = 1.2
) )
// Min takes the min of two ints
func Min(a, b int) int {
if a > b {
return b
}
return a
}
// Max takes the max of two ints
func Max(a, b int) int {
if a > b {
return a
}
return b
}
// A Rope is a data structure for efficiently manipulating large strings // A Rope is a data structure for efficiently manipulating large strings
type Rope struct { type Rope struct {
left *Rope left *Rope
@ -44,7 +27,7 @@ func NewRope(str string) *Rope {
r := new(Rope) r := new(Rope)
r.value = str r.value = str
r.valueNil = false r.valueNil = false
r.len = utf8.RuneCountInString(r.value) r.len = Count(r.value)
r.Adjust() r.Adjust()
@ -83,7 +66,7 @@ func (r *Rope) Remove(start, end int) {
if !r.valueNil { if !r.valueNil {
r.value = string(append([]rune(r.value)[:start], []rune(r.value)[end:]...)) r.value = string(append([]rune(r.value)[:start], []rune(r.value)[end:]...))
r.valueNil = false r.valueNil = false
r.len = utf8.RuneCountInString(r.value) r.len = Count(r.value)
} else { } else {
leftStart := Min(start, r.left.len) leftStart := Min(start, r.left.len)
leftEnd := Min(end, r.left.len) leftEnd := Min(end, r.left.len)
@ -107,7 +90,7 @@ func (r *Rope) Insert(pos int, value string) {
first := append([]rune(r.value)[:pos], []rune(value)...) first := append([]rune(r.value)[:pos], []rune(value)...)
r.value = string(append(first, []rune(r.value)[pos:]...)) r.value = string(append(first, []rune(r.value)[pos:]...))
r.valueNil = false r.valueNil = false
r.len = utf8.RuneCountInString(r.value) r.len = Count(r.value)
} else { } else {
if pos < r.left.len { if pos < r.left.len {
r.left.Insert(pos, value) r.left.Insert(pos, value)

View file

@ -33,11 +33,3 @@ func (s *Stack) Pop() (value interface{}) {
} }
return nil return nil
} }
// Peek lets you see and edit the top value of the stack without popping it
func (s *Stack) Peek() *interface{} {
if s.size > 0 {
return &s.top.value
}
return nil
}

View file

@ -5,39 +5,51 @@ import (
"strconv" "strconv"
) )
// Statusline represents the blue line at the bottom of the // Statusline represents the information line at the bottom
// editor that gives information about the buffer // of each view
// It gives information such as filename, whether the file has been
// modified, filetype, cursor location
type Statusline struct { type Statusline struct {
v *View view *View
} }
// Display draws the statusline to the screen // Display draws the statusline to the screen
func (sl *Statusline) Display() { func (sline *Statusline) Display() {
y := sl.v.height // We'll draw the line at the lowest line in the view
y := sline.view.height
file := sl.v.buf.name file := sline.view.buf.name
// If the name is empty, use 'No name'
if file == "" { if file == "" {
file = "Untitled" file = "No name"
} }
if sl.v.buf.IsDirty() {
// If the buffer is dirty (has been modified) write a little '+'
if sline.view.buf.IsDirty() {
file += " +" file += " +"
} }
file += " (" + strconv.Itoa(sl.v.cursor.y+1) + "," + strconv.Itoa(sl.v.cursor.GetVisualX()+1) + ")"
filetype := sl.v.buf.filetype // Add one to cursor.x and cursor.y because (0,0) is the top left,
file += " " + filetype // but users will be used to (1,1) (first line,first column)
// We use GetVisualX() here because otherwise we get the column number in runes
// so a '\t' is only 1, when it should be tabSize
columnNum := strconv.Itoa(sline.view.cursor.GetVisualX() + 1)
lineNum := strconv.Itoa(sline.view.cursor.y + 1)
file += " (" + lineNum + "," + columnNum + ")"
// Add the filetype
file += " " + sline.view.buf.filetype
statusLineStyle := tcell.StyleDefault.Reverse(true) statusLineStyle := tcell.StyleDefault.Reverse(true)
if _, ok := colorscheme["statusline"]; ok {
statusLineStyle = colorscheme["statusline"]
}
for x := 0; x < sl.v.width; x++ { // Maybe there is a unicode filename?
if x < Count(file) { fileRunes := []rune(file)
sl.v.s.SetContent(x, y, []rune(file)[x], nil, statusLineStyle) for x := 0; x < sline.view.width; x++ {
// } else if x > sl.v.width-Count(filetype)-1 { if x < len(fileRunes) {
// sl.v.s.SetContent(x, y, []rune(filetype)[Count(filetype)-(sl.v.width-1-x)-1], nil, statusLineStyle) screen.SetContent(x, y, fileRunes[x], nil, statusLineStyle)
} else { } else {
sl.v.s.SetContent(x, y, ' ', nil, statusLineStyle) screen.SetContent(x, y, ' ', nil, statusLineStyle)
} }
} }
} }

View file

@ -4,7 +4,11 @@ import (
"unicode/utf8" "unicode/utf8"
) )
// Util.go is a collection of utility functions that are used throughout
// the program
// Count returns the length of a string in runes // Count returns the length of a string in runes
// This is exactly equivalent to utf8.RuneCountInString(), just less characters
func Count(s string) int { func Count(s string) int {
return utf8.RuneCountInString(s) return utf8.RuneCountInString(s)
} }
@ -20,11 +24,27 @@ func NumOccurences(s string, c byte) int {
return n return n
} }
// EmptyString returns an empty string n spaces long // Spaces returns a string with n spaces
func EmptyString(n int) string { func Spaces(n int) string {
var str string var str string
for i := 0; i < n; i++ { for i := 0; i < n; i++ {
str += " " str += " "
} }
return str return str
} }
// Min takes the min of two ints
func Min(a, b int) int {
if a > b {
return b
}
return a
}
// Max takes the max of two ints
func Max(a, b int) int {
if a > b {
return a
}
return b
}

35
src/util_test.go Normal file
View file

@ -0,0 +1,35 @@
package main
import "testing"
func TestNumOccurences(t *testing.T) {
var tests = []struct {
inputStr string
inputChar byte
want int
}{
{"aaaa", 'a', 4},
{"\trfd\ta", '\t', 2},
{"∆ƒ\tø ® \t\t", '\t', 3},
}
for _, test := range tests {
if got := NumOccurences(test.inputStr, test.inputChar); got != test.want {
t.Errorf("NumOccurences(%s, %c) = %d", test.inputStr, test.inputChar, got)
}
}
}
func TestSpaces(t *testing.T) {
var tests = []struct {
input int
want string
}{
{4, " "},
{0, ""},
}
for _, test := range tests {
if got := Spaces(test.input); got != test.want {
t.Errorf("Spaces(%d) = \"%s\"", test.input, got)
}
}
}

View file

@ -4,7 +4,6 @@ import (
"github.com/atotto/clipboard" "github.com/atotto/clipboard"
"github.com/gdamore/tcell" "github.com/gdamore/tcell"
"io/ioutil" "io/ioutil"
"os"
"strconv" "strconv"
"strings" "strings"
) )
@ -13,53 +12,65 @@ import (
// It has a value for the cursor, and the window that the user sees // It has a value for the cursor, and the window that the user sees
// the buffer from. // the buffer from.
type View struct { type View struct {
cursor Cursor cursor Cursor
// The topmost line, used for vertical scrolling
topline int topline int
// Leftmost column. Used for horizontal scrolling // The leftmost column, used for horizontal scrolling
leftCol int leftCol int
// Percentage of the terminal window that this view takes up // Percentage of the terminal window that this view takes up (from 0 to 100)
heightPercent float32 widthPercent int
widthPercent float32 heightPercent int
height int
width int // Actual with and height
width int
height int
// How much to offset because of line numbers // How much to offset because of line numbers
lineNumOffset int lineNumOffset int
// The eventhandler for undo/redo
eh *EventHandler eh *EventHandler
// The buffer
buf *Buffer buf *Buffer
sl Statusline // The statusline
sline Statusline
// Since tcell doesn't differentiate between a mouse release event
// and a mouse move event with no keys pressed, we need to keep
// track of whether or not the mouse was pressed (or not released) last event to determine
// mouse release events
mouseReleased bool mouseReleased bool
// Syntax highlighting matches // Syntax higlighting matches
matches map[int]tcell.Style matches SyntaxMatches
// The messenger so we can send messages to the user and get input from them
m *Messenger m *Messenger
s tcell.Screen
} }
// NewView returns a new view with fullscreen width and height // NewView returns a new fullscreen view
func NewView(buf *Buffer, m *Messenger, s tcell.Screen) *View { func NewView(buf *Buffer, m *Messenger) *View {
return NewViewWidthHeight(buf, m, s, 1, 1) return NewViewWidthHeight(buf, m, 100, 100)
} }
// NewViewWidthHeight returns a new view with the specified width and height percentages // NewViewWidthHeight returns a new view with the specified width and height percentages
func NewViewWidthHeight(buf *Buffer, m *Messenger, s tcell.Screen, w, h float32) *View { // Note that w and h are percentages not actual values
func NewViewWidthHeight(buf *Buffer, m *Messenger, w, h int) *View {
v := new(View) v := new(View)
v.buf = buf v.buf = buf
v.s = s // Messenger
v.m = m v.m = m
v.widthPercent = w v.widthPercent = w
v.heightPercent = h v.heightPercent = h
v.Resize(s.Size()) v.Resize(screen.Size())
v.topline = 0 v.topline = 0
// Put the cursor at the first spot
v.cursor = Cursor{ v.cursor = Cursor{
x: 0, x: 0,
y: 0, y: 0,
@ -69,18 +80,23 @@ func NewViewWidthHeight(buf *Buffer, m *Messenger, s tcell.Screen, w, h float32)
v.eh = NewEventHandler(v) v.eh = NewEventHandler(v)
v.sl = Statusline{ v.sline = Statusline{
v: v, view: v,
} }
return v return v
} }
// Resize recalculates the width and height of the view based on the width and height percentages // Resize recalculates the actual width and height of the view from the width and height
// percentages
// This is usually called when the window is resized, or when a split has been added and
// the percentages have changed
func (v *View) Resize(w, h int) { func (v *View) Resize(w, h int) {
// Always include 1 line for the command line at the bottom
h-- h--
v.height = int(float32(h)*v.heightPercent) - 1 v.width = int(float32(w) * float32(v.widthPercent) / 100)
v.width = int(float32(w) * v.widthPercent) // We subtract 1 for the statusline
v.height = int(float32(h)*float32(v.heightPercent)/100) - 1
} }
// ScrollUp scrolls the view up n lines (if possible) // ScrollUp scrolls the view up n lines (if possible)
@ -139,70 +155,185 @@ func (v *View) HalfPageDown() {
} }
} }
// CanClose returns whether or not the view can be closed
// If there are unsaved changes, the user will be asked if the view can be closed
// causing them to lose the unsaved changes
// The message is what to print after saying "You have unsaved changes. "
func (v *View) CanClose(msg string) bool {
if v.buf.IsDirty() {
quit, canceled := v.m.Prompt("You have unsaved changes. " + msg)
if !canceled {
if strings.ToLower(quit) == "yes" || strings.ToLower(quit) == "y" {
return true
}
}
} else {
return true
}
return false
}
// Save the buffer to disk
func (v *View) Save() {
// If this is an empty buffer, ask for a filename
if v.buf.path == "" {
filename, canceled := v.m.Prompt("Filename: ")
if !canceled {
v.buf.path = filename
v.buf.name = filename
} else {
return
}
}
err := v.buf.Save()
if err != nil {
v.m.Error(err.Error())
}
}
// Copy the selection to the system clipboard
func (v *View) Copy() {
if v.cursor.HasSelection() {
if !clipboard.Unsupported {
clipboard.WriteAll(v.cursor.GetSelection())
} else {
v.m.Error("Clipboard is not supported on your system")
}
}
}
// Cut the selection to the system clipboard
func (v *View) Cut() {
if v.cursor.HasSelection() {
if !clipboard.Unsupported {
clipboard.WriteAll(v.cursor.GetSelection())
v.cursor.DeleteSelection()
v.cursor.ResetSelection()
} else {
v.m.Error("Clipboard is not supported on your system")
}
}
}
// Paste whatever is in the system clipboard into the buffer
// Delete and paste if the user has a selection
func (v *View) Paste() {
if !clipboard.Unsupported {
if v.cursor.HasSelection() {
v.cursor.DeleteSelection()
v.cursor.ResetSelection()
}
clip, _ := clipboard.ReadAll()
v.eh.Insert(v.cursor.loc, clip)
// This is a bit weird... Not sure if there's a better way
for i := 0; i < Count(clip); i++ {
v.cursor.Right()
}
} else {
v.m.Error("Clipboard is not supported on your system")
}
}
// SelectAll selects the entire buffer
func (v *View) SelectAll() {
v.cursor.selectionEnd = 0
v.cursor.selectionStart = v.buf.Len()
// Put the cursor at the beginning
v.cursor.x = 0
v.cursor.y = 0
v.cursor.loc = 0
}
// OpenFile opens a new file in the current view
// It makes sure that the current buffer can be closed first (unsaved changes)
func (v *View) OpenFile() {
if v.CanClose("Continue? ") {
filename, canceled := v.m.Prompt("File to open: ")
if canceled {
return
}
file, err := ioutil.ReadFile(filename)
if err != nil {
v.m.Error(err.Error())
return
}
v.buf = NewBuffer(string(file), filename)
}
}
// Relocate moves the view window so that the cursor is in view
// This is useful if the user has scrolled far away, and then starts typing
func (v *View) Relocate() {
cy := v.cursor.y
if cy < v.topline {
v.topline = cy
}
if cy > v.topline+v.height-1 {
v.topline = cy - v.height + 1
}
}
// MoveToMouseClick moves the cursor to location x, y assuming x, y were given
// by a mouse click
func (v *View) MoveToMouseClick(x, y int) {
if y-v.topline > v.height-1 {
v.ScrollDown(1)
y = v.height + v.topline - 1
}
if y >= len(v.buf.lines) {
y = len(v.buf.lines) - 1
}
if x < 0 {
x = 0
}
x = v.cursor.GetCharPosInLine(y, x)
if x > Count(v.buf.lines[y]) {
x = Count(v.buf.lines[y])
}
d := v.cursor.Distance(x, y)
v.cursor.loc += d
v.cursor.x = x
v.cursor.y = y
}
// HandleEvent handles an event passed by the main loop // HandleEvent handles an event passed by the main loop
// It returns an int describing how the screen needs to be redrawn func (v *View) HandleEvent(event tcell.Event) {
// 0: Screen does not need to be redrawn // This bool determines whether the view is relocated at the end of the function
// 1: Only the cursor/statusline needs to be redrawn // By default it's true because most events should cause a relocate
// 2: Everything needs to be redrawn relocate := true
func (v *View) HandleEvent(event tcell.Event) int {
var ret int
switch e := event.(type) { switch e := event.(type) {
case *tcell.EventResize: case *tcell.EventResize:
// Window resized // Window resized
v.Resize(e.Size()) v.Resize(e.Size())
ret = 2
case *tcell.EventKey: case *tcell.EventKey:
switch e.Key() { switch e.Key() {
case tcell.KeyCtrlQ:
// Quit
if v.buf.IsDirty() {
quit, canceled := v.m.Prompt("You have unsaved changes. Quit anyway? ")
if !canceled {
if strings.ToLower(quit) == "yes" || strings.ToLower(quit) == "y" {
v.s.Fini()
os.Exit(0)
} else {
return 2
}
} else {
return 2
}
} else {
v.s.Fini()
os.Exit(0)
}
case tcell.KeyUp: case tcell.KeyUp:
// Cursor up // Cursor up
v.cursor.Up() v.cursor.Up()
ret = 1
case tcell.KeyDown: case tcell.KeyDown:
// Cursor down // Cursor down
v.cursor.Down() v.cursor.Down()
ret = 1
case tcell.KeyLeft: case tcell.KeyLeft:
// Cursor left // Cursor left
v.cursor.Left() v.cursor.Left()
ret = 1
case tcell.KeyRight: case tcell.KeyRight:
// Cursor right // Cursor right
v.cursor.Right() v.cursor.Right()
ret = 1
case tcell.KeyEnter: case tcell.KeyEnter:
// Insert a newline // Insert a newline
v.eh.Insert(v.cursor.loc, "\n") v.eh.Insert(v.cursor.loc, "\n")
v.cursor.Right() v.cursor.Right()
ret = 2
case tcell.KeySpace: case tcell.KeySpace:
// Insert a space // Insert a space
v.eh.Insert(v.cursor.loc, " ") v.eh.Insert(v.cursor.loc, " ")
v.cursor.Right() v.cursor.Right()
ret = 2
case tcell.KeyBackspace2: case tcell.KeyBackspace2:
// Delete a character // Delete a character
if v.cursor.HasSelection() { if v.cursor.HasSelection() {
v.cursor.DeleteSelection() v.cursor.DeleteSelection()
v.cursor.ResetSelection() v.cursor.ResetSelection()
ret = 2
} else if v.cursor.loc > 0 { } else if v.cursor.loc > 0 {
// We have to do something a bit hacky here because we want to // We have to do something a bit hacky here because we want to
// delete the line by first moving left and then deleting backwards // delete the line by first moving left and then deleting backwards
@ -214,111 +345,35 @@ func (v *View) HandleEvent(event tcell.Event) int {
v.cursor.Right() v.cursor.Right()
v.eh.Remove(v.cursor.loc-1, v.cursor.loc) v.eh.Remove(v.cursor.loc-1, v.cursor.loc)
v.cursor.x, v.cursor.y, v.cursor.loc = cx, cy, cloc v.cursor.x, v.cursor.y, v.cursor.loc = cx, cy, cloc
ret = 2
} }
case tcell.KeyTab: case tcell.KeyTab:
// Insert a tab // Insert a tab
v.eh.Insert(v.cursor.loc, "\t") v.eh.Insert(v.cursor.loc, "\t")
v.cursor.Right() v.cursor.Right()
ret = 2
case tcell.KeyCtrlS: case tcell.KeyCtrlS:
// Save v.Save()
if v.buf.path == "" {
filename, canceled := v.m.Prompt("Filename: ")
if !canceled {
v.buf.path = filename
v.buf.name = filename
} else {
return 2
}
}
err := v.buf.Save()
if err != nil {
v.m.Error(err.Error())
}
// Need to redraw the status line
ret = 1
case tcell.KeyCtrlZ: case tcell.KeyCtrlZ:
// Undo
v.eh.Undo() v.eh.Undo()
ret = 2
case tcell.KeyCtrlY: case tcell.KeyCtrlY:
// Redo
v.eh.Redo() v.eh.Redo()
ret = 2
case tcell.KeyCtrlC: case tcell.KeyCtrlC:
// Copy v.Copy()
if v.cursor.HasSelection() {
if !clipboard.Unsupported {
clipboard.WriteAll(v.cursor.GetSelection())
ret = 2
}
}
case tcell.KeyCtrlX: case tcell.KeyCtrlX:
// Cut v.Cut()
if v.cursor.HasSelection() {
if !clipboard.Unsupported {
clipboard.WriteAll(v.cursor.GetSelection())
v.cursor.DeleteSelection()
v.cursor.ResetSelection()
ret = 2
}
}
case tcell.KeyCtrlV: case tcell.KeyCtrlV:
// Paste v.Paste()
if !clipboard.Unsupported {
if v.cursor.HasSelection() {
v.cursor.DeleteSelection()
v.cursor.ResetSelection()
}
clip, _ := clipboard.ReadAll()
v.eh.Insert(v.cursor.loc, clip)
// This is a bit weird... Not sure if there's a better way
for i := 0; i < Count(clip); i++ {
v.cursor.Right()
}
ret = 2
}
case tcell.KeyCtrlA: case tcell.KeyCtrlA:
// Select all v.SelectAll()
v.cursor.selectionEnd = 0
v.cursor.selectionStart = v.buf.Len()
v.cursor.x = 0
v.cursor.y = 0
v.cursor.loc = 0
ret = 2
case tcell.KeyCtrlO: case tcell.KeyCtrlO:
// Open file v.OpenFile()
if v.buf.IsDirty() {
quit, canceled := v.m.Prompt("You have unsaved changes. Continue? ")
if !canceled {
if strings.ToLower(quit) == "yes" || strings.ToLower(quit) == "y" {
return v.OpenFile()
} else {
return 2
}
} else {
return 2
}
} else {
return v.OpenFile()
}
case tcell.KeyPgUp: case tcell.KeyPgUp:
// Page up
v.PageUp() v.PageUp()
return 2
case tcell.KeyPgDn: case tcell.KeyPgDn:
// Page down
v.PageDown() v.PageDown()
return 2
case tcell.KeyCtrlU: case tcell.KeyCtrlU:
// Half page up
v.HalfPageUp() v.HalfPageUp()
return 2
case tcell.KeyCtrlD: case tcell.KeyCtrlD:
// Half page down
v.HalfPageDown() v.HalfPageDown()
return 2
case tcell.KeyRune: case tcell.KeyRune:
// Insert a character // Insert a character
if v.cursor.HasSelection() { if v.cursor.HasSelection() {
@ -327,7 +382,6 @@ func (v *View) HandleEvent(event tcell.Event) int {
} }
v.eh.Insert(v.cursor.loc, string(e.Rune())) v.eh.Insert(v.cursor.loc, string(e.Rune()))
v.cursor.Right() v.cursor.Right()
ret = 2
} }
case *tcell.EventMouse: case *tcell.EventMouse:
x, y := e.Position() x, y := e.Position()
@ -342,25 +396,7 @@ func (v *View) HandleEvent(event tcell.Event) int {
switch button { switch button {
case tcell.Button1: case tcell.Button1:
// Left click // Left click
if y-v.topline > v.height-1 { v.MoveToMouseClick(x, y)
v.ScrollDown(1)
y = v.height + v.topline - 1
}
if y >= len(v.buf.lines) {
y = len(v.buf.lines) - 1
}
if x < 0 {
x = 0
}
x = v.cursor.GetCharPosInLine(y, x)
if x > Count(v.buf.lines[y]) {
x = Count(v.buf.lines[y])
}
d := v.cursor.Distance(x, y)
v.cursor.loc += d
v.cursor.x = x
v.cursor.y = y
if v.mouseReleased { if v.mouseReleased {
v.cursor.selectionStart = v.cursor.loc v.cursor.selectionStart = v.cursor.loc
@ -369,59 +405,44 @@ func (v *View) HandleEvent(event tcell.Event) int {
} }
v.cursor.selectionEnd = v.cursor.loc v.cursor.selectionEnd = v.cursor.loc
v.mouseReleased = false v.mouseReleased = false
return 2
case tcell.ButtonNone: case tcell.ButtonNone:
// Mouse event with no click // Mouse event with no click
v.mouseReleased = true if !v.mouseReleased {
// We need to directly return here because otherwise the view will // Mouse was just released
// be readjusted to put the cursor in it, but there may be mouse events
// where the cursor is not (and should not be) be involved // Relocating here isn't really necessary because the cursor will
return 0 // be in the right place from the last mouse event
// However, if we are running in a terminal that doesn't support mouse motion
// events, this still allows the user to make selections, except only after they
// release the mouse
v.MoveToMouseClick(x, y)
v.cursor.selectionEnd = v.cursor.loc
v.mouseReleased = true
}
// We don't want to relocate because otherwise the view will be relocated
// everytime the user moves the cursor
relocate = false
case tcell.WheelUp: case tcell.WheelUp:
// Scroll up two lines // Scroll up two lines
v.ScrollUp(2) v.ScrollUp(2)
return 2 // We don't want to relocate if the user is scrolling
relocate = false
case tcell.WheelDown: case tcell.WheelDown:
// Scroll down two lines // Scroll down two lines
v.ScrollDown(2) v.ScrollDown(2)
return 2 // We don't want to relocate if the user is scrolling
relocate = false
} }
} }
// Reset the view so the cursor is in view if relocate {
cy := v.cursor.y v.Relocate()
if cy < v.topline {
v.topline = cy
ret = 2
} }
if cy > v.topline+v.height-1 {
v.topline = cy - v.height + 1
ret = 2
}
return ret
} }
// OpenFile Prompts the user for a filename and opens the file in the current buffer // DisplayView renders the view to the screen
func (v *View) OpenFile() int { func (v *View) DisplayView() {
filename, canceled := v.m.Prompt("File to open: ") // The character number of the character in the top left of the screen
if canceled {
return 2
}
file, err := ioutil.ReadFile(filename)
if err != nil {
v.m.Error(err.Error())
return 2
}
v.buf = NewBuffer(string(file), filename)
return 2
}
// Display renders the view to the screen
func (v *View) Display() {
var x int
charNum := v.cursor.loc + v.cursor.Distance(0, v.topline) charNum := v.cursor.loc + v.cursor.Distance(0, v.topline)
// Convert the length of buffer to a string, and get the length of the string // Convert the length of buffer to a string, and get the length of the string
@ -433,6 +454,9 @@ func (v *View) Display() {
var highlightStyle tcell.Style var highlightStyle tcell.Style
for lineN := 0; lineN < v.height; lineN++ { for lineN := 0; lineN < v.height; lineN++ {
var x int
// If the buffer is smaller than the view height
// and we went too far, break
if lineN+v.topline >= len(v.buf.lines) { if lineN+v.topline >= len(v.buf.lines) {
break break
} }
@ -446,22 +470,23 @@ func (v *View) Display() {
// Write the spaces before the line number if necessary // Write the spaces before the line number if necessary
lineNum := strconv.Itoa(lineN + v.topline + 1) lineNum := strconv.Itoa(lineN + v.topline + 1)
for i := 0; i < maxLineLength-len(lineNum); i++ { for i := 0; i < maxLineLength-len(lineNum); i++ {
v.s.SetContent(x, lineN, ' ', nil, lineNumStyle) screen.SetContent(x, lineN, ' ', nil, lineNumStyle)
x++ x++
} }
// Write the actual line number // Write the actual line number
for _, ch := range lineNum { for _, ch := range lineNum {
v.s.SetContent(x, lineN, ch, nil, lineNumStyle) screen.SetContent(x, lineN, ch, nil, lineNumStyle)
x++ x++
} }
// Write the extra space // Write the extra space
v.s.SetContent(x, lineN, ' ', nil, lineNumStyle) screen.SetContent(x, lineN, ' ', nil, lineNumStyle)
x++ x++
// Write the line // Write the line
tabchars := 0 tabchars := 0
for _, ch := range line { for _, ch := range line {
var lineStyle tcell.Style var lineStyle tcell.Style
// Does the current character need to be syntax highlighted?
st, ok := v.matches[charNum] st, ok := v.matches[charNum]
if ok { if ok {
highlightStyle = st highlightStyle = st
@ -483,17 +508,21 @@ func (v *View) Display() {
} }
if ch == '\t' { if ch == '\t' {
v.s.SetContent(x+tabchars, lineN, ' ', nil, lineStyle) screen.SetContent(x+tabchars, lineN, ' ', nil, lineStyle)
for i := 0; i < tabSize-1; i++ { for i := 0; i < tabSize-1; i++ {
tabchars++ tabchars++
v.s.SetContent(x+tabchars, lineN, ' ', nil, lineStyle) screen.SetContent(x+tabchars, lineN, ' ', nil, lineStyle)
} }
} else { } else {
v.s.SetContent(x+tabchars, lineN, ch, nil, lineStyle) screen.SetContent(x+tabchars, lineN, ch, nil, lineStyle)
} }
charNum++ charNum++
x++ x++
} }
// Here we are at a newline
// The newline may be selected, in which case we should draw the selection style
// with a space to represent it
if v.cursor.HasSelection() && if v.cursor.HasSelection() &&
(charNum >= v.cursor.selectionStart && charNum <= v.cursor.selectionEnd || (charNum >= v.cursor.selectionStart && charNum <= v.cursor.selectionEnd ||
charNum <= v.cursor.selectionStart && charNum >= v.cursor.selectionEnd) { charNum <= v.cursor.selectionStart && charNum >= v.cursor.selectionEnd) {
@ -503,14 +532,17 @@ func (v *View) Display() {
if _, ok := colorscheme["selection"]; ok { if _, ok := colorscheme["selection"]; ok {
selectStyle = colorscheme["selection"] selectStyle = colorscheme["selection"]
} }
v.s.SetContent(x+tabchars, lineN, ' ', nil, selectStyle) screen.SetContent(x+tabchars, lineN, ' ', nil, selectStyle)
} }
x = 0 x = 0
st, ok := v.matches[charNum]
if ok {
highlightStyle = st
}
charNum++ charNum++
} }
} }
// Display renders the view, the cursor, and statusline
func (v *View) Display() {
v.DisplayView()
v.cursor.Display()
v.sline.Display()
}