From d247db3e9d4e9d4462d6a33aa1c666e8477354c4 Mon Sep 17 00:00:00 2001 From: Zachary Yedidia Date: Tue, 21 Nov 2017 00:51:07 -0500 Subject: [PATCH] Implement retab command Ref #919 --- cmd/micro/actions.go | 34 ++++++++++++++++++++++++++++++++++ cmd/micro/command.go | 6 ++++++ runtime/help/commands.md | 3 +++ 3 files changed, 43 insertions(+) diff --git a/cmd/micro/actions.go b/cmd/micro/actions.go index c2b3b652..f89db180 100644 --- a/cmd/micro/actions.go +++ b/cmd/micro/actions.go @@ -542,6 +542,40 @@ func (v *View) ParagraphNext(usePlugin bool) bool { return true } +func (v *View) Retab(usePlugin bool) bool { + if usePlugin && !PreActionCall("Retab", v) { + return false + } + + toSpaces := v.Buf.Settings["tabstospaces"].(bool) + tabsize := int(v.Buf.Settings["tabsize"].(float64)) + dirty := false + + for i := 0; i < v.Buf.NumLines; i++ { + l := v.Buf.Line(i) + + ws := GetLeadingWhitespace(l) + if ws != "" { + if toSpaces { + ws = strings.Replace(ws, "\t", Spaces(tabsize), -1) + } else { + ws = strings.Replace(ws, Spaces(tabsize), "\t", -1) + } + } + + l = strings.TrimLeft(l, " \t") + v.Buf.lines[i].data = []byte(ws + l) + dirty = true + } + + v.Buf.IsModified = dirty + + if usePlugin { + return PostActionCall("Retab", v) + } + return true +} + // CursorStart moves the cursor to the start of the buffer func (v *View) CursorStart(usePlugin bool) bool { if usePlugin && !PreActionCall("CursorStart", v) { diff --git a/cmd/micro/command.go b/cmd/micro/command.go index 3d64768f..b71b1617 100644 --- a/cmd/micro/command.go +++ b/cmd/micro/command.go @@ -55,6 +55,7 @@ func init() { "Open": Open, "TabSwitch": TabSwitch, "MemUsage": MemUsage, + "Retab": Retab, } } @@ -110,6 +111,7 @@ func DefaultCommands() map[string]StrCommand { "open": {"Open", []Completion{FileCompletion}}, "tabswitch": {"TabSwitch", []Completion{NoCompletion}}, "memusage": {"MemUsage", []Completion{NoCompletion}}, + "retab": {"Retab", []Completion{NoCompletion}}, } } @@ -196,6 +198,10 @@ func PluginCmd(args []string) { } } +func Retab(args []string) { + CurView().Retab(true) +} + // TabSwitch switches to a given tab either by name or by number func TabSwitch(args []string) { if len(args) > 0 { diff --git a/runtime/help/commands.md b/runtime/help/commands.md index e6577294..45264f2a 100644 --- a/runtime/help/commands.md +++ b/runtime/help/commands.md @@ -76,6 +76,9 @@ Here are the possible commands that you can use. * `open filename`: Open a file in the current buffer. +* `retab`: Replaces all leading tabs with spaces or leading spaces with tabs + depending on the value of `tabstospaces`. + --- The following commands are provided by the default plugins: