Cleanup and add more comments

This commit is contained in:
Zachary Yedidia 2016-10-18 11:12:28 -04:00
parent 8db3b22411
commit 1b9bb31dd6
8 changed files with 60 additions and 39 deletions

View file

@ -619,7 +619,7 @@ func (v *View) OutdentLine(usePlugin bool) bool {
if v.Cursor.HasSelection() { if v.Cursor.HasSelection() {
return false return false
} }
for x := 0; x < len(v.Buf.IndentString()); x++ { for x := 0; x < len(v.Buf.IndentString()); x++ {
if len(GetLeadingWhitespace(v.Buf.Line(v.Cursor.Y))) == 0 { if len(GetLeadingWhitespace(v.Buf.Line(v.Cursor.Y))) == 0 {
break break
@ -678,7 +678,7 @@ func (v *View) InsertTab(usePlugin bool) bool {
if v.Cursor.HasSelection() { if v.Cursor.HasSelection() {
return false return false
} }
tabBytes := len(v.Buf.IndentString()) tabBytes := len(v.Buf.IndentString())
bytesUntilIndent := tabBytes - (v.Cursor.GetVisualX() % tabBytes) bytesUntilIndent := tabBytes - (v.Cursor.GetVisualX() % tabBytes)
v.Buf.Insert(v.Cursor.Loc, v.Buf.IndentString()[:bytesUntilIndent]) v.Buf.Insert(v.Cursor.Loc, v.Buf.IndentString()[:bytesUntilIndent])
@ -1627,6 +1627,7 @@ func (v *View) PreviousSplit(usePlugin bool) bool {
var curMacro []interface{} var curMacro []interface{}
var recordingMacro bool var recordingMacro bool
// ToggleMacro toggles recording of a macro
func (v *View) ToggleMacro(usePlugin bool) bool { func (v *View) ToggleMacro(usePlugin bool) bool {
if usePlugin && !PreActionCall("ToggleMacro", v) { if usePlugin && !PreActionCall("ToggleMacro", v) {
return false return false
@ -1647,6 +1648,7 @@ func (v *View) ToggleMacro(usePlugin bool) bool {
return true return true
} }
// PlayMacro plays back the most recently recorded macro
func (v *View) PlayMacro(usePlugin bool) bool { func (v *View) PlayMacro(usePlugin bool) bool {
if usePlugin && !PreActionCall("PlayMacro", v) { if usePlugin && !PreActionCall("PlayMacro", v) {
return false return false

View file

@ -186,9 +186,8 @@ func (b *Buffer) FileType() string {
func (b *Buffer) IndentString() string { func (b *Buffer) IndentString() string {
if b.Settings["tabstospaces"].(bool) { if b.Settings["tabstospaces"].(bool) {
return Spaces(int(b.Settings["tabsize"].(float64))) return Spaces(int(b.Settings["tabsize"].(float64)))
} else {
return "\t"
} }
return "\t"
} }
// CheckModTime makes sure that the file this buffer points to hasn't been updated // CheckModTime makes sure that the file this buffer points to hasn't been updated
@ -376,6 +375,7 @@ func (b *Buffer) Len() int {
return Count(b.String()) return Count(b.String())
} }
// MoveLinesUp moves the range of lines up one row
func (b *Buffer) MoveLinesUp(start int, end int) { func (b *Buffer) MoveLinesUp(start int, end int) {
// 0 < start < end <= len(b.lines) // 0 < start < end <= len(b.lines)
if start < 1 || start >= end || end > len(b.lines) { if start < 1 || start >= end || end > len(b.lines) {
@ -401,6 +401,7 @@ func (b *Buffer) MoveLinesUp(start int, end int) {
) )
} }
// MoveLinesDown moves the range of lines down one row
func (b *Buffer) MoveLinesDown(start int, end int) { func (b *Buffer) MoveLinesDown(start int, end int) {
// 0 <= start < end < len(b.lines) // 0 <= start < end < len(b.lines)
// if end == len(b.lines), we can't do anything here because the // if end == len(b.lines), we can't do anything here because the
@ -412,7 +413,7 @@ func (b *Buffer) MoveLinesDown(start int, end int) {
Loc{0, start}, Loc{0, start},
b.Line(end)+"\n", b.Line(end)+"\n",
) )
end += 1 end++
b.Remove( b.Remove(
Loc{0, end}, Loc{0, end},
Loc{0, end + 1}, Loc{0, end + 1},

View file

@ -419,8 +419,7 @@ func Replace(args []string) {
if matches != nil && len(matches) > 0 { if matches != nil && len(matches) > 0 {
prevMatchCount := runePos(matches[0][0], bufStr) prevMatchCount := runePos(matches[0][0], bufStr)
searchCount := runePos(matches[0][1], bufStr) - prevMatchCount searchCount := runePos(matches[0][1], bufStr) - prevMatchCount
prevMatch := matches[0] from := FromCharPos(matches[0][0], view.Buf)
from := FromCharPos(prevMatch[0], view.Buf)
to := from.Move(searchCount, view.Buf) to := from.Move(searchCount, view.Buf)
adjust := Count(replace) - searchCount adjust := Count(replace) - searchCount
view.Buf.Replace(from, to, replace) view.Buf.Replace(from, to, replace)
@ -432,7 +431,6 @@ func Replace(args []string) {
from = from.Move(matchCount-prevMatchCount+adjust, view.Buf) from = from.Move(matchCount-prevMatchCount+adjust, view.Buf)
to = from.Move(searchCount, view.Buf) to = from.Move(searchCount, view.Buf)
view.Buf.Replace(from, to, replace) view.Buf.Replace(from, to, replace)
prevMatch = match
prevMatchCount = matchCount prevMatchCount = matchCount
adjust = Count(replace) - searchCount adjust = Count(replace) - searchCount
} }

View file

@ -206,7 +206,7 @@ var flagStartPos = flag.String("startpos", "", "LINE,COL to start the cursor at
func main() { func main() {
flag.Usage = func() { flag.Usage = func() {
fmt.Println("Usage: micro [OPTIONS] [FILE]...") fmt.Println("Usage: micro [OPTIONS] [FILE]...")
fmt.Println("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") 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")
flag.PrintDefaults() flag.PrintDefaults()
} }

View file

@ -19,7 +19,7 @@ import (
) )
var ( var (
allPluginPackages PluginPackages = nil allPluginPackages PluginPackages
) )
// CorePluginName is a plugin dependency name for the micro core. // CorePluginName is a plugin dependency name for the micro core.
@ -57,7 +57,7 @@ type PluginVersion struct {
// PluginVersions is a slice of PluginVersion // PluginVersions is a slice of PluginVersion
type PluginVersions []*PluginVersion type PluginVersions []*PluginVersion
// PluginDenendency descripes a dependency to another plugin or micro itself. // PluginDependency descripes a dependency to another plugin or micro itself.
type PluginDependency struct { type PluginDependency struct {
Name string Name string
Range semver.Range Range semver.Range
@ -246,9 +246,8 @@ func GetAllPluginPackages() PluginPackages {
allPluginPackages = fetchAllSources(len(repos)+1, func(i int) PluginPackages { allPluginPackages = fetchAllSources(len(repos)+1, func(i int) PluginPackages {
if i == 0 { if i == 0 {
return channels.Fetch() return channels.Fetch()
} else {
return repos[i-1].Fetch()
} }
return repos[i-1].Fetch()
}) })
} }
return allPluginPackages return allPluginPackages
@ -274,8 +273,8 @@ func (pv PluginVersions) Swap(i, j int) {
} }
// Less returns true if the version at position i is greater then the version at position j (used for sorting) // Less returns true if the version at position i is greater then the version at position j (used for sorting)
func (s PluginVersions) Less(i, j int) bool { func (pv PluginVersions) Less(i, j int) bool {
return s[i].Version.GT(s[j].Version) return pv[i].Version.GT(pv[j].Version)
} }
// Match returns true if the package matches a given search text // Match returns true if the package matches a given search text
@ -382,6 +381,7 @@ func GetInstalledPluginVersion(name string) string {
return "" return ""
} }
// DownloadAndInstall downloads and installs the given plugin and version
func (pv *PluginVersion) DownloadAndInstall() error { func (pv *PluginVersion) DownloadAndInstall() error {
messenger.AddLog(fmt.Sprintf("Downloading %q (%s) from %q", pv.pack.Name, pv.Version, pv.Url)) messenger.AddLog(fmt.Sprintf("Downloading %q (%s) from %q", pv.pack.Name, pv.Version, pv.Url))
resp, err := http.Get(pv.Url) resp, err := http.Get(pv.Url)
@ -439,13 +439,13 @@ func (pv *PluginVersion) DownloadAndInstall() error {
return err return err
} }
defer content.Close() defer content.Close()
if target, err := os.Create(targetName); err != nil { target, err := os.Create(targetName)
if err != nil {
return err
}
defer target.Close()
if _, err = io.Copy(target, content); err != nil {
return err return err
} else {
defer target.Close()
if _, err = io.Copy(target, content); err != nil {
return err
}
} }
} }
} }
@ -495,6 +495,7 @@ func (req PluginDependencies) Join(other PluginDependencies) PluginDependencies
return result return result
} }
// Resolve resolves dependencies between different plugins
func (all PluginPackages) Resolve(selectedVersions PluginVersions, open PluginDependencies) (PluginVersions, error) { func (all PluginPackages) Resolve(selectedVersions PluginVersions, open PluginDependencies) (PluginVersions, error) {
if len(open) == 0 { if len(open) == 0 {
return selectedVersions, nil return selectedVersions, nil
@ -506,31 +507,29 @@ func (all PluginPackages) Resolve(selectedVersions PluginVersions, open PluginDe
return all.Resolve(selectedVersions, stillOpen) return all.Resolve(selectedVersions, stillOpen)
} }
return nil, fmt.Errorf("unable to find a matching version for \"%s\"", currentRequirement.Name) return nil, fmt.Errorf("unable to find a matching version for \"%s\"", currentRequirement.Name)
} else { }
availableVersions := all.GetAllVersions(currentRequirement.Name) availableVersions := all.GetAllVersions(currentRequirement.Name)
sort.Sort(availableVersions) sort.Sort(availableVersions)
for _, version := range availableVersions { for _, version := range availableVersions {
if currentRequirement.Range(version.Version) { if currentRequirement.Range(version.Version) {
resolved, err := all.Resolve(append(selectedVersions, version), stillOpen.Join(version.Require)) resolved, err := all.Resolve(append(selectedVersions, version), stillOpen.Join(version.Require))
if err == nil { if err == nil {
return resolved, nil return resolved, nil
}
} }
} }
return nil, fmt.Errorf("unable to find a matching version for \"%s\"", currentRequirement.Name)
} }
} else { return nil, fmt.Errorf("unable to find a matching version for \"%s\"", currentRequirement.Name)
return selectedVersions, nil
} }
return selectedVersions, nil
} }
func (versions PluginVersions) install() { func (pv PluginVersions) install() {
anyInstalled := false anyInstalled := false
currentlyInstalled := GetInstalledVersions(true) currentlyInstalled := GetInstalledVersions(true)
for _, sel := range versions { for _, sel := range pv {
if sel.pack.Name != CorePluginName { if sel.pack.Name != CorePluginName {
shouldInstall := true shouldInstall := true
if pv := currentlyInstalled.find(sel.pack.Name); pv != nil { if pv := currentlyInstalled.find(sel.pack.Name); pv != nil {
@ -565,6 +564,7 @@ func UninstallPlugin(name string) {
} }
} }
// Install installs the plugin
func (pl PluginPackage) Install() { func (pl PluginPackage) Install() {
selected, err := GetAllPluginPackages().Resolve(GetInstalledVersions(true), PluginDependencies{ selected, err := GetAllPluginPackages().Resolve(GetInstalledVersions(true), PluginDependencies{
&PluginDependency{ &PluginDependency{
@ -578,6 +578,7 @@ func (pl PluginPackage) Install() {
selected.install() selected.install()
} }
// UpdatePlugins updates the given plugins
func UpdatePlugins(plugins []string) { func UpdatePlugins(plugins []string) {
// if no plugins are specified, update all installed plugins. // if no plugins are specified, update all installed plugins.
if len(plugins) == 0 { if len(plugins) == 0 {

View file

@ -1,24 +1,30 @@
package main package main
// SpltType specifies whether a split is horizontal or vertical
type SplitType bool type SplitType bool
const ( const (
VerticalSplit = false // VerticalSplit type
VerticalSplit = false
// HorizontalSplit type
HorizontalSplit = true HorizontalSplit = true
) )
// A Node on the split tree
type Node interface { type Node interface {
VSplit(buf *Buffer) VSplit(buf *Buffer)
HSplit(buf *Buffer) HSplit(buf *Buffer)
String() string String() string
} }
// A LeafNode is an actual split so it contains a view
type LeafNode struct { type LeafNode struct {
view *View view *View
parent *SplitTree parent *SplitTree
} }
// NewLeafNode returns a new leaf node containing the given view
func NewLeafNode(v *View, parent *SplitTree) *LeafNode { func NewLeafNode(v *View, parent *SplitTree) *LeafNode {
n := new(LeafNode) n := new(LeafNode)
n.view = v n.view = v
@ -27,6 +33,7 @@ func NewLeafNode(v *View, parent *SplitTree) *LeafNode {
return n return n
} }
// A SplitTree is a Node itself and it contains other nodes
type SplitTree struct { type SplitTree struct {
kind SplitType kind SplitType
@ -42,6 +49,7 @@ type SplitTree struct {
tabNum int tabNum int
} }
// VSplit creates a vertical split
func (l *LeafNode) VSplit(buf *Buffer) { func (l *LeafNode) VSplit(buf *Buffer) {
tab := tabs[l.parent.tabNum] tab := tabs[l.parent.tabNum]
if l.parent.kind == VerticalSplit { if l.parent.kind == VerticalSplit {
@ -69,6 +77,7 @@ func (l *LeafNode) VSplit(buf *Buffer) {
} }
} }
// HSplit creates a horizontal split
func (l *LeafNode) HSplit(buf *Buffer) { func (l *LeafNode) HSplit(buf *Buffer) {
tab := tabs[l.parent.tabNum] tab := tabs[l.parent.tabNum]
if l.parent.kind == HorizontalSplit { if l.parent.kind == HorizontalSplit {
@ -96,6 +105,7 @@ func (l *LeafNode) HSplit(buf *Buffer) {
} }
} }
// Delete deletes a split
func (l *LeafNode) Delete() { func (l *LeafNode) Delete() {
i := search(l.parent.children, l) i := search(l.parent.children, l)
@ -117,6 +127,7 @@ func (l *LeafNode) Delete() {
} }
} }
// Cleanup rearranges all the parents after a split has been deleted
func (s *SplitTree) Cleanup() { func (s *SplitTree) Cleanup() {
for i, node := range s.children { for i, node := range s.children {
if n, ok := node.(*SplitTree); ok { if n, ok := node.(*SplitTree); ok {
@ -132,6 +143,7 @@ func (s *SplitTree) Cleanup() {
} }
} }
// ResizeSplits resizes all the splits correctly
func (s *SplitTree) ResizeSplits() { func (s *SplitTree) ResizeSplits() {
for i, node := range s.children { for i, node := range s.children {
if n, ok := node.(*LeafNode); ok { if n, ok := node.(*LeafNode); ok {
@ -195,7 +207,10 @@ func findView(haystack []*View, needle *View) int {
return 0 return 0
} }
// VSplit is here just to make SplitTree fit the Node interface
func (s *SplitTree) VSplit(buf *Buffer) {} func (s *SplitTree) VSplit(buf *Buffer) {}
// HSplit is here just to make SplitTree fit the Node interface
func (s *SplitTree) HSplit(buf *Buffer) {} func (s *SplitTree) HSplit(buf *Buffer) {}
func (s *SplitTree) String() string { func (s *SplitTree) String() string {

View file

@ -23,7 +23,7 @@ func Count(s string) int {
return utf8.RuneCountInString(s) return utf8.RuneCountInString(s)
} }
// NumOccurrences counts the number of occurences of a byte in a string // NumOccurrences counts the number of occurrences of a byte in a string
func NumOccurrences(s string, c byte) int { func NumOccurrences(s string, c byte) int {
var n int var n int
for i := 0; i < len(s); i++ { for i := 0; i < len(s); i++ {
@ -244,11 +244,11 @@ func FuncName(i interface{}) string {
return runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name() return runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name()
} }
// SplitCommandArgs seperates multiple command arguments which may be quoted. // SplitCommandArgs separates multiple command arguments which may be quoted.
// The returned slice contains at least one string // The returned slice contains at least one string
func SplitCommandArgs(input string) []string { func SplitCommandArgs(input string) []string {
var result []string var result []string
var curQuote *bytes.Buffer = nil var curQuote *bytes.Buffer
curArg := new(bytes.Buffer) curArg := new(bytes.Buffer)
escape := false escape := false

View file

@ -129,6 +129,7 @@ func NewViewWidthHeight(buf *Buffer, w, h int) *View {
return v return v
} }
// ToggleStatusLine creates an extra row for the statusline if necessary
func (v *View) ToggleStatusLine() { func (v *View) ToggleStatusLine() {
if v.Buf.Settings["statusline"].(bool) { if v.Buf.Settings["statusline"].(bool) {
v.height-- v.height--
@ -137,6 +138,7 @@ func (v *View) ToggleStatusLine() {
} }
} }
// ToggleTabbar creates an extra row for the tabbar if necessary
func (v *View) ToggleTabbar() { func (v *View) ToggleTabbar() {
if len(tabs) > 1 { if len(tabs) > 1 {
if v.y == 0 { if v.y == 0 {
@ -234,6 +236,7 @@ func (v *View) OpenBuffer(buf *Buffer) {
v.lastClickTime = time.Time{} v.lastClickTime = time.Time{}
} }
// Open opens the given file in the view
func (v *View) Open(filename string) { func (v *View) Open(filename string) {
home, _ := homedir.Dir() home, _ := homedir.Dir()
filename = strings.Replace(filename, "~", home, 1) filename = strings.Replace(filename, "~", home, 1)
@ -281,6 +284,7 @@ func (v *View) VSplit(buf *Buffer) bool {
return false return false
} }
// GetSoftWrapLocation gets the location of a visual click on the screen and converts it to col,line
func (v *View) GetSoftWrapLocation(vx, vy int) (int, int) { func (v *View) GetSoftWrapLocation(vx, vy int) (int, int) {
if !v.Buf.Settings["softwrap"].(bool) { if !v.Buf.Settings["softwrap"].(bool) {
vx = v.Cursor.GetCharPosInLine(vy, vx) vx = v.Cursor.GetCharPosInLine(vy, vx)