text
stringlengths 9
39.2M
| dir
stringlengths 25
226
| lang
stringclasses 163
values | created_date
timestamp[s] | updated_date
timestamp[s] | repo_name
stringclasses 751
values | repo_full_name
stringclasses 752
values | star
int64 1.01k
183k
| len_tokens
int64 1
18.5M
|
|---|---|---|---|---|---|---|---|---|
```go
//go:build ignore
// +build ignore
package main
import (
"fmt"
"io/ioutil"
"os"
"runtime"
)
func check(e error) {
if e != nil {
panic(e)
}
}
func main() {
if runtime.GOOS != "darwin" {
return
}
if len(os.Args) == 3 {
if os.Args[1] == "darwin" && runtime.GOOS == "darwin" {
rawInfoPlistString := `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "path_to_url">
<plist version="1.0">
<dict>
<key>CFBundleIdentifier</key>
<string>io.github.micro-editor</string>
<key>CFBundleName</key>
<string>micro</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>` + os.Args[2] + `</string>
</dict>
</plist>
`
infoPlistData := []byte(rawInfoPlistString)
err := ioutil.WriteFile("/tmp/micro-info.plist", infoPlistData, 0644)
check(err)
fmt.Println("-linkmode external -extldflags -Wl,-sectcreate,__TEXT,__info_plist,/tmp/micro-info.plist")
}
} else {
panic("missing arguments")
}
}
```
|
/content/code_sandbox/tools/info-plist.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 364
|
```shell
command -v fpm > /dev/null && fpm -s dir -t deb -p micro-$1-amd64.deb --name micro --license mit --version $1 --deb-recommends xclip --description "A modern and intuitive terminal-based text editor" --after-install ./assets/packaging/deb/micro.postinst --before-remove ./assets/packaging/deb/micro.prerm ./micro=/usr/bin/micro ./assets/packaging/micro.1=/usr/share/man/man1/micro.1
```
|
/content/code_sandbox/tools/package-deb.sh
|
shell
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 112
|
```shell
# This script creates releases on Github for micro
# You must have the correct Github access token to run this script
# $1 is the title, $2 is the description
commitID=$(git rev-parse HEAD)
tag="v$1"
echo "Creating tag"
git tag $tag $commitID
hub push --tags
echo "Cross compiling binaries"
./cross-compile.sh $1
mv ../binaries .
NL=$'\n'
echo "Creating new release"
hub release create $tag \
--prerelease \
--message "$1${NL}${NL}$2" \
--attach "binaries/micro-$1-osx.tar.gz" \
--attach "binaries/micro-$1-macos-arm64.tar.gz" \
--attach "binaries/micro-$1-linux64.tar.gz" \
--attach "binaries/micro-$1-linux64-static.tar.gz" \
--attach "binaries/micro-$1-amd64.deb" \
--attach "binaries/micro-$1-linux32.tar.gz" \
--attach "binaries/micro-$1-linux-arm.tar.gz" \
--attach "binaries/micro-$1-linux-arm64.tar.gz" \
--attach "binaries/micro-$1-freebsd64.tar.gz" \
--attach "binaries/micro-$1-freebsd32.tar.gz" \
--attach "binaries/micro-$1-openbsd64.tar.gz" \
--attach "binaries/micro-$1-openbsd32.tar.gz" \
--attach "binaries/micro-$1-netbsd64.tar.gz" \
--attach "binaries/micro-$1-netbsd32.tar.gz" \
--attach "binaries/micro-$1-win64.zip" \
--attach "binaries/micro-$1-win32.zip"
```
|
/content/code_sandbox/tools/pre-release.sh
|
shell
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 388
|
```go
//+build ignore
package main
import (
"fmt"
"os"
"strconv"
"time"
)
func main() {
var buildTime time.Time
epoch := os.Getenv("SOURCE_DATE_EPOCH")
if epoch != "" {
i, err := strconv.Atoi(epoch)
if err != nil {
fmt.Errorf("SOURCE_DATE_EPOCH is not a valid integer")
os.Exit(1)
}
buildTime = time.Unix(int64(i), 0)
} else {
buildTime = time.Now().Local()
}
fmt.Println(buildTime.Format("January 02, 2006"))
}
```
|
/content/code_sandbox/tools/build-date.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 132
|
```go
//+build ignore
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"regexp"
"strings"
"github.com/robertkrimen/otto/ast"
"github.com/robertkrimen/otto/parser"
)
type walker struct {
nodes []ast.Node
}
func (w *walker) Enter(node ast.Node) ast.Visitor {
w.nodes = append(w.nodes, node)
return w
}
func (w *walker) Exit(node ast.Node) {
}
func getAllNodes(node ast.Node) []ast.Node {
w := &walker{}
ast.Walk(w, node)
return w.nodes
}
func getCalls(node ast.Node, name string) []*ast.CallExpression {
nodes := []*ast.CallExpression{}
for _, n := range getAllNodes(node) {
if ce, ok := n.(*ast.CallExpression); ok {
var calleeName string
switch callee := ce.Callee.(type) {
case *ast.Identifier:
calleeName = callee.Name
case *ast.DotExpression:
calleeName = callee.Identifier.Name
default:
continue
}
if calleeName == name {
nodes = append(nodes, ce)
}
}
}
return nodes
}
func getPropertyValue(node ast.Node, key string) ast.Expression {
for _, p := range node.(*ast.ObjectLiteral).Value {
if p.Key == key {
return p.Value
}
}
return nil
}
type operation struct {
startLine int
startColumn int
endLine int
endColumn int
text []string
}
type check struct {
before []string
operations []operation
after []string
}
type test struct {
description string
checks []check
}
func stringSliceToGoSource(slice []string) string {
var b strings.Builder
b.WriteString("[]string{\n")
for _, s := range slice {
b.WriteString(fmt.Sprintf("%#v,\n", s))
}
b.WriteString("}")
return b.String()
}
func testToGoTest(test test, name string) string {
var b strings.Builder
b.WriteString("func Test")
b.WriteString(name)
b.WriteString("(t *testing.T) {\n")
for _, c := range test.checks {
b.WriteString("check(\n")
b.WriteString("t,\n")
b.WriteString(fmt.Sprintf("%v,\n", stringSliceToGoSource(c.before)))
b.WriteString("[]operation{\n")
for _, op := range c.operations {
b.WriteString("operation{\n")
b.WriteString(fmt.Sprintf("start: Loc{%v, %v},\n", op.startColumn, op.startLine))
b.WriteString(fmt.Sprintf("end: Loc{%v, %v},\n", op.endColumn, op.endLine))
b.WriteString(fmt.Sprintf("text: %v,\n", stringSliceToGoSource(op.text)))
b.WriteString("},\n")
}
b.WriteString("},\n")
b.WriteString(fmt.Sprintf("%v,\n", stringSliceToGoSource(c.after)))
b.WriteString(")\n")
}
b.WriteString("}\n")
return b.String()
}
func nodeToStringSlice(node ast.Node) []string {
var result []string
for _, s := range node.(*ast.ArrayLiteral).Value {
result = append(result, s.(*ast.StringLiteral).Value)
}
return result
}
func nodeToStringSlice2(node ast.Node) []string {
var result []string
for _, o := range node.(*ast.ArrayLiteral).Value {
result = append(result, getPropertyValue(o, "text").(*ast.StringLiteral).Value)
}
return result
}
func nodeToInt(node ast.Node) int {
return int(node.(*ast.NumberLiteral).Value.(int64))
}
func getChecks(node ast.Node) []check {
checks := []check{}
for _, ce := range getCalls(node, "testApplyEdits") {
if len(ce.ArgumentList) != 3 {
// Wrong function
continue
}
before := nodeToStringSlice2(ce.ArgumentList[0])
after := nodeToStringSlice2(ce.ArgumentList[2])
var operations []operation
for _, op := range ce.ArgumentList[1].(*ast.ArrayLiteral).Value {
args := getPropertyValue(op, "range").(*ast.NewExpression).ArgumentList
operations = append(operations, operation{
startLine: nodeToInt(args[0]) - 1,
startColumn: nodeToInt(args[1]) - 1,
endLine: nodeToInt(args[2]) - 1,
endColumn: nodeToInt(args[3]) - 1,
text: []string{getPropertyValue(op, "text").(*ast.StringLiteral).Value},
})
}
checks = append(checks, check{before, operations, after})
}
for _, ce := range getCalls(node, "testApplyEditsWithSyncedModels") {
if len(ce.ArgumentList) > 3 && ce.ArgumentList[3].(*ast.BooleanLiteral).Value {
// inputEditsAreInvalid == true
continue
}
before := nodeToStringSlice(ce.ArgumentList[0])
after := nodeToStringSlice(ce.ArgumentList[2])
var operations []operation
for _, op := range getCalls(ce.ArgumentList[1], "editOp") {
operations = append(operations, operation{
startLine: nodeToInt(op.ArgumentList[0]) - 1,
startColumn: nodeToInt(op.ArgumentList[1]) - 1,
endLine: nodeToInt(op.ArgumentList[2]) - 1,
endColumn: nodeToInt(op.ArgumentList[3]) - 1,
text: nodeToStringSlice(op.ArgumentList[4]),
})
}
checks = append(checks, check{before, operations, after})
}
return checks
}
func getTests(node ast.Node) []test {
tests := []test{}
for _, ce := range getCalls(node, "test") {
description := ce.ArgumentList[0].(*ast.StringLiteral).Value
body := ce.ArgumentList[1].(*ast.FunctionLiteral).Body
checks := getChecks(body)
if len(checks) > 0 {
tests = append(tests, test{description, checks})
}
}
return tests
}
func main() {
var tests []test
for _, filename := range os.Args[1:] {
source, err := ioutil.ReadFile(filename)
if err != nil {
log.Fatalln(err)
}
program, err := parser.ParseFile(nil, "", source, parser.IgnoreRegExpErrors)
if err != nil {
log.Fatalln(err)
}
tests = append(tests, getTests(program)...)
}
if len(tests) == 0 {
log.Fatalln("no tests found!")
}
fmt.Println("// This file is generated from VSCode model tests by the testgen tool.")
fmt.Println("// DO NOT EDIT THIS FILE BY HAND; your changes will be overwritten!\n")
fmt.Println("package buffer")
fmt.Println(`import "testing"`)
re := regexp.MustCompile(`[^\w]`)
usedNames := map[string]bool{}
for _, test := range tests {
name := strings.Title(strings.ToLower(test.description))
name = re.ReplaceAllLiteralString(name, "")
if name == "" {
name = "Unnamed"
}
if usedNames[name] {
for i := 2; ; i++ {
newName := fmt.Sprintf("%v_%v", name, i)
if !usedNames[newName] {
name = newName
break
}
}
}
usedNames[name] = true
fmt.Println(testToGoTest(test, name))
}
}
```
|
/content/code_sandbox/tools/testgen.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 1,684
|
```go
package highlight
import (
"bytes"
"errors"
"fmt"
"regexp"
"gopkg.in/yaml.v2"
)
// A Group represents a syntax group
type Group uint8
// Groups contains all of the groups that are defined
// You can access them in the map via their string name
var Groups map[string]Group
var numGroups Group
// String returns the group name attached to the specific group
func (g Group) String() string {
for k, v := range Groups {
if v == g {
return k
}
}
return ""
}
// A Def is a full syntax definition for a language
// It has a filetype, information about how to detect the filetype based
// on filename or header (the first line of the file)
// Then it has the rules which define how to highlight the file
type Def struct {
*Header
rules *rules
}
type Header struct {
FileType string
FileNameRegex *regexp.Regexp
HeaderRegex *regexp.Regexp
SignatureRegex *regexp.Regexp
}
type HeaderYaml struct {
FileType string `yaml:"filetype"`
Detect struct {
FNameRegexStr string `yaml:"filename"`
HeaderRegexStr string `yaml:"header"`
SignatureRegexStr string `yaml:"signature"`
} `yaml:"detect"`
}
type File struct {
FileType string
yamlSrc map[interface{}]interface{}
}
// A Pattern is one simple syntax rule
// It has a group that the rule belongs to, as well as
// the regular expression to match the pattern
type pattern struct {
group Group
regex *regexp.Regexp
}
// rules defines which patterns and regions can be used to highlight
// a filetype
type rules struct {
regions []*region
patterns []*pattern
includes []string
}
// A region is a highlighted region (such as a multiline comment, or a string)
// It belongs to a group, and has start and end regular expressions
// A region also has rules of its own that only apply when matching inside the
// region and also rules from the above region do not match inside this region
// Note that a region may contain more regions
type region struct {
group Group
limitGroup Group
parent *region
start *regexp.Regexp
end *regexp.Regexp
skip *regexp.Regexp
rules *rules
}
func init() {
Groups = make(map[string]Group)
}
// MakeHeader takes a header (.hdr file) file and parses the header
// Header files make parsing more efficient when you only want to compute
// on the headers of syntax files
// A yaml file might take ~400us to parse while a header file only takes ~20us
func MakeHeader(data []byte) (*Header, error) {
lines := bytes.Split(data, []byte{'\n'})
if len(lines) < 4 {
return nil, errors.New("Header file has incorrect format")
}
header := new(Header)
var err error
header.FileType = string(lines[0])
fnameRegexStr := string(lines[1])
headerRegexStr := string(lines[2])
signatureRegexStr := string(lines[3])
if fnameRegexStr != "" {
header.FileNameRegex, err = regexp.Compile(fnameRegexStr)
}
if err == nil && headerRegexStr != "" {
header.HeaderRegex, err = regexp.Compile(headerRegexStr)
}
if err == nil && signatureRegexStr != "" {
header.SignatureRegex, err = regexp.Compile(signatureRegexStr)
}
if err != nil {
return nil, err
}
return header, nil
}
// MakeHeaderYaml takes a yaml spec for a syntax file and parses the
// header
func MakeHeaderYaml(data []byte) (*Header, error) {
var hdrYaml HeaderYaml
err := yaml.Unmarshal(data, &hdrYaml)
if err != nil {
return nil, err
}
header := new(Header)
header.FileType = hdrYaml.FileType
if hdrYaml.Detect.FNameRegexStr != "" {
header.FileNameRegex, err = regexp.Compile(hdrYaml.Detect.FNameRegexStr)
}
if err == nil && hdrYaml.Detect.HeaderRegexStr != "" {
header.HeaderRegex, err = regexp.Compile(hdrYaml.Detect.HeaderRegexStr)
}
if err == nil && hdrYaml.Detect.SignatureRegexStr != "" {
header.SignatureRegex, err = regexp.Compile(hdrYaml.Detect.SignatureRegexStr)
}
if err != nil {
return nil, err
}
return header, nil
}
// MatchFileName will check the given file name with the stored regex
func (header *Header) MatchFileName(filename string) bool {
if header.FileNameRegex != nil {
return header.FileNameRegex.MatchString(filename)
}
return false
}
func (header *Header) MatchFileHeader(firstLine []byte) bool {
if header.HeaderRegex != nil {
return header.HeaderRegex.Match(firstLine)
}
return false
}
// HasFileSignature checks the presence of a stored signature
func (header *Header) HasFileSignature() bool {
return header.SignatureRegex != nil
}
// MatchFileSignature will check the given line with the stored regex
func (header *Header) MatchFileSignature(line []byte) bool {
if header.SignatureRegex != nil {
return header.SignatureRegex.Match(line)
}
return false
}
func ParseFile(input []byte) (f *File, err error) {
// This is just so if we have an error, we can exit cleanly and return the parse error to the user
defer func() {
if r := recover(); r != nil {
var ok bool
err, ok = r.(error)
if !ok {
err = fmt.Errorf("pkg: %v", r)
}
}
}()
var rules map[interface{}]interface{}
if err = yaml.Unmarshal(input, &rules); err != nil {
return nil, err
}
f = new(File)
f.yamlSrc = rules
for k, v := range rules {
if k == "filetype" {
filetype := v.(string)
if filetype == "" {
return nil, errors.New("empty filetype")
}
f.FileType = filetype
break
}
}
if f.FileType == "" {
return nil, errors.New("missing filetype")
}
return f, err
}
// ParseDef parses an input syntax file into a highlight Def
func ParseDef(f *File, header *Header) (s *Def, err error) {
// This is just so if we have an error, we can exit cleanly and return the parse error to the user
defer func() {
if r := recover(); r != nil {
var ok bool
err, ok = r.(error)
if !ok {
err = fmt.Errorf("pkg: %v", r)
}
}
}()
src := f.yamlSrc
s = new(Def)
s.Header = header
for k, v := range src {
if k == "rules" {
inputRules := v.([]interface{})
rules, err := parseRules(inputRules, nil)
if err != nil {
return nil, err
}
s.rules = rules
}
}
if s.rules == nil {
// allow empty rules
s.rules = new(rules)
}
return s, err
}
// HasIncludes returns whether this syntax def has any include statements
func HasIncludes(d *Def) bool {
hasIncludes := len(d.rules.includes) > 0
for _, r := range d.rules.regions {
hasIncludes = hasIncludes || hasIncludesInRegion(r)
}
return hasIncludes
}
func hasIncludesInRegion(region *region) bool {
hasIncludes := len(region.rules.includes) > 0
for _, r := range region.rules.regions {
hasIncludes = hasIncludes || hasIncludesInRegion(r)
}
return hasIncludes
}
// GetIncludes returns a list of filetypes that are included by this syntax def
func GetIncludes(d *Def) []string {
includes := d.rules.includes
for _, r := range d.rules.regions {
includes = append(includes, getIncludesInRegion(r)...)
}
return includes
}
func getIncludesInRegion(region *region) []string {
includes := region.rules.includes
for _, r := range region.rules.regions {
includes = append(includes, getIncludesInRegion(r)...)
}
return includes
}
// ResolveIncludes will sort out the rules for including other filetypes
// You should call this after parsing all the Defs
func ResolveIncludes(def *Def, files []*File) {
resolveIncludesInDef(files, def)
}
func resolveIncludesInDef(files []*File, d *Def) {
for _, lang := range d.rules.includes {
for _, searchFile := range files {
if lang == searchFile.FileType {
searchDef, _ := ParseDef(searchFile, nil)
d.rules.patterns = append(d.rules.patterns, searchDef.rules.patterns...)
d.rules.regions = append(d.rules.regions, searchDef.rules.regions...)
}
}
}
for _, r := range d.rules.regions {
resolveIncludesInRegion(files, r)
r.parent = nil
}
}
func resolveIncludesInRegion(files []*File, region *region) {
for _, lang := range region.rules.includes {
for _, searchFile := range files {
if lang == searchFile.FileType {
searchDef, _ := ParseDef(searchFile, nil)
region.rules.patterns = append(region.rules.patterns, searchDef.rules.patterns...)
region.rules.regions = append(region.rules.regions, searchDef.rules.regions...)
}
}
}
for _, r := range region.rules.regions {
resolveIncludesInRegion(files, r)
r.parent = region
}
}
func parseRules(input []interface{}, curRegion *region) (ru *rules, err error) {
defer func() {
if r := recover(); r != nil {
var ok bool
err, ok = r.(error)
if !ok {
err = fmt.Errorf("pkg: %v", r)
}
}
}()
ru = new(rules)
for _, v := range input {
rule := v.(map[interface{}]interface{})
for k, val := range rule {
group := k
switch object := val.(type) {
case string:
if object == "" {
return nil, fmt.Errorf("Empty rule %s", k)
}
if k == "include" {
ru.includes = append(ru.includes, object)
} else {
// Pattern
r, err := regexp.Compile(object)
if err != nil {
return nil, err
}
groupStr := group.(string)
if _, ok := Groups[groupStr]; !ok {
numGroups++
Groups[groupStr] = numGroups
}
groupNum := Groups[groupStr]
ru.patterns = append(ru.patterns, &pattern{groupNum, r})
}
case map[interface{}]interface{}:
// region
region, err := parseRegion(group.(string), object, curRegion)
if err != nil {
return nil, err
}
ru.regions = append(ru.regions, region)
default:
return nil, fmt.Errorf("Bad type %T", object)
}
}
}
return ru, nil
}
func parseRegion(group string, regionInfo map[interface{}]interface{}, prevRegion *region) (r *region, err error) {
defer func() {
if r := recover(); r != nil {
var ok bool
err, ok = r.(error)
if !ok {
err = fmt.Errorf("pkg: %v", r)
}
}
}()
r = new(region)
if _, ok := Groups[group]; !ok {
numGroups++
Groups[group] = numGroups
}
groupNum := Groups[group]
r.group = groupNum
r.parent = prevRegion
// start is mandatory
if start, ok := regionInfo["start"]; ok {
start := start.(string)
if start == "" {
return nil, fmt.Errorf("Empty start in %s", group)
}
r.start, err = regexp.Compile(start)
if err != nil {
return nil, err
}
} else {
return nil, fmt.Errorf("Missing start in %s", group)
}
// end is mandatory
if end, ok := regionInfo["end"]; ok {
end := end.(string)
if end == "" {
return nil, fmt.Errorf("Empty end in %s", group)
}
r.end, err = regexp.Compile(end)
if err != nil {
return nil, err
}
} else {
return nil, fmt.Errorf("Missing end in %s", group)
}
// skip is optional
if skip, ok := regionInfo["skip"]; ok {
skip := skip.(string)
if skip == "" {
return nil, fmt.Errorf("Empty skip in %s", group)
}
r.skip, err = regexp.Compile(skip)
if err != nil {
return nil, err
}
}
// limit-color is optional
if groupStr, ok := regionInfo["limit-group"]; ok {
groupStr := groupStr.(string)
if groupStr == "" {
return nil, fmt.Errorf("Empty limit-group in %s", group)
}
if _, ok := Groups[groupStr]; !ok {
numGroups++
Groups[groupStr] = numGroups
}
groupNum := Groups[groupStr]
r.limitGroup = groupNum
if err != nil {
return nil, err
}
} else {
r.limitGroup = r.group
}
r.rules, err = parseRules(regionInfo["rules"].([]interface{}), r)
if err != nil {
return nil, err
}
return r, nil
}
```
|
/content/code_sandbox/pkg/highlight/parser.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 3,070
|
```go
package highlight
import (
"unicode"
"unicode/utf8"
)
var minMark = rune(unicode.Mark.R16[0].Lo)
func isMark(r rune) bool {
// Fast path
if r < minMark {
return false
}
return unicode.In(r, unicode.Mark)
}
// DecodeCharacter returns the next character from an array of bytes
// A character is a rune along with any accompanying combining runes
func DecodeCharacter(b []byte) (rune, []rune, int) {
r, size := utf8.DecodeRune(b)
b = b[size:]
c, s := utf8.DecodeRune(b)
var combc []rune
for isMark(c) {
combc = append(combc, c)
size += s
b = b[s:]
c, s = utf8.DecodeRune(b)
}
return r, combc, size
}
// DecodeCharacterInString returns the next character from a string
// A character is a rune along with any accompanying combining runes
func DecodeCharacterInString(str string) (rune, []rune, int) {
r, size := utf8.DecodeRuneInString(str)
str = str[size:]
c, s := utf8.DecodeRuneInString(str)
var combc []rune
for isMark(c) {
combc = append(combc, c)
size += s
str = str[s:]
c, s = utf8.DecodeRuneInString(str)
}
return r, combc, size
}
// CharacterCount returns the number of characters in a byte array
// Similar to utf8.RuneCount but for unicode characters
func CharacterCount(b []byte) int {
s := 0
for len(b) > 0 {
r, size := utf8.DecodeRune(b)
if !isMark(r) {
s++
}
b = b[size:]
}
return s
}
// CharacterCount returns the number of characters in a string
// Similar to utf8.RuneCountInString but for unicode characters
func CharacterCountInString(str string) int {
s := 0
for _, r := range str {
if !isMark(r) {
s++
}
}
return s
}
```
|
/content/code_sandbox/pkg/highlight/unicode.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 485
|
```desktop
[Desktop Entry]
Name=Micro
GenericName=Text Editor
Comment=Edit text files in a terminal
Icon=micro
Type=Application
Categories=Utility;TextEditor;Development;
Keywords=text;editor;syntax;terminal;
Exec=micro %F
StartupNotify=false
Terminal=true
MimeType=text/plain;text/x-chdr;text/x-csrc;text/x-c++hdr;text/x-c++src;text/x-java;text/x-dsrc;text/x-pascal;text/x-perl;text/x-python;application/x-php;application/x-httpd-php3;application/x-httpd-php4;application/x-httpd-php5;application/xml;text/html;text/css;text/x-sql;text/x-diff;
```
|
/content/code_sandbox/assets/packaging/micro.desktop
|
desktop
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 143
|
```groff
.TH micro 1 "2020-02-10"
.SH NAME
micro \- A modern and intuitive terminal-based text editor
.SH SYNOPSIS
.B micro
.RB [OPTIONS]
[FILE]\&...
.SH DESCRIPTION
Micro is a terminal-based text editor that aims to be easy to use and intuitive, while also taking advantage of the full capabilities
of modern terminals. It comes as one single, batteries-included, static binary with no dependencies.
As the name indicates, micro aims to be somewhat of a successor to the nano editor by being easy to install and use in a pinch, but micro also aims to be
enjoyable to use full time, whether you work in the terminal because you prefer it (like me), or because you need to (over ssh).
Use Ctrl-q to quit, Ctrl-s to save, and Ctrl-g to open the in-editor help menu.
.SH OPTIONS
.PP
\-clean
.RS 4
Cleans the configuration directory
.RE
.PP
\-config-dir dir
.RS 4
Specify a custom location for the configuration directory
.RE
.PP
[FILE]:LINE:COL
.RS 4
Specify a line and column to start the cursor at when opening a buffer
.RE
.PP
\-options
.RS 4
Show all option help
.RE
.PP
\-debug
.RS 4
Enable debug mode (enables logging to ./log.txt)
.RE
.PP
\-version
.RS 4
Show the version number and information
.RE
Micro's plugins can be managed at the command line with the following commands.
.RS 4
.PP
\-plugin remove [PLUGIN]...
.RS 4
Remove plugin(s)
.RE
.PP
\-plugin update [PLUGIN]...
.RS 4
Update plugin(s) (if no argument is given, updates all plugins)
.RE
.PP
\-plugin search [PLUGIN]...
.RS 4
Search for a plugin
.RE
.PP
\-plugin list
.RS 4
List installed plugins
.RE
.PP
\-plugin available
.RS 4
List available plugins
.RE
.RE
Micro's options can also be set via command line arguments for quick
adjustments. For real configuration, please use the settings.json
file (see 'help options').
.RS 4
.PP
\-option value
.RS 4
Set `option` to `value` for this session
For example: `micro -syntax off file.c`
.RE
.SH CONFIGURATION
Micro uses $MICRO_CONFIG_HOME as the configuration directory.
If this environment variable is not set, it uses $XDG_CONFIG_HOME/micro instead.
If that environment variable is not set, it uses ~/.config/micro as the configuration directory.
In the documentation, we use ~/.config/micro to refer to the configuration directory
(even if it may in fact be somewhere else if you have set either of the above environment variables).
.SH NOTICE
This manpage is intended only to serve as a quick guide to the invocation of
micro and is not intended to replace the full documentation included with micro
which can be accessed from within micro. Micro tells you what key combination to
press to get help in the lower right.
.SH BUGS
A comprehensive list of bugs will not be listed in this manpage. See the Github
page at \fBpath_to_url for a list of known bugs
and to report any newly encountered bugs you may find. We strive to correct
bugs as swiftly as possible.
.SH COPYRIGHT
See \fBpath_to_url for details.
```
|
/content/code_sandbox/assets/packaging/micro.1
|
groff
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 755
|
```go
package highlight
import (
"regexp"
"strings"
)
func sliceStart(slc []byte, index int) []byte {
len := len(slc)
i := 0
totalSize := 0
for totalSize < len {
if i >= index {
return slc[totalSize:]
}
_, _, size := DecodeCharacter(slc[totalSize:])
totalSize += size
i++
}
return slc[totalSize:]
}
func sliceEnd(slc []byte, index int) []byte {
len := len(slc)
i := 0
totalSize := 0
for totalSize < len {
if i >= index {
return slc[:totalSize]
}
_, _, size := DecodeCharacter(slc[totalSize:])
totalSize += size
i++
}
return slc[:totalSize]
}
// RunePos returns the rune index of a given byte index
// This could cause problems if the byte index is between code points
func runePos(p int, str []byte) int {
if p < 0 {
return 0
}
if p >= len(str) {
return CharacterCount(str)
}
return CharacterCount(str[:p])
}
func combineLineMatch(src, dst LineMatch) LineMatch {
for k, v := range src {
if g, ok := dst[k]; ok {
if g == 0 {
dst[k] = v
}
} else {
dst[k] = v
}
}
return dst
}
// A State represents the region at the end of a line
type State *region
// LineStates is an interface for a buffer-like object which can also store the states and matches for every line
type LineStates interface {
LineBytes(n int) []byte
LinesNum() int
State(lineN int) State
SetState(lineN int, s State)
SetMatch(lineN int, m LineMatch)
Lock()
Unlock()
}
// A Highlighter contains the information needed to highlight a string
type Highlighter struct {
lastRegion *region
Def *Def
}
// NewHighlighter returns a new highlighter from the given syntax definition
func NewHighlighter(def *Def) *Highlighter {
h := new(Highlighter)
h.Def = def
return h
}
// LineMatch represents the syntax highlighting matches for one line. Each index where the coloring is changed is marked with that
// color's group (represented as one byte)
type LineMatch map[int]Group
func findIndex(regex *regexp.Regexp, skip *regexp.Regexp, str []byte) []int {
var strbytes []byte
if skip != nil {
strbytes = skip.ReplaceAllFunc(str, func(match []byte) []byte {
res := make([]byte, CharacterCount(match))
return res
})
} else {
strbytes = str
}
match := regex.FindIndex(strbytes)
if match == nil {
return nil
}
// return []int{match.Index, match.Index + match.Length}
return []int{runePos(match[0], str), runePos(match[1], str)}
}
func findAllIndex(regex *regexp.Regexp, str []byte) [][]int {
matches := regex.FindAllIndex(str, -1)
for i, m := range matches {
matches[i][0] = runePos(m[0], str)
matches[i][1] = runePos(m[1], str)
}
return matches
}
func (h *Highlighter) highlightRegion(highlights LineMatch, start int, canMatchEnd bool, lineNum int, line []byte, curRegion *region, statesOnly bool) LineMatch {
lineLen := CharacterCount(line)
if start == 0 {
if !statesOnly {
if _, ok := highlights[0]; !ok {
highlights[0] = curRegion.group
}
}
}
var firstRegion *region
firstLoc := []int{lineLen, 0}
searchNesting := true
endLoc := findIndex(curRegion.end, curRegion.skip, line)
if endLoc != nil {
if start == endLoc[0] {
searchNesting = false
} else {
firstLoc = endLoc
}
}
if searchNesting {
for _, r := range curRegion.rules.regions {
loc := findIndex(r.start, r.skip, line)
if loc != nil {
if loc[0] < firstLoc[0] {
firstLoc = loc
firstRegion = r
}
}
}
}
if firstRegion != nil && firstLoc[0] != lineLen {
if !statesOnly {
highlights[start+firstLoc[0]] = firstRegion.limitGroup
}
h.highlightEmptyRegion(highlights, start+firstLoc[1], canMatchEnd, lineNum, sliceStart(line, firstLoc[1]), statesOnly)
h.highlightRegion(highlights, start+firstLoc[1], canMatchEnd, lineNum, sliceStart(line, firstLoc[1]), firstRegion, statesOnly)
return highlights
}
if !statesOnly {
fullHighlights := make([]Group, lineLen)
for i := 0; i < len(fullHighlights); i++ {
fullHighlights[i] = curRegion.group
}
if searchNesting {
for _, p := range curRegion.rules.patterns {
if curRegion.group == curRegion.limitGroup || p.group == curRegion.limitGroup {
matches := findAllIndex(p.regex, line)
for _, m := range matches {
if ((endLoc == nil) || (m[0] < endLoc[0])) {
for i := m[0]; i < m[1]; i++ {
fullHighlights[i] = p.group
}
}
}
}
}
}
for i, h := range fullHighlights {
if i == 0 || h != fullHighlights[i-1] {
highlights[start+i] = h
}
}
}
loc := endLoc
if loc != nil {
if !statesOnly {
highlights[start+loc[0]] = curRegion.limitGroup
}
if curRegion.parent == nil {
if !statesOnly {
highlights[start+loc[1]] = 0
}
h.highlightEmptyRegion(highlights, start+loc[1], canMatchEnd, lineNum, sliceStart(line, loc[1]), statesOnly)
return highlights
}
if !statesOnly {
highlights[start+loc[1]] = curRegion.parent.group
}
h.highlightRegion(highlights, start+loc[1], canMatchEnd, lineNum, sliceStart(line, loc[1]), curRegion.parent, statesOnly)
return highlights
}
if canMatchEnd {
h.lastRegion = curRegion
}
return highlights
}
func (h *Highlighter) highlightEmptyRegion(highlights LineMatch, start int, canMatchEnd bool, lineNum int, line []byte, statesOnly bool) LineMatch {
lineLen := CharacterCount(line)
if lineLen == 0 {
if canMatchEnd {
h.lastRegion = nil
}
return highlights
}
var firstRegion *region
firstLoc := []int{lineLen, 0}
for _, r := range h.Def.rules.regions {
loc := findIndex(r.start, r.skip, line)
if loc != nil {
if loc[0] < firstLoc[0] {
firstLoc = loc
firstRegion = r
}
}
}
if firstRegion != nil && firstLoc[0] != lineLen {
if !statesOnly {
highlights[start+firstLoc[0]] = firstRegion.limitGroup
}
h.highlightEmptyRegion(highlights, start, false, lineNum, sliceEnd(line, firstLoc[0]), statesOnly)
h.highlightRegion(highlights, start+firstLoc[1], canMatchEnd, lineNum, sliceStart(line, firstLoc[1]), firstRegion, statesOnly)
return highlights
}
if statesOnly {
if canMatchEnd {
h.lastRegion = nil
}
return highlights
}
fullHighlights := make([]Group, len(line))
for _, p := range h.Def.rules.patterns {
matches := findAllIndex(p.regex, line)
for _, m := range matches {
for i := m[0]; i < m[1]; i++ {
fullHighlights[i] = p.group
}
}
}
for i, h := range fullHighlights {
if i == 0 || h != fullHighlights[i-1] {
// if _, ok := highlights[start+i]; !ok {
highlights[start+i] = h
// }
}
}
if canMatchEnd {
h.lastRegion = nil
}
return highlights
}
// HighlightString syntax highlights a string
// Use this function for simple syntax highlighting and use the other functions for
// more advanced syntax highlighting. They are optimized for quick rehighlighting of the same
// text with minor changes made
func (h *Highlighter) HighlightString(input string) []LineMatch {
lines := strings.Split(input, "\n")
var lineMatches []LineMatch
for i := 0; i < len(lines); i++ {
line := []byte(lines[i])
highlights := make(LineMatch)
if i == 0 || h.lastRegion == nil {
lineMatches = append(lineMatches, h.highlightEmptyRegion(highlights, 0, true, i, line, false))
} else {
lineMatches = append(lineMatches, h.highlightRegion(highlights, 0, true, i, line, h.lastRegion, false))
}
}
return lineMatches
}
// HighlightStates correctly sets all states for the buffer
func (h *Highlighter) HighlightStates(input LineStates) {
for i := 0; ; i++ {
input.Lock()
if i >= input.LinesNum() {
input.Unlock()
break
}
line := input.LineBytes(i)
// highlights := make(LineMatch)
if i == 0 || h.lastRegion == nil {
h.highlightEmptyRegion(nil, 0, true, i, line, true)
} else {
h.highlightRegion(nil, 0, true, i, line, h.lastRegion, true)
}
curState := h.lastRegion
input.SetState(i, curState)
input.Unlock()
}
}
// HighlightMatches sets the matches for each line from startline to endline
// It sets all other matches in the buffer to nil to conserve memory
// This assumes that all the states are set correctly
func (h *Highlighter) HighlightMatches(input LineStates, startline, endline int) {
for i := startline; i <= endline; i++ {
input.Lock()
if i >= input.LinesNum() {
input.Unlock()
break
}
line := input.LineBytes(i)
highlights := make(LineMatch)
var match LineMatch
if i == 0 || input.State(i-1) == nil {
match = h.highlightEmptyRegion(highlights, 0, true, i, line, false)
} else {
match = h.highlightRegion(highlights, 0, true, i, line, input.State(i-1), false)
}
input.SetMatch(i, match)
input.Unlock()
}
}
// ReHighlightStates will scan down from `startline` and set the appropriate end of line state
// for each line until it comes across a line whose state does not change
// returns the number of the final line
func (h *Highlighter) ReHighlightStates(input LineStates, startline int) int {
// lines := input.LineData()
h.lastRegion = nil
if startline > 0 {
input.Lock()
if startline-1 < input.LinesNum() {
h.lastRegion = input.State(startline - 1)
}
input.Unlock()
}
for i := startline; ; i++ {
input.Lock()
if i >= input.LinesNum() {
input.Unlock()
break
}
line := input.LineBytes(i)
// highlights := make(LineMatch)
// var match LineMatch
if i == 0 || h.lastRegion == nil {
h.highlightEmptyRegion(nil, 0, true, i, line, true)
} else {
h.highlightRegion(nil, 0, true, i, line, h.lastRegion, true)
}
curState := h.lastRegion
lastState := input.State(i)
input.SetState(i, curState)
input.Unlock()
if curState == lastState {
return i
}
}
return input.LinesNum() - 1
}
// ReHighlightLine will rehighlight the state and match for a single line
func (h *Highlighter) ReHighlightLine(input LineStates, lineN int) {
input.Lock()
defer input.Unlock()
line := input.LineBytes(lineN)
highlights := make(LineMatch)
h.lastRegion = nil
if lineN > 0 {
h.lastRegion = input.State(lineN - 1)
}
var match LineMatch
if lineN == 0 || h.lastRegion == nil {
match = h.highlightEmptyRegion(highlights, 0, true, lineN, line, false)
} else {
match = h.highlightRegion(highlights, 0, true, lineN, line, h.lastRegion, false)
}
curState := h.lastRegion
input.SetMatch(lineN, match)
input.SetState(lineN, curState)
}
```
|
/content/code_sandbox/pkg/highlight/highlighter.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 2,999
|
```unknown
#!/bin/sh
set -e
if [ "$1" != "upgrade" ]; then
update-alternatives --remove editor /usr/bin/micro
fi
```
|
/content/code_sandbox/assets/packaging/deb/micro.prerm
|
unknown
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 37
|
```go
package main
import (
"bufio"
"encoding/gob"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"sort"
"strings"
"github.com/zyedidia/micro/v2/internal/buffer"
"github.com/zyedidia/micro/v2/internal/config"
)
func shouldContinue() bool {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Continue [Y/n]: ")
text, err := reader.ReadString('\n')
if err != nil {
fmt.Println(err)
return false
}
text = strings.TrimRight(text, "\r\n")
return len(text) == 0 || strings.ToLower(text)[0] == 'y'
}
// CleanConfig performs cleanup in the user's configuration directory
func CleanConfig() {
fmt.Println("Cleaning your configuration directory at", config.ConfigDir)
fmt.Printf("Please consider backing up %s before continuing\n", config.ConfigDir)
if !shouldContinue() {
fmt.Println("Stopping early")
return
}
fmt.Println("Cleaning default settings")
config.WriteSettings(filepath.Join(config.ConfigDir, "settings.json"))
// detect unused options
var unusedOptions []string
defaultSettings := config.DefaultAllSettings()
for k := range config.GlobalSettings {
if _, ok := defaultSettings[k]; !ok {
valid := false
for _, p := range config.Plugins {
if strings.HasPrefix(k, p.Name+".") || k == p.Name {
valid = true
}
}
if !valid {
unusedOptions = append(unusedOptions, k)
}
}
}
if len(unusedOptions) > 0 {
fmt.Println("The following options are unused:")
sort.Strings(unusedOptions)
for _, s := range unusedOptions {
fmt.Printf("%s (value: %v)\n", s, config.GlobalSettings[s])
}
fmt.Printf("These options will be removed from %s\n", filepath.Join(config.ConfigDir, "settings.json"))
if shouldContinue() {
for _, s := range unusedOptions {
delete(config.GlobalSettings, s)
}
err := config.OverwriteSettings(filepath.Join(config.ConfigDir, "settings.json"))
if err != nil {
fmt.Println("Error writing settings.json file: " + err.Error())
}
fmt.Println("Removed unused options")
fmt.Print("\n\n")
}
}
// detect incorrectly formatted buffer/ files
files, err := ioutil.ReadDir(filepath.Join(config.ConfigDir, "buffers"))
if err == nil {
var badFiles []string
var buffer buffer.SerializedBuffer
for _, f := range files {
fname := filepath.Join(config.ConfigDir, "buffers", f.Name())
file, e := os.Open(fname)
if e == nil {
decoder := gob.NewDecoder(file)
err = decoder.Decode(&buffer)
if err != nil && f.Name() != "history" {
badFiles = append(badFiles, fname)
}
file.Close()
}
}
if len(badFiles) > 0 {
fmt.Printf("Detected %d files with an invalid format in %s\n", len(badFiles), filepath.Join(config.ConfigDir, "buffers"))
fmt.Println("These files store cursor and undo history.")
fmt.Printf("Removing badly formatted files in %s\n", filepath.Join(config.ConfigDir, "buffers"))
if shouldContinue() {
removed := 0
for _, f := range badFiles {
err := os.Remove(f)
if err != nil {
fmt.Println(err)
continue
}
removed++
}
if removed == 0 {
fmt.Println("Failed to remove files")
} else {
fmt.Printf("Removed %d badly formatted files\n", removed)
}
fmt.Print("\n\n")
}
}
}
// detect plugins/ directory
plugins := filepath.Join(config.ConfigDir, "plugins")
if stat, err := os.Stat(plugins); err == nil && stat.IsDir() {
fmt.Printf("Found directory %s\n", plugins)
fmt.Printf("Plugins should now be stored in %s\n", filepath.Join(config.ConfigDir, "plug"))
fmt.Printf("Removing %s\n", plugins)
if shouldContinue() {
os.RemoveAll(plugins)
}
fmt.Print("\n\n")
}
fmt.Println("Done cleaning")
}
```
|
/content/code_sandbox/cmd/micro/clean.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 946
|
```unknown
#!/bin/sh
set -e
if [ "$1" = "configure" ] || [ "$1" = "abort-upgrade" ]; then
update-alternatives --install /usr/bin/editor editor /usr/bin/micro 40 \
--slave /usr/share/man/man1/editor.1 editor.1 \
/usr/share/man/man1/micro.1
fi
```
|
/content/code_sandbox/assets/packaging/deb/micro.postinst
|
unknown
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 83
|
```go
package main
import (
"log"
"os"
"github.com/zyedidia/micro/v2/internal/util"
)
// NullWriter simply sends writes into the void
type NullWriter struct{}
// Write is empty
func (NullWriter) Write(data []byte) (n int, err error) {
return 0, nil
}
// InitLog sets up the debug log system for micro if it has been enabled by compile-time variables
func InitLog() {
if util.Debug == "ON" {
f, err := os.OpenFile("log.txt", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)
if err != nil {
log.Fatalf("error opening file: %v", err)
}
log.SetOutput(f)
log.Println("Micro started")
} else {
log.SetOutput(NullWriter{})
}
}
```
|
/content/code_sandbox/cmd/micro/debug.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 184
|
```go
package main
import (
"log"
"time"
lua "github.com/yuin/gopher-lua"
luar "layeh.com/gopher-luar"
"github.com/zyedidia/micro/v2/internal/action"
"github.com/zyedidia/micro/v2/internal/buffer"
"github.com/zyedidia/micro/v2/internal/config"
"github.com/zyedidia/micro/v2/internal/display"
ulua "github.com/zyedidia/micro/v2/internal/lua"
"github.com/zyedidia/micro/v2/internal/screen"
"github.com/zyedidia/micro/v2/internal/shell"
"github.com/zyedidia/micro/v2/internal/util"
)
func init() {
ulua.L = lua.NewState()
ulua.L.SetGlobal("import", luar.New(ulua.L, LuaImport))
}
// LuaImport is meant to be called from lua by a plugin and will import the given micro package
func LuaImport(pkg string) *lua.LTable {
switch pkg {
case "micro":
return luaImportMicro()
case "micro/shell":
return luaImportMicroShell()
case "micro/buffer":
return luaImportMicroBuffer()
case "micro/config":
return luaImportMicroConfig()
case "micro/util":
return luaImportMicroUtil()
default:
return ulua.Import(pkg)
}
}
func luaImportMicro() *lua.LTable {
pkg := ulua.L.NewTable()
ulua.L.SetField(pkg, "TermMessage", luar.New(ulua.L, screen.TermMessage))
ulua.L.SetField(pkg, "TermError", luar.New(ulua.L, screen.TermError))
ulua.L.SetField(pkg, "InfoBar", luar.New(ulua.L, action.GetInfoBar))
ulua.L.SetField(pkg, "Log", luar.New(ulua.L, log.Println))
ulua.L.SetField(pkg, "SetStatusInfoFn", luar.New(ulua.L, display.SetStatusInfoFnLua))
ulua.L.SetField(pkg, "CurPane", luar.New(ulua.L, func() *action.BufPane {
return action.MainTab().CurPane()
}))
ulua.L.SetField(pkg, "CurTab", luar.New(ulua.L, action.MainTab))
ulua.L.SetField(pkg, "Tabs", luar.New(ulua.L, func() *action.TabList {
return action.Tabs
}))
ulua.L.SetField(pkg, "After", luar.New(ulua.L, func(t time.Duration, f func()) {
time.AfterFunc(t, func() {
timerChan <- f
})
}))
return pkg
}
func luaImportMicroConfig() *lua.LTable {
pkg := ulua.L.NewTable()
ulua.L.SetField(pkg, "MakeCommand", luar.New(ulua.L, action.MakeCommand))
ulua.L.SetField(pkg, "FileComplete", luar.New(ulua.L, buffer.FileComplete))
ulua.L.SetField(pkg, "HelpComplete", luar.New(ulua.L, action.HelpComplete))
ulua.L.SetField(pkg, "OptionComplete", luar.New(ulua.L, action.OptionComplete))
ulua.L.SetField(pkg, "OptionValueComplete", luar.New(ulua.L, action.OptionValueComplete))
ulua.L.SetField(pkg, "NoComplete", luar.New(ulua.L, nil))
ulua.L.SetField(pkg, "TryBindKey", luar.New(ulua.L, action.TryBindKey))
ulua.L.SetField(pkg, "Reload", luar.New(ulua.L, action.ReloadConfig))
ulua.L.SetField(pkg, "AddRuntimeFileFromMemory", luar.New(ulua.L, config.PluginAddRuntimeFileFromMemory))
ulua.L.SetField(pkg, "AddRuntimeFilesFromDirectory", luar.New(ulua.L, config.PluginAddRuntimeFilesFromDirectory))
ulua.L.SetField(pkg, "AddRuntimeFile", luar.New(ulua.L, config.PluginAddRuntimeFile))
ulua.L.SetField(pkg, "ListRuntimeFiles", luar.New(ulua.L, config.PluginListRuntimeFiles))
ulua.L.SetField(pkg, "ReadRuntimeFile", luar.New(ulua.L, config.PluginReadRuntimeFile))
ulua.L.SetField(pkg, "NewRTFiletype", luar.New(ulua.L, config.NewRTFiletype))
ulua.L.SetField(pkg, "RTColorscheme", luar.New(ulua.L, config.RTColorscheme))
ulua.L.SetField(pkg, "RTSyntax", luar.New(ulua.L, config.RTSyntax))
ulua.L.SetField(pkg, "RTHelp", luar.New(ulua.L, config.RTHelp))
ulua.L.SetField(pkg, "RTPlugin", luar.New(ulua.L, config.RTPlugin))
ulua.L.SetField(pkg, "RegisterCommonOption", luar.New(ulua.L, config.RegisterCommonOptionPlug))
ulua.L.SetField(pkg, "RegisterGlobalOption", luar.New(ulua.L, config.RegisterGlobalOptionPlug))
ulua.L.SetField(pkg, "GetGlobalOption", luar.New(ulua.L, config.GetGlobalOption))
ulua.L.SetField(pkg, "SetGlobalOption", luar.New(ulua.L, action.SetGlobalOption))
ulua.L.SetField(pkg, "SetGlobalOptionNative", luar.New(ulua.L, action.SetGlobalOptionNative))
ulua.L.SetField(pkg, "ConfigDir", luar.New(ulua.L, config.ConfigDir))
return pkg
}
func luaImportMicroShell() *lua.LTable {
pkg := ulua.L.NewTable()
ulua.L.SetField(pkg, "ExecCommand", luar.New(ulua.L, shell.ExecCommand))
ulua.L.SetField(pkg, "RunCommand", luar.New(ulua.L, shell.RunCommand))
ulua.L.SetField(pkg, "RunBackgroundShell", luar.New(ulua.L, shell.RunBackgroundShell))
ulua.L.SetField(pkg, "RunInteractiveShell", luar.New(ulua.L, shell.RunInteractiveShell))
ulua.L.SetField(pkg, "JobStart", luar.New(ulua.L, shell.JobStart))
ulua.L.SetField(pkg, "JobSpawn", luar.New(ulua.L, shell.JobSpawn))
ulua.L.SetField(pkg, "JobStop", luar.New(ulua.L, shell.JobStop))
ulua.L.SetField(pkg, "JobSend", luar.New(ulua.L, shell.JobSend))
ulua.L.SetField(pkg, "RunTermEmulator", luar.New(ulua.L, action.RunTermEmulator))
ulua.L.SetField(pkg, "TermEmuSupported", luar.New(ulua.L, action.TermEmuSupported))
return pkg
}
func luaImportMicroBuffer() *lua.LTable {
pkg := ulua.L.NewTable()
ulua.L.SetField(pkg, "NewMessage", luar.New(ulua.L, buffer.NewMessage))
ulua.L.SetField(pkg, "NewMessageAtLine", luar.New(ulua.L, buffer.NewMessageAtLine))
ulua.L.SetField(pkg, "MTInfo", luar.New(ulua.L, buffer.MTInfo))
ulua.L.SetField(pkg, "MTWarning", luar.New(ulua.L, buffer.MTWarning))
ulua.L.SetField(pkg, "MTError", luar.New(ulua.L, buffer.MTError))
ulua.L.SetField(pkg, "Loc", luar.New(ulua.L, func(x, y int) buffer.Loc {
return buffer.Loc{x, y}
}))
ulua.L.SetField(pkg, "SLoc", luar.New(ulua.L, func(line, row int) display.SLoc {
return display.SLoc{line, row}
}))
ulua.L.SetField(pkg, "BTDefault", luar.New(ulua.L, buffer.BTDefault.Kind))
ulua.L.SetField(pkg, "BTHelp", luar.New(ulua.L, buffer.BTHelp.Kind))
ulua.L.SetField(pkg, "BTLog", luar.New(ulua.L, buffer.BTLog.Kind))
ulua.L.SetField(pkg, "BTScratch", luar.New(ulua.L, buffer.BTScratch.Kind))
ulua.L.SetField(pkg, "BTRaw", luar.New(ulua.L, buffer.BTRaw.Kind))
ulua.L.SetField(pkg, "BTInfo", luar.New(ulua.L, buffer.BTInfo.Kind))
ulua.L.SetField(pkg, "NewBuffer", luar.New(ulua.L, func(text, path string) *buffer.Buffer {
return buffer.NewBufferFromString(text, path, buffer.BTDefault)
}))
ulua.L.SetField(pkg, "NewBufferFromFile", luar.New(ulua.L, func(path string) (*buffer.Buffer, error) {
return buffer.NewBufferFromFile(path, buffer.BTDefault)
}))
ulua.L.SetField(pkg, "ByteOffset", luar.New(ulua.L, buffer.ByteOffset))
ulua.L.SetField(pkg, "Log", luar.New(ulua.L, buffer.WriteLog))
ulua.L.SetField(pkg, "LogBuf", luar.New(ulua.L, buffer.GetLogBuf))
return pkg
}
func luaImportMicroUtil() *lua.LTable {
pkg := ulua.L.NewTable()
ulua.L.SetField(pkg, "RuneAt", luar.New(ulua.L, util.LuaRuneAt))
ulua.L.SetField(pkg, "GetLeadingWhitespace", luar.New(ulua.L, util.LuaGetLeadingWhitespace))
ulua.L.SetField(pkg, "IsWordChar", luar.New(ulua.L, util.LuaIsWordChar))
ulua.L.SetField(pkg, "String", luar.New(ulua.L, util.String))
ulua.L.SetField(pkg, "Unzip", luar.New(ulua.L, util.Unzip))
ulua.L.SetField(pkg, "Version", luar.New(ulua.L, util.Version))
ulua.L.SetField(pkg, "SemVersion", luar.New(ulua.L, util.SemVersion))
ulua.L.SetField(pkg, "HttpRequest", luar.New(ulua.L, util.HttpRequest))
ulua.L.SetField(pkg, "CharacterCountInString", luar.New(ulua.L, util.CharacterCountInString))
ulua.L.SetField(pkg, "RuneStr", luar.New(ulua.L, func(r rune) string {
return string(r)
}))
return pkg
}
```
|
/content/code_sandbox/cmd/micro/initlua.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 2,357
|
```go
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"testing"
"github.com/go-errors/errors"
"github.com/stretchr/testify/assert"
"github.com/zyedidia/micro/v2/internal/action"
"github.com/zyedidia/micro/v2/internal/buffer"
"github.com/zyedidia/micro/v2/internal/config"
"github.com/zyedidia/micro/v2/internal/screen"
"github.com/zyedidia/tcell/v2"
)
var tempDir string
var sim tcell.SimulationScreen
func init() {
screen.Events = make(chan tcell.Event, 8)
}
func startup(args []string) (tcell.SimulationScreen, error) {
var err error
tempDir, err = ioutil.TempDir("", "micro_test")
if err != nil {
return nil, err
}
err = config.InitConfigDir(tempDir)
if err != nil {
return nil, err
}
config.InitRuntimeFiles(true)
config.InitPlugins()
err = config.ReadSettings()
if err != nil {
return nil, err
}
err = config.InitGlobalSettings()
if err != nil {
return nil, err
}
s, err := screen.InitSimScreen()
if err != nil {
return nil, err
}
defer func() {
if err := recover(); err != nil {
screen.Screen.Fini()
fmt.Println("Micro encountered an error:", err)
// backup all open buffers
for _, b := range buffer.OpenBuffers {
b.Backup()
}
// Print the stack trace too
log.Fatalf(errors.Wrap(err, 2).ErrorStack())
}
}()
err = config.LoadAllPlugins()
if err != nil {
screen.TermMessage(err)
}
action.InitBindings()
action.InitCommands()
err = config.InitColorscheme()
if err != nil {
return nil, err
}
b := LoadInput(args)
if len(b) == 0 {
return nil, errors.New("No buffers opened")
}
action.InitTabs(b)
action.InitGlobals()
err = config.RunPluginFn("init")
if err != nil {
return nil, err
}
s.InjectResize()
handleEvent()
return s, nil
}
func cleanup() {
os.RemoveAll(tempDir)
}
func handleEvent() {
screen.Lock()
e := screen.Screen.PollEvent()
screen.Unlock()
if e != nil {
screen.Events <- e
}
for len(screen.DrawChan()) > 0 || len(screen.Events) > 0 {
DoEvent()
}
}
func injectKey(key tcell.Key, r rune, mod tcell.ModMask) {
sim.InjectKey(key, r, mod)
handleEvent()
}
func injectMouse(x, y int, buttons tcell.ButtonMask, mod tcell.ModMask) {
sim.InjectMouse(x, y, buttons, mod)
handleEvent()
}
func injectString(str string) {
// the tcell simulation screen event channel can only handle
// 10 events at once, so we need to divide up the key events
// into chunks of 10 and handle the 10 events before sending
// another chunk of events
iters := len(str) / 10
extra := len(str) % 10
for i := 0; i < iters; i++ {
s := i * 10
e := i*10 + 10
sim.InjectKeyBytes([]byte(str[s:e]))
for i := 0; i < 10; i++ {
handleEvent()
}
}
sim.InjectKeyBytes([]byte(str[len(str)-extra:]))
for i := 0; i < extra; i++ {
handleEvent()
}
}
func openFile(file string) {
injectKey(tcell.KeyCtrlE, rune(tcell.KeyCtrlE), tcell.ModCtrl)
injectString(fmt.Sprintf("open %s", file))
injectKey(tcell.KeyEnter, rune(tcell.KeyEnter), tcell.ModNone)
}
func findBuffer(file string) *buffer.Buffer {
var buf *buffer.Buffer
for _, b := range buffer.OpenBuffers {
if b.Path == file {
buf = b
}
}
return buf
}
func createTestFile(name string, content string) (string, error) {
testf, err := ioutil.TempFile("", name)
if err != nil {
return "", err
}
if _, err := testf.Write([]byte(content)); err != nil {
return "", err
}
if err := testf.Close(); err != nil {
return "", err
}
return testf.Name(), nil
}
func TestMain(m *testing.M) {
var err error
sim, err = startup([]string{})
if err != nil {
log.Fatalln(err)
}
retval := m.Run()
cleanup()
os.Exit(retval)
}
func TestSimpleEdit(t *testing.T) {
file, err := createTestFile("micro_simple_edit_test", "base content")
if err != nil {
t.Error(err)
return
}
defer os.Remove(file)
openFile(file)
if findBuffer(file) == nil {
t.Errorf("Could not find buffer %s", file)
return
}
injectKey(tcell.KeyEnter, rune(tcell.KeyEnter), tcell.ModNone)
injectKey(tcell.KeyUp, 0, tcell.ModNone)
injectString("first line")
// test both kinds of backspace
for i := 0; i < len("ne"); i++ {
injectKey(tcell.KeyBackspace, rune(tcell.KeyBackspace), tcell.ModNone)
}
for i := 0; i < len(" li"); i++ {
injectKey(tcell.KeyBackspace2, rune(tcell.KeyBackspace2), tcell.ModNone)
}
injectString("foobar")
injectKey(tcell.KeyCtrlS, rune(tcell.KeyCtrlS), tcell.ModCtrl)
data, err := ioutil.ReadFile(file)
if err != nil {
t.Error(err)
return
}
assert.Equal(t, "firstfoobar\nbase content\n", string(data))
}
func TestMouse(t *testing.T) {
file, err := createTestFile("micro_mouse_test", "base content")
if err != nil {
t.Error(err)
return
}
defer os.Remove(file)
openFile(file)
if findBuffer(file) == nil {
t.Errorf("Could not find buffer %s", file)
return
}
// buffer:
// base content
// the selections need to happen at different locations to avoid a double click
injectMouse(3, 0, tcell.Button1, tcell.ModNone)
injectKey(tcell.KeyLeft, 0, tcell.ModNone)
injectMouse(0, 0, tcell.ButtonNone, tcell.ModNone)
injectString("secondline")
// buffer:
// secondlinebase content
injectKey(tcell.KeyEnter, rune(tcell.KeyEnter), tcell.ModNone)
// buffer:
// secondline
// base content
injectMouse(2, 0, tcell.Button1, tcell.ModNone)
injectMouse(0, 0, tcell.ButtonNone, tcell.ModNone)
injectKey(tcell.KeyEnter, rune(tcell.KeyEnter), tcell.ModNone)
// buffer:
//
// secondline
// base content
injectKey(tcell.KeyUp, 0, tcell.ModNone)
injectString("firstline")
// buffer:
// firstline
// secondline
// base content
injectKey(tcell.KeyCtrlS, rune(tcell.KeyCtrlS), tcell.ModCtrl)
data, err := ioutil.ReadFile(file)
if err != nil {
t.Error(err)
return
}
assert.Equal(t, "firstline\nsecondline\nbase content\n", string(data))
}
var srTestStart = `foo
foo
foofoofoo
Ernlee foo elen
`
var srTest2 = `test_string
test_string
test_stringtest_stringtest_string
Ernlee test_string elen
`
var srTest3 = `test_foo
test_string
test_footest_stringtest_foo
Ernlee test_string elen
`
func TestSearchAndReplace(t *testing.T) {
file, err := createTestFile("micro_search_replace_test", srTestStart)
if err != nil {
t.Error(err)
return
}
defer os.Remove(file)
openFile(file)
if findBuffer(file) == nil {
t.Errorf("Could not find buffer %s", file)
return
}
injectKey(tcell.KeyCtrlE, rune(tcell.KeyCtrlE), tcell.ModCtrl)
injectString(fmt.Sprintf("replaceall %s %s", "foo", "test_string"))
injectKey(tcell.KeyEnter, rune(tcell.KeyEnter), tcell.ModNone)
injectKey(tcell.KeyCtrlS, rune(tcell.KeyCtrlS), tcell.ModCtrl)
data, err := ioutil.ReadFile(file)
if err != nil {
t.Error(err)
return
}
assert.Equal(t, srTest2, string(data))
injectKey(tcell.KeyCtrlE, rune(tcell.KeyCtrlE), tcell.ModCtrl)
injectString(fmt.Sprintf("replace %s %s", "string", "foo"))
injectKey(tcell.KeyEnter, rune(tcell.KeyEnter), tcell.ModNone)
injectString("ynyny")
injectKey(tcell.KeyEscape, 0, tcell.ModNone)
injectKey(tcell.KeyCtrlS, rune(tcell.KeyCtrlS), tcell.ModCtrl)
data, err = ioutil.ReadFile(file)
if err != nil {
t.Error(err)
return
}
assert.Equal(t, srTest3, string(data))
}
func TestMultiCursor(t *testing.T) {
// TODO
}
func TestSettingsPersistence(t *testing.T) {
// TODO
}
// more tests (rendering, tabs, plugins)?
```
|
/content/code_sandbox/cmd/micro/micro_test.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 2,148
|
```go
package action
import (
"bytes"
"errors"
"fmt"
"strings"
"github.com/zyedidia/tcell/v2"
)
type Event interface {
Name() string
}
// RawEvent is simply an escape code
// We allow users to directly bind escape codes
// to get around some of a limitations of terminals
type RawEvent struct {
esc string
}
func (r RawEvent) Name() string {
return r.esc
}
// KeyEvent is a key event containing a key code,
// some possible modifiers (alt, ctrl, etc...) and
// a rune if it was simply a character press
// Note: to be compatible with tcell events,
// for ctrl keys r=code
type KeyEvent struct {
code tcell.Key
mod tcell.ModMask
r rune
any bool
}
func metaToAlt(mod tcell.ModMask) tcell.ModMask {
if mod&tcell.ModMeta != 0 {
mod &= ^tcell.ModMeta
mod |= tcell.ModAlt
}
return mod
}
func keyEvent(e *tcell.EventKey) KeyEvent {
ke := KeyEvent{
code: e.Key(),
mod: metaToAlt(e.Modifiers()),
}
if e.Key() == tcell.KeyRune {
ke.r = e.Rune()
}
return ke
}
func (k KeyEvent) Name() string {
if k.any {
return "<any>"
}
s := ""
m := []string{}
if k.mod&tcell.ModShift != 0 {
m = append(m, "Shift")
}
if k.mod&tcell.ModAlt != 0 {
m = append(m, "Alt")
}
if k.mod&tcell.ModMeta != 0 {
m = append(m, "Meta")
}
if k.mod&tcell.ModCtrl != 0 {
m = append(m, "Ctrl")
}
ok := false
if s, ok = tcell.KeyNames[k.code]; !ok {
if k.code == tcell.KeyRune {
s = string(k.r)
} else {
s = fmt.Sprintf("Key[%d]", k.code)
}
}
if len(m) != 0 {
if k.mod&tcell.ModCtrl != 0 && strings.HasPrefix(s, "Ctrl-") {
s = s[5:]
if len(s) == 1 {
s = strings.ToLower(s)
}
}
return fmt.Sprintf("%s-%s", strings.Join(m, "-"), s)
}
return s
}
// A KeySequence defines a list of consecutive
// events. All events in the sequence must be KeyEvents
// or MouseEvents.
type KeySequenceEvent struct {
keys []Event
}
func (k KeySequenceEvent) Name() string {
buf := bytes.Buffer{}
for _, e := range k.keys {
buf.WriteByte('<')
buf.WriteString(e.Name())
buf.WriteByte('>')
}
return buf.String()
}
type MouseState int
const (
MousePress = iota
MouseDrag
MouseRelease
)
// MouseEvent is a mouse event with a mouse button and
// any possible key modifiers
type MouseEvent struct {
btn tcell.ButtonMask
mod tcell.ModMask
state MouseState
}
func (m MouseEvent) Name() string {
mod := ""
if m.mod&tcell.ModShift != 0 {
mod = "Shift-"
}
if m.mod&tcell.ModAlt != 0 {
mod = "Alt-"
}
if m.mod&tcell.ModMeta != 0 {
mod = "Meta-"
}
if m.mod&tcell.ModCtrl != 0 {
mod = "Ctrl-"
}
state := ""
switch m.state {
case MouseDrag:
state = "Drag"
case MouseRelease:
state = "Release"
}
for k, v := range mouseEvents {
if v == m.btn {
return fmt.Sprintf("%s%s%s", mod, k, state)
}
}
return ""
}
// ConstructEvent takes a tcell event and returns a micro
// event. Note that tcell events can't express certain
// micro events such as key sequences. This function is
// mostly used for debugging/raw panes or constructing
// intermediate micro events while parsing a sequence.
func ConstructEvent(event tcell.Event) (Event, error) {
switch e := event.(type) {
case *tcell.EventKey:
return keyEvent(e), nil
case *tcell.EventRaw:
return RawEvent{
esc: e.EscSeq(),
}, nil
case *tcell.EventMouse:
return MouseEvent{
btn: e.Buttons(),
mod: metaToAlt(e.Modifiers()),
}, nil
}
return nil, errors.New("No micro event equivalent")
}
// A Handler will take a tcell event and execute it
// appropriately
type Handler interface {
HandleEvent(tcell.Event)
HandleCommand(string)
}
```
|
/content/code_sandbox/internal/action/events.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 1,050
|
```go
package main
import (
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"os/signal"
"regexp"
"runtime"
"runtime/pprof"
"sort"
"strconv"
"syscall"
"time"
"github.com/go-errors/errors"
isatty "github.com/mattn/go-isatty"
lua "github.com/yuin/gopher-lua"
"github.com/zyedidia/micro/v2/internal/action"
"github.com/zyedidia/micro/v2/internal/buffer"
"github.com/zyedidia/micro/v2/internal/clipboard"
"github.com/zyedidia/micro/v2/internal/config"
"github.com/zyedidia/micro/v2/internal/screen"
"github.com/zyedidia/micro/v2/internal/shell"
"github.com/zyedidia/micro/v2/internal/util"
"github.com/zyedidia/tcell/v2"
)
var (
// Command line flags
flagVersion = flag.Bool("version", false, "Show the version number and information")
flagConfigDir = flag.String("config-dir", "", "Specify a custom location for the configuration directory")
flagOptions = flag.Bool("options", false, "Show all option help")
flagDebug = flag.Bool("debug", false, "Enable debug mode (prints debug info to ./log.txt)")
flagProfile = flag.Bool("profile", false, "Enable CPU profiling (writes profile info to ./micro.prof)")
flagPlugin = flag.String("plugin", "", "Plugin command")
flagClean = flag.Bool("clean", false, "Clean configuration directory")
optionFlags map[string]*string
sighup chan os.Signal
timerChan chan func()
)
func InitFlags() {
flag.Usage = func() {
fmt.Println("Usage: micro [OPTIONS] [FILE]...")
fmt.Println("-clean")
fmt.Println(" \tCleans the configuration directory")
fmt.Println("-config-dir dir")
fmt.Println(" \tSpecify a custom location for the configuration directory")
fmt.Println("[FILE]:LINE:COL (if the `parsecursor` option is enabled)")
fmt.Println("+LINE:COL")
fmt.Println(" \tSpecify a line and column to start the cursor at when opening a buffer")
fmt.Println("-options")
fmt.Println(" \tShow all option help")
fmt.Println("-debug")
fmt.Println(" \tEnable debug mode (enables logging to ./log.txt)")
fmt.Println("-profile")
fmt.Println(" \tEnable CPU profiling (writes profile info to ./micro.prof")
fmt.Println(" \tso it can be analyzed later with \"go tool pprof micro.prof\")")
fmt.Println("-version")
fmt.Println(" \tShow the version number and information")
fmt.Print("\nMicro's plugins can be managed at the command line with the following commands.\n")
fmt.Println("-plugin install [PLUGIN]...")
fmt.Println(" \tInstall plugin(s)")
fmt.Println("-plugin remove [PLUGIN]...")
fmt.Println(" \tRemove plugin(s)")
fmt.Println("-plugin update [PLUGIN]...")
fmt.Println(" \tUpdate plugin(s) (if no argument is given, updates all plugins)")
fmt.Println("-plugin search [PLUGIN]...")
fmt.Println(" \tSearch for a plugin")
fmt.Println("-plugin list")
fmt.Println(" \tList installed plugins")
fmt.Println("-plugin available")
fmt.Println(" \tList available plugins")
fmt.Print("\nMicro's options can also be set via command line arguments for quick\nadjustments. For real configuration, please use the settings.json\nfile (see 'help options').\n\n")
fmt.Println("-option value")
fmt.Println(" \tSet `option` to `value` for this session")
fmt.Println(" \tFor example: `micro -syntax off file.c`")
fmt.Println("\nUse `micro -options` to see the full list of configuration options")
}
optionFlags = make(map[string]*string)
for k, v := range config.DefaultAllSettings() {
optionFlags[k] = flag.String(k, "", fmt.Sprintf("The %s option. Default value: '%v'.", k, v))
}
flag.Parse()
if *flagVersion {
// If -version was passed
fmt.Println("Version:", util.Version)
fmt.Println("Commit hash:", util.CommitHash)
fmt.Println("Compiled on", util.CompileDate)
os.Exit(0)
}
if *flagOptions {
// If -options was passed
var keys []string
m := config.DefaultAllSettings()
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
v := m[k]
fmt.Printf("-%s value\n", k)
fmt.Printf(" \tDefault value: '%v'\n", v)
}
os.Exit(0)
}
if util.Debug == "OFF" && *flagDebug {
util.Debug = "ON"
}
}
// DoPluginFlags parses and executes any flags that require LoadAllPlugins (-plugin and -clean)
func DoPluginFlags() {
if *flagClean || *flagPlugin != "" {
config.LoadAllPlugins()
if *flagPlugin != "" {
args := flag.Args()
config.PluginCommand(os.Stdout, *flagPlugin, args)
} else if *flagClean {
CleanConfig()
}
os.Exit(0)
}
}
// LoadInput determines which files should be loaded into buffers
// based on the input stored in flag.Args()
func LoadInput(args []string) []*buffer.Buffer {
// There are a number of ways micro should start given its input
// 1. If it is given a files in flag.Args(), it should open those
// 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
var filename string
var input []byte
var err error
buffers := make([]*buffer.Buffer, 0, len(args))
btype := buffer.BTDefault
if !isatty.IsTerminal(os.Stdout.Fd()) {
btype = buffer.BTStdout
}
files := make([]string, 0, len(args))
flagStartPos := buffer.Loc{-1, -1}
flagr := regexp.MustCompile(`^\+(\d+)(?::(\d+))?$`)
for _, a := range args {
match := flagr.FindStringSubmatch(a)
if len(match) == 3 && match[2] != "" {
line, err := strconv.Atoi(match[1])
if err != nil {
screen.TermMessage(err)
continue
}
col, err := strconv.Atoi(match[2])
if err != nil {
screen.TermMessage(err)
continue
}
flagStartPos = buffer.Loc{col - 1, line - 1}
} else if len(match) == 3 && match[2] == "" {
line, err := strconv.Atoi(match[1])
if err != nil {
screen.TermMessage(err)
continue
}
flagStartPos = buffer.Loc{0, line - 1}
} else {
files = append(files, a)
}
}
if len(files) > 0 {
// Option 1
// We go through each file and load it
for i := 0; i < len(files); i++ {
buf, err := buffer.NewBufferFromFileAtLoc(files[i], btype, flagStartPos)
if err != nil {
screen.TermMessage(err)
continue
}
// If the file didn't exist, input will be empty, and we'll open an empty buffer
buffers = append(buffers, buf)
}
} else if !isatty.IsTerminal(os.Stdin.Fd()) {
// Option 2
// The input is not a terminal, so something is being piped in
// and we should read from stdin
input, err = ioutil.ReadAll(os.Stdin)
if err != nil {
screen.TermMessage("Error reading from stdin: ", err)
input = []byte{}
}
buffers = append(buffers, buffer.NewBufferFromStringAtLoc(string(input), filename, btype, flagStartPos))
} else {
// Option 3, just open an empty buffer
buffers = append(buffers, buffer.NewBufferFromStringAtLoc(string(input), filename, btype, flagStartPos))
}
return buffers
}
func main() {
defer func() {
if util.Stdout.Len() > 0 {
fmt.Fprint(os.Stdout, util.Stdout.String())
}
os.Exit(0)
}()
var err error
InitFlags()
if *flagProfile {
f, err := os.Create("micro.prof")
if err != nil {
log.Fatal("error creating CPU profile: ", err)
}
if err := pprof.StartCPUProfile(f); err != nil {
log.Fatal("error starting CPU profile: ", err)
}
defer pprof.StopCPUProfile()
}
InitLog()
err = config.InitConfigDir(*flagConfigDir)
if err != nil {
screen.TermMessage(err)
}
config.InitRuntimeFiles(true)
config.InitPlugins()
err = config.ReadSettings()
if err != nil {
screen.TermMessage(err)
}
err = config.InitGlobalSettings()
if err != nil {
screen.TermMessage(err)
}
// flag options
for k, v := range optionFlags {
if *v != "" {
nativeValue, err := config.GetNativeValue(k, config.DefaultAllSettings()[k], *v)
if err != nil {
screen.TermMessage(err)
continue
}
if err = config.OptionIsValid(k, nativeValue); err != nil {
screen.TermMessage(err)
continue
}
config.GlobalSettings[k] = nativeValue
config.VolatileSettings[k] = true
}
}
DoPluginFlags()
err = screen.Init()
if err != nil {
fmt.Println(err)
fmt.Println("Fatal: Micro could not initialize a Screen.")
os.Exit(1)
}
m := clipboard.SetMethod(config.GetGlobalOption("clipboard").(string))
clipErr := clipboard.Initialize(m)
defer func() {
if err := recover(); err != nil {
if screen.Screen != nil {
screen.Screen.Fini()
}
if e, ok := err.(*lua.ApiError); ok {
fmt.Println("Lua API error:", e)
} else {
fmt.Println("Micro encountered an error:", errors.Wrap(err, 2).ErrorStack(), "\nIf you can reproduce this error, please report it at path_to_url")
}
// backup all open buffers
for _, b := range buffer.OpenBuffers {
b.Backup()
}
os.Exit(1)
}
}()
err = config.LoadAllPlugins()
if err != nil {
screen.TermMessage(err)
}
action.InitBindings()
action.InitCommands()
err = config.InitColorscheme()
if err != nil {
screen.TermMessage(err)
}
err = config.RunPluginFn("preinit")
if err != nil {
screen.TermMessage(err)
}
action.InitGlobals()
buffer.SetMessager(action.InfoBar)
args := flag.Args()
b := LoadInput(args)
if len(b) == 0 {
// No buffers to open
screen.Screen.Fini()
runtime.Goexit()
}
action.InitTabs(b)
err = config.RunPluginFn("init")
if err != nil {
screen.TermMessage(err)
}
err = config.RunPluginFn("postinit")
if err != nil {
screen.TermMessage(err)
}
if clipErr != nil {
log.Println(clipErr, " or change 'clipboard' option")
}
config.StartAutoSave()
if a := config.GetGlobalOption("autosave").(float64); a > 0 {
config.SetAutoTime(a)
}
screen.Events = make(chan tcell.Event)
util.Sigterm = make(chan os.Signal, 1)
sighup = make(chan os.Signal, 1)
signal.Notify(util.Sigterm, syscall.SIGTERM, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGABRT)
signal.Notify(sighup, syscall.SIGHUP)
timerChan = make(chan func())
// Here is the event loop which runs in a separate thread
go func() {
for {
screen.Lock()
e := screen.Screen.PollEvent()
screen.Unlock()
if e != nil {
screen.Events <- e
}
}
}()
// clear the drawchan so we don't redraw excessively
// if someone requested a redraw before we started displaying
for len(screen.DrawChan()) > 0 {
<-screen.DrawChan()
}
// wait for initial resize event
select {
case event := <-screen.Events:
action.Tabs.HandleEvent(event)
case <-time.After(10 * time.Millisecond):
// time out after 10ms
}
for {
DoEvent()
}
}
// DoEvent runs the main action loop of the editor
func DoEvent() {
var event tcell.Event
// Display everything
screen.Screen.Fill(' ', config.DefStyle)
screen.Screen.HideCursor()
action.Tabs.Display()
for _, ep := range action.MainTab().Panes {
ep.Display()
}
action.MainTab().Display()
action.InfoBar.Display()
screen.Screen.Show()
// Check for new events
select {
case f := <-shell.Jobs:
// If a new job has finished while running in the background we should execute the callback
f.Function(f.Output, f.Args)
case <-config.Autosave:
for _, b := range buffer.OpenBuffers {
b.AutoSave()
}
case <-shell.CloseTerms:
action.Tabs.CloseTerms()
case event = <-screen.Events:
case <-screen.DrawChan():
for len(screen.DrawChan()) > 0 {
<-screen.DrawChan()
}
case f := <-timerChan:
f()
case <-sighup:
for _, b := range buffer.OpenBuffers {
if !b.Modified() {
b.Fini()
}
}
os.Exit(0)
case <-util.Sigterm:
for _, b := range buffer.OpenBuffers {
if !b.Modified() {
b.Fini()
}
}
if screen.Screen != nil {
screen.Screen.Fini()
}
os.Exit(0)
}
if e, ok := event.(*tcell.EventError); ok {
log.Println("tcell event error: ", e.Error())
if e.Err() == io.EOF {
// shutdown due to terminal closing/becoming inaccessible
for _, b := range buffer.OpenBuffers {
if !b.Modified() {
b.Fini()
}
}
if screen.Screen != nil {
screen.Screen.Fini()
}
os.Exit(0)
}
return
}
if event != nil {
_, resize := event.(*tcell.EventResize)
if resize {
action.InfoBar.HandleEvent(event)
action.Tabs.HandleEvent(event)
} else if action.InfoBar.HasPrompt {
action.InfoBar.HandleEvent(event)
} else {
action.Tabs.HandleEvent(event)
}
}
err := config.RunPluginFn("onAnyEvent")
if err != nil {
screen.TermMessage(err)
}
}
```
|
/content/code_sandbox/cmd/micro/micro.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 3,402
|
```go
package action
import (
"bytes"
"github.com/zyedidia/tcell/v2"
)
type PaneKeyAction func(Pane) bool
type PaneMouseAction func(Pane, *tcell.EventMouse) bool
type PaneKeyAnyAction func(Pane, []KeyEvent) bool
// A KeyTreeNode stores a single node in the KeyTree (trie). The
// children are stored as a map, and any node may store a list of
// actions (the list will be nil if no actions correspond to a certain
// node)
type KeyTreeNode struct {
children map[Event]*KeyTreeNode
// Only one of these actions may be active in the current
// mode, and only one will be returned. If multiple actions
// are active, it is undefined which one will be the one
// returned.
actions []TreeAction
}
func NewKeyTreeNode() *KeyTreeNode {
n := new(KeyTreeNode)
n.children = make(map[Event]*KeyTreeNode)
n.actions = []TreeAction{}
return n
}
// A TreeAction stores an action, and a set of mode constraints for
// the action to be active.
type TreeAction struct {
// only one of these can be non-nil
action PaneKeyAction
any PaneKeyAnyAction
mouse PaneMouseAction
modes []ModeConstraint
}
// A KeyTree is a data structure for storing keybindings. It maps
// key events to actions, and maintains a set of currently enabled
// modes, which affects the action that is returned for a key event.
// The tree acts like a Trie for Events to handle sequence events.
type KeyTree struct {
root *KeyTreeNode
modes map[string]bool
cursor KeyTreeCursor
}
// A KeyTreeCursor keeps track of the current location within the
// tree, and stores any information from previous events that may
// be needed to execute the action (values of wildcard events or
// mouse events)
type KeyTreeCursor struct {
node *KeyTreeNode
recordedEvents []Event
wildcards []KeyEvent
mouseInfo *tcell.EventMouse
}
// MakeClosure uses the information stored in a key tree cursor to construct
// a PaneKeyAction from a TreeAction (which may have a PaneKeyAction, PaneMouseAction,
// or AnyAction)
func (k *KeyTreeCursor) MakeClosure(a TreeAction) PaneKeyAction {
if a.action != nil {
return a.action
} else if a.any != nil {
return func(p Pane) bool {
return a.any(p, k.wildcards)
}
} else if a.mouse != nil {
return func(p Pane) bool {
return a.mouse(p, k.mouseInfo)
}
}
return nil
}
// NewKeyTree allocates and returns an empty key tree
func NewKeyTree() *KeyTree {
root := NewKeyTreeNode()
tree := new(KeyTree)
tree.root = root
tree.modes = make(map[string]bool)
tree.cursor = KeyTreeCursor{
node: root,
wildcards: []KeyEvent{},
mouseInfo: nil,
}
return tree
}
// A ModeConstraint specifies that an action can only be executed
// while a certain mode is enabled or disabled.
type ModeConstraint struct {
mode string
disabled bool
}
// RegisterKeyBinding registers a PaneKeyAction with an Event.
func (k *KeyTree) RegisterKeyBinding(e Event, a PaneKeyAction) {
k.registerBinding(e, TreeAction{
action: a,
any: nil,
mouse: nil,
modes: nil,
})
}
// RegisterKeyAnyBinding registers a PaneKeyAnyAction with an Event.
// The event should contain an "any" event.
func (k *KeyTree) RegisterKeyAnyBinding(e Event, a PaneKeyAnyAction) {
k.registerBinding(e, TreeAction{
action: nil,
any: a,
mouse: nil,
modes: nil,
})
}
// RegisterMouseBinding registers a PaneMouseAction with an Event.
// The event should contain a mouse event.
func (k *KeyTree) RegisterMouseBinding(e Event, a PaneMouseAction) {
k.registerBinding(e, TreeAction{
action: nil,
any: nil,
mouse: a,
modes: nil,
})
}
func (k *KeyTree) registerBinding(e Event, a TreeAction) {
switch ev := e.(type) {
case KeyEvent, MouseEvent, RawEvent:
newNode, ok := k.root.children[e]
if !ok {
newNode = NewKeyTreeNode()
k.root.children[e] = newNode
}
// newNode.actions = append(newNode.actions, a)
newNode.actions = []TreeAction{a}
case KeySequenceEvent:
n := k.root
for _, key := range ev.keys {
newNode, ok := n.children[key]
if !ok {
newNode = NewKeyTreeNode()
n.children[key] = newNode
}
n = newNode
}
// n.actions = append(n.actions, a)
n.actions = []TreeAction{a}
}
}
// NextEvent returns the action for the current sequence where e is the next
// event. Even if the action was registered as a PaneKeyAnyAction or PaneMouseAction,
// it will be returned as a PaneKeyAction closure where the appropriate arguments
// have been provided.
// If no action is associated with the given Event, or mode constraints are not
// met for that action, nil is returned.
// A boolean is returned to indicate if there is a conflict with this action. A
// conflict occurs when there is an active action for this event but there are
// bindings associated with further sequences starting with this event. The
// calling function can decide what to do about the conflict (e.g. use a
// timeout).
func (k *KeyTree) NextEvent(e Event, mouse *tcell.EventMouse) (PaneKeyAction, bool) {
n := k.cursor.node
c, ok := n.children[e]
if !ok {
return nil, false
}
more := len(c.children) > 0
k.cursor.node = c
k.cursor.recordedEvents = append(k.cursor.recordedEvents, e)
switch ev := e.(type) {
case KeyEvent:
if ev.any {
k.cursor.wildcards = append(k.cursor.wildcards, ev)
}
case MouseEvent:
k.cursor.mouseInfo = mouse
}
if len(c.actions) > 0 {
// check if actions are active
for _, a := range c.actions {
active := true
for _, mc := range a.modes {
// if any mode constraint is not met, the action is not active
hasMode := k.modes[mc.mode]
if hasMode != mc.disabled {
active = false
}
}
if active {
// the first active action to be found is returned
return k.cursor.MakeClosure(a), more
}
}
}
return nil, more
}
// ResetEvents sets the current sequence back to the initial value.
func (k *KeyTree) ResetEvents() {
k.cursor.node = k.root
k.cursor.wildcards = []KeyEvent{}
k.cursor.recordedEvents = []Event{}
k.cursor.mouseInfo = nil
}
// RecordedEventsStr returns the list of recorded events as a string
func (k *KeyTree) RecordedEventsStr() string {
buf := &bytes.Buffer{}
for _, e := range k.cursor.recordedEvents {
buf.WriteString(e.Name())
}
return buf.String()
}
// DeleteBinding removes any currently active actions associated with the
// given event.
func (k *KeyTree) DeleteBinding(e Event) {
}
// DeleteAllBindings removes all actions associated with the given event,
// regardless of whether they are active or not.
func (k *KeyTree) DeleteAllBindings(e Event) {
}
// SetMode enables or disabled a given mode
func (k *KeyTree) SetMode(mode string, en bool) {
k.modes[mode] = en
}
// HasMode returns if the given mode is currently active
func (k *KeyTree) HasMode(mode string) bool {
return k.modes[mode]
}
```
|
/content/code_sandbox/internal/action/keytree.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 1,777
|
```go
package action
import "github.com/zyedidia/micro/v2/internal/buffer"
// InfoBar is the global info bar.
var InfoBar *InfoPane
// LogBufPane is a global log buffer.
var LogBufPane *BufPane
// InitGlobals initializes the log buffer and the info bar
func InitGlobals() {
InfoBar = NewInfoBar()
buffer.LogBuf = buffer.NewBufferFromString("", "Log", buffer.BTLog)
}
// GetInfoBar returns the infobar pane
func GetInfoBar() *InfoPane {
return InfoBar
}
// WriteLog writes a string to the log buffer
func WriteLog(s string) {
buffer.WriteLog(s)
if LogBufPane != nil {
LogBufPane.CursorEnd()
}
}
// OpenLogBuf opens the log buffer from the current bufpane
// If the current bufpane is a log buffer nothing happens,
// otherwise the log buffer is opened in a horizontal split
func (h *BufPane) OpenLogBuf() {
LogBufPane = h.HSplitBuf(buffer.LogBuf)
LogBufPane.CursorEnd()
}
```
|
/content/code_sandbox/internal/action/globals.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 231
|
```go
package action
import (
"github.com/zyedidia/micro/v2/internal/display"
)
// A Pane is a general interface for a window in the editor.
type Pane interface {
Handler
display.Window
ID() uint64
SetID(i uint64)
Name() string
Close()
SetTab(t *Tab)
Tab() *Tab
}
```
|
/content/code_sandbox/internal/action/pane.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 75
|
```go
// +build !linux,!darwin,!freebsd,!dragonfly,!openbsd_amd64
package action
import "errors"
// TermEmuSupported is a constant that marks if the terminal emulator is supported
const TermEmuSupported = false
// RunTermEmulator returns an error for unsupported systems (non-unix systems
func RunTermEmulator(input string, wait bool, getOutput bool, callback func(out string, userargs []interface{}), userargs []interface{}) error {
return errors.New("Unsupported operating system")
}
```
|
/content/code_sandbox/internal/action/terminal_unsupported.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 112
|
```go
package action
var termdefaults = map[string]string{
"<Ctrl-q><Ctrl-q>": "Exit",
"<Ctrl-e><Ctrl-e>": "CommandMode",
"<Ctrl-w><Ctrl-w>": "NextSplit",
}
// DefaultBindings returns a map containing micro's default keybindings
func DefaultBindings(pane string) map[string]string {
switch pane {
case "command":
return infodefaults
case "buffer":
return bufdefaults
case "terminal":
return termdefaults
default:
return map[string]string{}
}
}
```
|
/content/code_sandbox/internal/action/defaults.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 118
|
```go
package action
var bufdefaults = map[string]string{
"Up": "CursorUp",
"Down": "CursorDown",
"Right": "CursorRight",
"Left": "CursorLeft",
"ShiftUp": "SelectUp",
"ShiftDown": "SelectDown",
"ShiftLeft": "SelectLeft",
"ShiftRight": "SelectRight",
"AltLeft": "WordLeft",
"AltRight": "WordRight",
"AltUp": "MoveLinesUp",
"AltDown": "MoveLinesDown",
"AltShiftRight": "SelectWordRight",
"AltShiftLeft": "SelectWordLeft",
"CtrlLeft": "StartOfTextToggle",
"CtrlRight": "EndOfLine",
"CtrlShiftLeft": "SelectToStartOfTextToggle",
"ShiftHome": "SelectToStartOfTextToggle",
"CtrlShiftRight": "SelectToEndOfLine",
"ShiftEnd": "SelectToEndOfLine",
"CtrlUp": "CursorStart",
"CtrlDown": "CursorEnd",
"CtrlShiftUp": "SelectToStart",
"CtrlShiftDown": "SelectToEnd",
"Alt-{": "ParagraphPrevious",
"Alt-}": "ParagraphNext",
"Enter": "InsertNewline",
"CtrlH": "Backspace",
"Backspace": "Backspace",
"OldBackspace": "Backspace",
"Alt-CtrlH": "DeleteWordLeft",
"Alt-Backspace": "DeleteWordLeft",
"Tab": "Autocomplete|IndentSelection|InsertTab",
"Backtab": "CycleAutocompleteBack|OutdentSelection|OutdentLine",
"Ctrl-o": "OpenFile",
"Ctrl-s": "Save",
"Ctrl-f": "Find",
"Alt-F": "FindLiteral",
"Ctrl-n": "FindNext",
"Ctrl-p": "FindPrevious",
"Alt-[": "DiffPrevious|CursorStart",
"Alt-]": "DiffNext|CursorEnd",
"Ctrl-z": "Undo",
"Ctrl-y": "Redo",
"Ctrl-c": "CopyLine|Copy",
"Ctrl-x": "Cut",
"Ctrl-k": "CutLine",
"Ctrl-d": "DuplicateLine",
"Ctrl-v": "Paste",
"Ctrl-a": "SelectAll",
"Ctrl-t": "AddTab",
"Alt-,": "PreviousTab",
"Alt-.": "NextTab",
"Home": "StartOfTextToggle",
"End": "EndOfLine",
"CtrlHome": "CursorStart",
"CtrlEnd": "CursorEnd",
"PageUp": "CursorPageUp",
"PageDown": "CursorPageDown",
"CtrlPageUp": "PreviousTab",
"CtrlPageDown": "NextTab",
"ShiftPageUp": "SelectPageUp",
"ShiftPageDown": "SelectPageDown",
"Ctrl-g": "ToggleHelp",
"Alt-g": "ToggleKeyMenu",
"Ctrl-r": "ToggleRuler",
"Ctrl-l": "command-edit:goto ",
"Delete": "Delete",
"Ctrl-b": "ShellMode",
"Ctrl-q": "Quit",
"Ctrl-e": "CommandMode",
"Ctrl-w": "NextSplit",
"Ctrl-u": "ToggleMacro",
"Ctrl-j": "PlayMacro",
"Insert": "ToggleOverwriteMode",
// Emacs-style keybindings
"Alt-f": "WordRight",
"Alt-b": "WordLeft",
"Alt-a": "StartOfText",
"Alt-e": "EndOfLine",
// "Alt-p": "CursorUp",
// "Alt-n": "CursorDown",
// Integration with file managers
"F2": "Save",
"F3": "Find",
"F4": "Quit",
"F7": "Find",
"F10": "Quit",
"Esc": "Escape,Deselect,ClearInfo,RemoveAllMultiCursors,UnhighlightSearch",
// Mouse bindings
"MouseWheelUp": "ScrollUp",
"MouseWheelDown": "ScrollDown",
"MouseLeft": "MousePress",
"MouseLeftDrag": "MouseDrag",
"MouseLeftRelease": "MouseRelease",
"MouseMiddle": "PastePrimary",
"Ctrl-MouseLeft": "MouseMultiCursor",
"Alt-n": "SpawnMultiCursor",
"AltShiftUp": "SpawnMultiCursorUp",
"AltShiftDown": "SpawnMultiCursorDown",
"Alt-m": "SpawnMultiCursorSelect",
"Alt-p": "RemoveMultiCursor",
"Alt-c": "RemoveAllMultiCursors",
"Alt-x": "SkipMultiCursor",
}
var infodefaults = map[string]string{
"Up": "HistoryUp",
"Down": "HistoryDown",
"Right": "CursorRight",
"Left": "CursorLeft",
"ShiftUp": "SelectUp",
"ShiftDown": "SelectDown",
"ShiftLeft": "SelectLeft",
"ShiftRight": "SelectRight",
"AltLeft": "WordLeft",
"AltRight": "WordRight",
"AltUp": "CursorStart",
"AltDown": "CursorEnd",
"AltShiftRight": "SelectWordRight",
"AltShiftLeft": "SelectWordLeft",
"CtrlLeft": "StartOfTextToggle",
"CtrlRight": "EndOfLine",
"CtrlShiftLeft": "SelectToStartOfTextToggle",
"ShiftHome": "SelectToStartOfTextToggle",
"CtrlShiftRight": "SelectToEndOfLine",
"ShiftEnd": "SelectToEndOfLine",
"CtrlUp": "CursorStart",
"CtrlDown": "CursorEnd",
"CtrlShiftUp": "SelectToStart",
"CtrlShiftDown": "SelectToEnd",
"Enter": "ExecuteCommand",
"CtrlH": "Backspace",
"Backspace": "Backspace",
"OldBackspace": "Backspace",
"Alt-CtrlH": "DeleteWordLeft",
"Alt-Backspace": "DeleteWordLeft",
"Tab": "CommandComplete",
"Backtab": "CycleAutocompleteBack",
"Ctrl-z": "Undo",
"Ctrl-y": "Redo",
"Ctrl-c": "CopyLine|Copy",
"Ctrl-x": "Cut",
"Ctrl-k": "CutLine",
"Ctrl-v": "Paste",
"Home": "StartOfTextToggle",
"End": "EndOfLine",
"CtrlHome": "CursorStart",
"CtrlEnd": "CursorEnd",
"Delete": "Delete",
"Ctrl-q": "AbortCommand",
"Ctrl-e": "EndOfLine",
"Ctrl-a": "StartOfLine",
"Ctrl-w": "DeleteWordLeft",
"Insert": "ToggleOverwriteMode",
"Ctrl-b": "WordLeft",
"Ctrl-f": "WordRight",
"Ctrl-d": "DeleteWordLeft",
"Ctrl-m": "ExecuteCommand",
"Ctrl-n": "HistoryDown",
"Ctrl-p": "HistoryUp",
"Ctrl-u": "SelectToStart",
// Emacs-style keybindings
"Alt-f": "WordRight",
"Alt-b": "WordLeft",
"Alt-a": "StartOfText",
"Alt-e": "EndOfLine",
// Integration with file managers
"F10": "AbortCommand",
"Esc": "AbortCommand",
// Mouse bindings
"MouseWheelUp": "HistoryUp",
"MouseWheelDown": "HistoryDown",
"MouseLeft": "MousePress",
"MouseLeftDrag": "MouseDrag",
"MouseLeftRelease": "MouseRelease",
"MouseMiddle": "PastePrimary",
}
```
|
/content/code_sandbox/internal/action/defaults_darwin.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 1,846
|
```go
package action
import (
"bytes"
"github.com/zyedidia/micro/v2/internal/buffer"
"github.com/zyedidia/micro/v2/internal/config"
"github.com/zyedidia/micro/v2/internal/display"
"github.com/zyedidia/micro/v2/internal/info"
"github.com/zyedidia/micro/v2/internal/util"
"github.com/zyedidia/tcell/v2"
)
type InfoKeyAction func(*InfoPane)
var InfoBindings *KeyTree
var InfoBufBindings *KeyTree
func init() {
InfoBindings = NewKeyTree()
InfoBufBindings = NewKeyTree()
}
func InfoMapEvent(k Event, action string) {
config.Bindings["command"][k.Name()] = action
switch e := k.(type) {
case KeyEvent, KeySequenceEvent, RawEvent:
infoMapKey(e, action)
case MouseEvent:
infoMapMouse(e, action)
}
}
func infoMapKey(k Event, action string) {
if f, ok := InfoKeyActions[action]; ok {
InfoBindings.RegisterKeyBinding(k, InfoKeyActionGeneral(f))
} else if f, ok := BufKeyActions[action]; ok {
InfoBufBindings.RegisterKeyBinding(k, BufKeyActionGeneral(f))
}
}
func infoMapMouse(k MouseEvent, action string) {
// TODO: map mouse
if f, ok := BufMouseActions[action]; ok {
InfoBufBindings.RegisterMouseBinding(k, BufMouseActionGeneral(f))
} else {
infoMapKey(k, action)
}
}
func InfoKeyActionGeneral(a InfoKeyAction) PaneKeyAction {
return func(p Pane) bool {
a(p.(*InfoPane))
return true
}
}
type InfoPane struct {
*BufPane
*info.InfoBuf
}
func NewInfoPane(ib *info.InfoBuf, w display.BWindow, tab *Tab) *InfoPane {
ip := new(InfoPane)
ip.InfoBuf = ib
ip.BufPane = NewBufPane(ib.Buffer, w, tab)
ip.BufPane.bindings = InfoBufBindings
return ip
}
func NewInfoBar() *InfoPane {
ib := info.NewBuffer()
w := display.NewInfoWindow(ib)
return NewInfoPane(ib, w, nil)
}
func (h *InfoPane) Close() {
h.InfoBuf.Close()
h.BufPane.Close()
}
func (h *InfoPane) HandleEvent(event tcell.Event) {
switch e := event.(type) {
case *tcell.EventResize:
// TODO
case *tcell.EventKey:
ke := keyEvent(e)
done := h.DoKeyEvent(ke)
hasYN := h.HasYN
if e.Key() == tcell.KeyRune && hasYN {
y := e.Rune() == 'y' || e.Rune() == 'Y'
n := e.Rune() == 'n' || e.Rune() == 'N'
if y || n {
h.YNResp = y
h.DonePrompt(false)
InfoBindings.ResetEvents()
InfoBufBindings.ResetEvents()
}
}
if e.Key() == tcell.KeyRune && !done && !hasYN {
h.DoRuneInsert(e.Rune())
done = true
}
if done && h.HasPrompt && !hasYN {
resp := string(h.LineBytes(0))
hist := h.History[h.PromptType]
if resp != hist[h.HistoryNum] {
h.HistoryNum = len(hist) - 1
hist[h.HistoryNum] = resp
h.HistorySearch = false
}
if h.EventCallback != nil {
h.EventCallback(resp)
}
}
default:
h.BufPane.HandleEvent(event)
}
}
// DoKeyEvent executes a key event for the command bar, doing any overridden actions.
// Returns true if the action was executed OR if there are more keys remaining
// to process before executing an action (if this is a key sequence event).
// Returns false if no action found.
func (h *InfoPane) DoKeyEvent(e KeyEvent) bool {
action, more := InfoBindings.NextEvent(e, nil)
if action != nil && !more {
action(h)
InfoBindings.ResetEvents()
return true
} else if action == nil && !more {
InfoBindings.ResetEvents()
// return false //TODO:?
}
if !more {
// If no infopane action found, try to find a bufpane action.
//
// TODO: this is buggy. For example, if the command bar has the following
// two bindings:
//
// "<Ctrl-x><Ctrl-p>": "HistoryUp",
// "<Ctrl-x><Ctrl-v>": "Paste",
//
// the 2nd binding (with a bufpane action) doesn't work, since <Ctrl-x>
// has been already consumed by the 1st binding (with an infopane action).
//
// We should either iterate both InfoBindings and InfoBufBindings keytrees
// together, or just use the same keytree for both infopane and bufpane
// bindings.
action, more = InfoBufBindings.NextEvent(e, nil)
if action != nil && !more {
action(h.BufPane)
InfoBufBindings.ResetEvents()
return true
} else if action == nil && !more {
InfoBufBindings.ResetEvents()
}
}
return more
}
// HistoryUp cycles history up
func (h *InfoPane) HistoryUp() {
h.UpHistory(h.History[h.PromptType])
}
// HistoryDown cycles history down
func (h *InfoPane) HistoryDown() {
h.DownHistory(h.History[h.PromptType])
}
// HistorySearchUp fetches the previous history item beginning with the text
// in the infobuffer before cursor
func (h *InfoPane) HistorySearchUp() {
h.SearchUpHistory(h.History[h.PromptType])
}
// HistorySearchDown fetches the next history item beginning with the text
// in the infobuffer before cursor
func (h *InfoPane) HistorySearchDown() {
h.SearchDownHistory(h.History[h.PromptType])
}
// Autocomplete begins autocompletion
func (h *InfoPane) CommandComplete() {
b := h.Buf
if b.HasSuggestions {
b.CycleAutocomplete(true)
return
}
c := b.GetActiveCursor()
l := b.LineBytes(0)
l = util.SliceStart(l, c.X)
args := bytes.Split(l, []byte{' '})
cmd := string(args[0])
if h.PromptType == "Command" {
if len(args) == 1 {
b.Autocomplete(CommandComplete)
} else if action, ok := commands[cmd]; ok {
if action.completer != nil {
b.Autocomplete(action.completer)
}
}
} else {
// by default use filename autocompletion
b.Autocomplete(buffer.FileComplete)
}
}
// ExecuteCommand completes the prompt
func (h *InfoPane) ExecuteCommand() {
if !h.HasYN {
h.DonePrompt(false)
}
}
// AbortCommand cancels the prompt
func (h *InfoPane) AbortCommand() {
h.DonePrompt(true)
}
// InfoKeyActions contains the list of all possible key actions the infopane could execute
var InfoKeyActions = map[string]InfoKeyAction{
"HistoryUp": (*InfoPane).HistoryUp,
"HistoryDown": (*InfoPane).HistoryDown,
"HistorySearchUp": (*InfoPane).HistorySearchUp,
"HistorySearchDown": (*InfoPane).HistorySearchDown,
"CommandComplete": (*InfoPane).CommandComplete,
"ExecuteCommand": (*InfoPane).ExecuteCommand,
"AbortCommand": (*InfoPane).AbortCommand,
}
```
|
/content/code_sandbox/internal/action/infopane.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 1,732
|
```go
package action
import (
luar "layeh.com/gopher-luar"
"github.com/zyedidia/micro/v2/internal/buffer"
"github.com/zyedidia/micro/v2/internal/config"
"github.com/zyedidia/micro/v2/internal/display"
ulua "github.com/zyedidia/micro/v2/internal/lua"
"github.com/zyedidia/micro/v2/internal/screen"
"github.com/zyedidia/micro/v2/internal/views"
"github.com/zyedidia/tcell/v2"
)
// The TabList is a list of tabs and a window to display the tab bar
// at the top of the screen
type TabList struct {
*display.TabWindow
List []*Tab
}
// NewTabList creates a TabList from a list of buffers by creating a Tab
// for each buffer
func NewTabList(bufs []*buffer.Buffer) *TabList {
w, h := screen.Screen.Size()
iOffset := config.GetInfoBarOffset()
tl := new(TabList)
tl.List = make([]*Tab, len(bufs))
if len(bufs) > 1 {
for i, b := range bufs {
tl.List[i] = NewTabFromBuffer(0, 1, w, h-1-iOffset, b)
}
} else {
tl.List[0] = NewTabFromBuffer(0, 0, w, h-iOffset, bufs[0])
}
tl.TabWindow = display.NewTabWindow(w, 0)
tl.Names = make([]string, len(bufs))
return tl
}
// UpdateNames makes sure that the list of names the tab window has access to is
// correct
func (t *TabList) UpdateNames() {
t.Names = t.Names[:0]
for _, p := range t.List {
t.Names = append(t.Names, p.Panes[p.active].Name())
}
}
// AddTab adds a new tab to this TabList
func (t *TabList) AddTab(p *Tab) {
t.List = append(t.List, p)
t.Resize()
t.UpdateNames()
}
// RemoveTab removes a tab with the given id from the TabList
func (t *TabList) RemoveTab(id uint64) {
for i, p := range t.List {
if len(p.Panes) == 0 {
continue
}
if p.Panes[0].ID() == id {
copy(t.List[i:], t.List[i+1:])
t.List[len(t.List)-1] = nil
t.List = t.List[:len(t.List)-1]
if t.Active() >= len(t.List) {
t.SetActive(len(t.List) - 1)
}
t.Resize()
t.UpdateNames()
return
}
}
}
// Resize resizes all elements within the tab list
// One thing to note is that when there is only 1 tab
// the tab bar should not be drawn so resizing must take
// that into account
func (t *TabList) Resize() {
w, h := screen.Screen.Size()
iOffset := config.GetInfoBarOffset()
InfoBar.Resize(w, h-1)
if len(t.List) > 1 {
for _, p := range t.List {
p.Y = 1
p.Node.Resize(w, h-1-iOffset)
p.Resize()
}
} else if len(t.List) == 1 {
t.List[0].Y = 0
t.List[0].Node.Resize(w, h-iOffset)
t.List[0].Resize()
}
t.TabWindow.Resize(w, h)
}
// HandleEvent checks for a resize event or a mouse event on the tab bar
// otherwise it will forward the event to the currently active tab
func (t *TabList) HandleEvent(event tcell.Event) {
switch e := event.(type) {
case *tcell.EventResize:
t.Resize()
case *tcell.EventMouse:
mx, my := e.Position()
switch e.Buttons() {
case tcell.Button1:
if my == t.Y && len(t.List) > 1 {
if mx == 0 {
t.Scroll(-4)
} else if mx == t.Width-1 {
t.Scroll(4)
} else {
ind := t.LocFromVisual(buffer.Loc{mx, my})
if ind != -1 {
t.SetActive(ind)
}
}
return
}
case tcell.ButtonNone:
if t.List[t.Active()].release {
// Mouse release received, while already released
t.ResetMouse()
return
}
case tcell.WheelUp:
if my == t.Y && len(t.List) > 1 {
t.Scroll(4)
return
}
case tcell.WheelDown:
if my == t.Y && len(t.List) > 1 {
t.Scroll(-4)
return
}
}
}
t.List[t.Active()].HandleEvent(event)
}
// Display updates the names and then displays the tab bar
func (t *TabList) Display() {
t.UpdateNames()
if len(t.List) > 1 {
t.TabWindow.Display()
}
}
func (t *TabList) SetActive(a int) {
t.TabWindow.SetActive(a)
for i, p := range t.List {
if i == a {
if !p.isActive {
p.isActive = true
err := config.RunPluginFn("onSetActive", luar.New(ulua.L, p.CurPane()))
if err != nil {
screen.TermMessage(err)
}
}
} else {
p.isActive = false
}
}
}
// ResetMouse resets the mouse release state after the screen was stopped
// or the pane changed.
// This prevents situations in which mouse releases are received at the wrong place
// and the mouse state is still pressed.
func (t *TabList) ResetMouse() {
for _, tab := range t.List {
if !tab.release && tab.resizing != nil {
tab.resizing = nil
}
tab.release = true
for _, p := range tab.Panes {
if bp, ok := p.(*BufPane); ok {
bp.resetMouse()
}
}
}
}
// CloseTerms notifies term panes that a terminal job has finished.
func (t *TabList) CloseTerms() {
for _, tab := range t.List {
for _, p := range tab.Panes {
if tp, ok := p.(*TermPane); ok {
tp.HandleTermClose()
}
}
}
}
// Tabs is the global tab list
var Tabs *TabList
func InitTabs(bufs []*buffer.Buffer) {
multiopen := config.GetGlobalOption("multiopen").(string)
if multiopen == "tab" {
Tabs = NewTabList(bufs)
} else {
Tabs = NewTabList(bufs[:1])
for _, b := range bufs[1:] {
if multiopen == "vsplit" {
MainTab().CurPane().VSplitBuf(b)
} else { // default hsplit
MainTab().CurPane().HSplitBuf(b)
}
}
}
screen.RestartCallback = Tabs.ResetMouse
}
func MainTab() *Tab {
return Tabs.List[Tabs.Active()]
}
// A Tab represents a single tab
// It consists of a list of edit panes (the open buffers),
// a split tree (stored as just the root node), and a uiwindow
// to display the UI elements like the borders between splits
type Tab struct {
*views.Node
*display.UIWindow
isActive bool
Panes []Pane
active int
resizing *views.Node // node currently being resized
// captures whether the mouse is released
release bool
}
// NewTabFromBuffer creates a new tab from the given buffer
func NewTabFromBuffer(x, y, width, height int, b *buffer.Buffer) *Tab {
t := new(Tab)
t.Node = views.NewRoot(x, y, width, height)
t.UIWindow = display.NewUIWindow(t.Node)
t.release = true
e := NewBufPaneFromBuf(b, t)
e.SetID(t.ID())
t.Panes = append(t.Panes, e)
return t
}
func NewTabFromPane(x, y, width, height int, pane Pane) *Tab {
t := new(Tab)
t.Node = views.NewRoot(x, y, width, height)
t.UIWindow = display.NewUIWindow(t.Node)
t.release = true
pane.SetTab(t)
pane.SetID(t.ID())
t.Panes = append(t.Panes, pane)
return t
}
// HandleEvent takes a tcell event and usually dispatches it to the current
// active pane. However if the event is a resize or a mouse event where the user
// is interacting with the UI (resizing splits) then the event is consumed here
// If the event is a mouse press event in a pane, that pane will become active
// and get the event
func (t *Tab) HandleEvent(event tcell.Event) {
switch e := event.(type) {
case *tcell.EventMouse:
mx, my := e.Position()
btn := e.Buttons()
switch {
case btn & ^(tcell.WheelUp|tcell.WheelDown|tcell.WheelLeft|tcell.WheelRight) != tcell.ButtonNone:
// button press or drag
wasReleased := t.release
t.release = false
if btn == tcell.Button1 {
if t.resizing != nil {
var size int
if t.resizing.Kind == views.STVert {
size = mx - t.resizing.X
} else {
size = my - t.resizing.Y + 1
}
t.resizing.ResizeSplit(size)
t.Resize()
return
}
if wasReleased {
t.resizing = t.GetMouseSplitNode(buffer.Loc{mx, my})
if t.resizing != nil {
return
}
}
}
if wasReleased {
for i, p := range t.Panes {
v := p.GetView()
inpane := mx >= v.X && mx < v.X+v.Width && my >= v.Y && my < v.Y+v.Height
if inpane {
t.SetActive(i)
break
}
}
}
case btn == tcell.ButtonNone:
// button release
t.release = true
if t.resizing != nil {
t.resizing = nil
return
}
default:
// wheel move
for _, p := range t.Panes {
v := p.GetView()
inpane := mx >= v.X && mx < v.X+v.Width && my >= v.Y && my < v.Y+v.Height
if inpane {
p.HandleEvent(event)
return
}
}
}
}
t.Panes[t.active].HandleEvent(event)
}
// SetActive changes the currently active pane to the specified index
func (t *Tab) SetActive(i int) {
t.active = i
for j, p := range t.Panes {
if j == i {
p.SetActive(true)
} else {
p.SetActive(false)
}
}
}
// GetPane returns the pane with the given split index
func (t *Tab) GetPane(splitid uint64) int {
for i, p := range t.Panes {
if p.ID() == splitid {
return i
}
}
return 0
}
// Remove pane removes the pane with the given index
func (t *Tab) RemovePane(i int) {
copy(t.Panes[i:], t.Panes[i+1:])
t.Panes[len(t.Panes)-1] = nil
t.Panes = t.Panes[:len(t.Panes)-1]
}
// Resize resizes all panes according to their corresponding split nodes
func (t *Tab) Resize() {
for _, p := range t.Panes {
n := t.GetNode(p.ID())
pv := p.GetView()
offset := 0
if n.X != 0 {
offset = 1
}
pv.X, pv.Y = n.X+offset, n.Y
p.SetView(pv)
p.Resize(n.W-offset, n.H)
}
}
// CurPane returns the currently active pane
func (t *Tab) CurPane() *BufPane {
p, ok := t.Panes[t.active].(*BufPane)
if !ok {
return nil
}
return p
}
```
|
/content/code_sandbox/internal/action/tab.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 2,762
|
```go
package action
import (
"bytes"
"sort"
"strings"
"github.com/zyedidia/micro/v2/internal/buffer"
"github.com/zyedidia/micro/v2/internal/config"
"github.com/zyedidia/micro/v2/internal/util"
"github.com/zyedidia/micro/v2/pkg/highlight"
)
// This file is meant (for now) for autocompletion in command mode, not
// while coding. This helps micro autocomplete commands and then filenames
// for example with `vsplit filename`.
// CommandComplete autocompletes commands
func CommandComplete(b *buffer.Buffer) ([]string, []string) {
c := b.GetActiveCursor()
input, argstart := b.GetArg()
var suggestions []string
for cmd := range commands {
if strings.HasPrefix(cmd, input) {
suggestions = append(suggestions, cmd)
}
}
sort.Strings(suggestions)
completions := make([]string, len(suggestions))
for i := range suggestions {
completions[i] = util.SliceEndStr(suggestions[i], c.X-argstart)
}
return completions, suggestions
}
// HelpComplete autocompletes help topics
func HelpComplete(b *buffer.Buffer) ([]string, []string) {
c := b.GetActiveCursor()
input, argstart := b.GetArg()
var suggestions []string
for _, file := range config.ListRuntimeFiles(config.RTHelp) {
topic := file.Name()
if strings.HasPrefix(topic, input) {
suggestions = append(suggestions, topic)
}
}
sort.Strings(suggestions)
completions := make([]string, len(suggestions))
for i := range suggestions {
completions[i] = util.SliceEndStr(suggestions[i], c.X-argstart)
}
return completions, suggestions
}
// colorschemeComplete tab-completes names of colorschemes.
// This is just a heper value for OptionValueComplete
func colorschemeComplete(input string) (string, []string) {
var suggestions []string
files := config.ListRuntimeFiles(config.RTColorscheme)
for _, f := range files {
if strings.HasPrefix(f.Name(), input) {
suggestions = append(suggestions, f.Name())
}
}
var chosen string
if len(suggestions) == 1 {
chosen = suggestions[0]
}
return chosen, suggestions
}
// filetypeComplete autocompletes filetype
func filetypeComplete(input string) (string, []string) {
var suggestions []string
// We cannot match filetypes just by names of syntax files,
// since those names may be different from the actual filetype values
// specified inside syntax files (e.g. "c++" filetype in cpp.yaml).
// So we need to parse filetype values out of those files.
for _, f := range config.ListRealRuntimeFiles(config.RTSyntax) {
data, err := f.Data()
if err != nil {
continue
}
header, err := highlight.MakeHeaderYaml(data)
if err != nil {
continue
}
// Prevent duplicated defaults
if header.FileType == "off" || header.FileType == "unknown" {
continue
}
if strings.HasPrefix(header.FileType, input) {
suggestions = append(suggestions, header.FileType)
}
}
headerLoop:
for _, f := range config.ListRuntimeFiles(config.RTSyntaxHeader) {
data, err := f.Data()
if err != nil {
continue
}
header, err := highlight.MakeHeader(data)
if err != nil {
continue
}
for _, v := range suggestions {
if v == header.FileType {
continue headerLoop
}
}
if strings.HasPrefix(header.FileType, input) {
suggestions = append(suggestions, header.FileType)
}
}
if strings.HasPrefix("off", input) {
suggestions = append(suggestions, "off")
}
var chosen string
if len(suggestions) == 1 {
chosen = suggestions[0]
}
return chosen, suggestions
}
func contains(s []string, e string) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}
// OptionComplete autocompletes options
func OptionComplete(b *buffer.Buffer) ([]string, []string) {
c := b.GetActiveCursor()
input, argstart := b.GetArg()
var suggestions []string
for option := range config.GlobalSettings {
if strings.HasPrefix(option, input) {
suggestions = append(suggestions, option)
}
}
// for option := range localSettings {
// if strings.HasPrefix(option, input) && !contains(suggestions, option) {
// suggestions = append(suggestions, option)
// }
// }
sort.Strings(suggestions)
completions := make([]string, len(suggestions))
for i := range suggestions {
completions[i] = util.SliceEndStr(suggestions[i], c.X-argstart)
}
return completions, suggestions
}
// OptionValueComplete completes values for various options
func OptionValueComplete(b *buffer.Buffer) ([]string, []string) {
c := b.GetActiveCursor()
l := b.LineBytes(c.Y)
l = util.SliceStart(l, c.X)
input, argstart := b.GetArg()
completeValue := false
args := bytes.Split(l, []byte{' '})
if len(args) >= 2 {
// localSettings := config.DefaultLocalSettings()
for option := range config.GlobalSettings {
if option == string(args[len(args)-2]) {
completeValue = true
break
}
}
// for option := range localSettings {
// if option == string(args[len(args)-2]) {
// completeValue = true
// break
// }
// }
}
if !completeValue {
return OptionComplete(b)
}
inputOpt := string(args[len(args)-2])
inputOpt = strings.TrimSpace(inputOpt)
var suggestions []string
// localSettings := config.DefaultLocalSettings()
var optionVal interface{}
for k, option := range config.GlobalSettings {
if k == inputOpt {
optionVal = option
}
}
// for k, option := range localSettings {
// if k == inputOpt {
// optionVal = option
// }
// }
switch optionVal.(type) {
case bool:
if strings.HasPrefix("on", input) {
suggestions = append(suggestions, "on")
} else if strings.HasPrefix("true", input) {
suggestions = append(suggestions, "true")
}
if strings.HasPrefix("off", input) {
suggestions = append(suggestions, "off")
} else if strings.HasPrefix("false", input) {
suggestions = append(suggestions, "false")
}
case string:
switch inputOpt {
case "colorscheme":
_, suggestions = colorschemeComplete(input)
case "filetype":
_, suggestions = filetypeComplete(input)
case "sucmd":
if strings.HasPrefix("sudo", input) {
suggestions = append(suggestions, "sudo")
}
if strings.HasPrefix("doas", input) {
suggestions = append(suggestions, "doas")
}
default:
if choices, ok := config.OptionChoices[inputOpt]; ok {
for _, choice := range choices {
if strings.HasPrefix(choice, input) {
suggestions = append(suggestions, choice)
}
}
}
}
}
sort.Strings(suggestions)
completions := make([]string, len(suggestions))
for i := range suggestions {
completions[i] = util.SliceEndStr(suggestions[i], c.X-argstart)
}
return completions, suggestions
}
// PluginCmdComplete autocompletes the plugin command
func PluginCmdComplete(b *buffer.Buffer) ([]string, []string) {
c := b.GetActiveCursor()
input, argstart := b.GetArg()
var suggestions []string
for _, cmd := range PluginCmds {
if strings.HasPrefix(cmd, input) {
suggestions = append(suggestions, cmd)
}
}
sort.Strings(suggestions)
completions := make([]string, len(suggestions))
for i := range suggestions {
completions[i] = util.SliceEndStr(suggestions[i], c.X-argstart)
}
return completions, suggestions
}
// PluginComplete completes values for the plugin command
func PluginComplete(b *buffer.Buffer) ([]string, []string) {
c := b.GetActiveCursor()
l := b.LineBytes(c.Y)
l = util.SliceStart(l, c.X)
input, argstart := b.GetArg()
completeValue := false
args := bytes.Split(l, []byte{' '})
if len(args) >= 2 {
for _, cmd := range PluginCmds {
if cmd == string(args[len(args)-2]) {
completeValue = true
break
}
}
}
if !completeValue {
return PluginCmdComplete(b)
}
var suggestions []string
for _, pl := range config.Plugins {
if strings.HasPrefix(pl.Name, input) {
suggestions = append(suggestions, pl.Name)
}
}
sort.Strings(suggestions)
completions := make([]string, len(suggestions))
for i := range suggestions {
completions[i] = util.SliceEndStr(suggestions[i], c.X-argstart)
}
return completions, suggestions
}
// PluginNameComplete completes with the names of loaded plugins
// func PluginNameComplete(b *buffer.Buffer) ([]string, []string) {
// c := b.GetActiveCursor()
// input, argstart := buffer.GetArg(b)
//
// var suggestions []string
// for _, pp := range config.GetAllPluginPackages(nil) {
// if strings.HasPrefix(pp.Name, input) {
// suggestions = append(suggestions, pp.Name)
// }
// }
//
// sort.Strings(suggestions)
// completions := make([]string, len(suggestions))
// for i := range suggestions {
// completions[i] = util.SliceEndStr(suggestions[i], c.X-argstart)
// }
// return completions, suggestions
// }
// // MakeCompletion registers a function from a plugin for autocomplete commands
// func MakeCompletion(function string) Completion {
// pluginCompletions = append(pluginCompletions, LuaFunctionComplete(function))
// return Completion(-len(pluginCompletions))
// }
```
|
/content/code_sandbox/internal/action/infocomplete.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 2,301
|
```go
// +build linux darwin dragonfly solaris openbsd netbsd freebsd
package action
import (
"syscall"
"github.com/zyedidia/micro/v2/internal/screen"
)
// Suspend sends micro to the background. This is the same as pressing CtrlZ in most unix programs.
// This only works on linux and has no default binding.
// This code was adapted from the suspend code in nsf/godit
func (*BufPane) Suspend() bool {
screenb := screen.TempFini()
// suspend the process
pid := syscall.Getpid()
err := syscall.Kill(pid, syscall.SIGSTOP)
if err != nil {
screen.TermMessage(err)
}
screen.TempStart(screenb)
return false
}
```
|
/content/code_sandbox/internal/action/actions_posix.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 156
|
```go
// +build plan9 nacl windows
package action
func (*BufPane) Suspend() bool {
InfoBar.Error("Suspend is only supported on BSD/Linux")
return false
}
```
|
/content/code_sandbox/internal/action/actions_other.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 41
|
```go
// +build linux darwin dragonfly openbsd_amd64 freebsd
package action
import (
shellquote "github.com/kballard/go-shellquote"
"github.com/zyedidia/micro/v2/internal/shell"
)
// TermEmuSupported is a constant that marks if the terminal emulator is supported
const TermEmuSupported = true
// RunTermEmulator starts a terminal emulator from a bufpane with the given input (command)
// if wait is true it will wait for the user to exit by pressing enter once the executable has terminated
// if getOutput is true it will redirect the stdout of the process to a pipe which will be passed to the
// callback which is a function that takes a string and a list of optional user arguments
func RunTermEmulator(h *BufPane, input string, wait bool, getOutput bool, callback func(out string, userargs []interface{}), userargs []interface{}) error {
args, err := shellquote.Split(input)
if err != nil {
return err
}
if len(args) == 0 {
return nil
}
t := new(shell.Terminal)
err = t.Start(args, getOutput, wait, callback, userargs)
if err != nil {
return err
}
h.AddTab()
id := MainTab().Panes[0].ID()
v := h.GetView()
tp, err := NewTermPane(v.X, v.Y, v.Width, v.Height, t, id, MainTab())
if err != nil {
return err
}
MainTab().Panes[0] = tp
MainTab().SetActive(0)
return nil
}
```
|
/content/code_sandbox/internal/action/terminal_supported.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 347
|
```go
package action
import (
"bytes"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"reflect"
"regexp"
"strconv"
"strings"
shellquote "github.com/kballard/go-shellquote"
"github.com/zyedidia/micro/v2/internal/buffer"
"github.com/zyedidia/micro/v2/internal/clipboard"
"github.com/zyedidia/micro/v2/internal/config"
"github.com/zyedidia/micro/v2/internal/screen"
"github.com/zyedidia/micro/v2/internal/shell"
"github.com/zyedidia/micro/v2/internal/util"
)
// A Command contains information about how to execute a command
// It has the action for that command as well as a completer function
type Command struct {
action func(*BufPane, []string)
completer buffer.Completer
}
var commands map[string]Command
func InitCommands() {
commands = map[string]Command{
"set": {(*BufPane).SetCmd, OptionValueComplete},
"reset": {(*BufPane).ResetCmd, OptionValueComplete},
"setlocal": {(*BufPane).SetLocalCmd, OptionValueComplete},
"show": {(*BufPane).ShowCmd, OptionComplete},
"showkey": {(*BufPane).ShowKeyCmd, nil},
"run": {(*BufPane).RunCmd, nil},
"bind": {(*BufPane).BindCmd, nil},
"unbind": {(*BufPane).UnbindCmd, nil},
"quit": {(*BufPane).QuitCmd, nil},
"goto": {(*BufPane).GotoCmd, nil},
"jump": {(*BufPane).JumpCmd, nil},
"save": {(*BufPane).SaveCmd, nil},
"replace": {(*BufPane).ReplaceCmd, nil},
"replaceall": {(*BufPane).ReplaceAllCmd, nil},
"vsplit": {(*BufPane).VSplitCmd, buffer.FileComplete},
"hsplit": {(*BufPane).HSplitCmd, buffer.FileComplete},
"tab": {(*BufPane).NewTabCmd, buffer.FileComplete},
"help": {(*BufPane).HelpCmd, HelpComplete},
"eval": {(*BufPane).EvalCmd, nil},
"log": {(*BufPane).ToggleLogCmd, nil},
"plugin": {(*BufPane).PluginCmd, PluginComplete},
"reload": {(*BufPane).ReloadCmd, nil},
"reopen": {(*BufPane).ReopenCmd, nil},
"cd": {(*BufPane).CdCmd, buffer.FileComplete},
"pwd": {(*BufPane).PwdCmd, nil},
"open": {(*BufPane).OpenCmd, buffer.FileComplete},
"tabmove": {(*BufPane).TabMoveCmd, nil},
"tabswitch": {(*BufPane).TabSwitchCmd, nil},
"term": {(*BufPane).TermCmd, nil},
"memusage": {(*BufPane).MemUsageCmd, nil},
"retab": {(*BufPane).RetabCmd, nil},
"raw": {(*BufPane).RawCmd, nil},
"textfilter": {(*BufPane).TextFilterCmd, nil},
}
}
// MakeCommand is a function to easily create new commands
// This can be called by plugins in Lua so that plugins can define their own commands
func MakeCommand(name string, action func(bp *BufPane, args []string), completer buffer.Completer) {
if action != nil {
commands[name] = Command{action, completer}
}
}
// CommandEditAction returns a bindable function that opens a prompt with
// the given string and executes the command when the user presses
// enter
func CommandEditAction(prompt string) BufKeyAction {
return func(h *BufPane) bool {
InfoBar.Prompt("> ", prompt, "Command", nil, func(resp string, canceled bool) {
if !canceled {
MainTab().CurPane().HandleCommand(resp)
}
})
return false
}
}
// CommandAction returns a bindable function which executes the
// given command
func CommandAction(cmd string) BufKeyAction {
return func(h *BufPane) bool {
MainTab().CurPane().HandleCommand(cmd)
return false
}
}
var PluginCmds = []string{"install", "remove", "update", "available", "list", "search"}
// PluginCmd installs, removes, updates, lists, or searches for given plugins
func (h *BufPane) PluginCmd(args []string) {
if len(args) < 1 {
InfoBar.Error("Not enough arguments")
return
}
if h.Buf.Type != buffer.BTLog {
h.OpenLogBuf()
}
config.PluginCommand(buffer.LogBuf, args[0], args[1:])
}
// RetabCmd changes all spaces to tabs or all tabs to spaces
// depending on the user's settings
func (h *BufPane) RetabCmd(args []string) {
h.Buf.Retab()
}
// RawCmd opens a new raw view which displays the escape sequences micro
// is receiving in real-time
func (h *BufPane) RawCmd(args []string) {
width, height := screen.Screen.Size()
iOffset := config.GetInfoBarOffset()
tp := NewTabFromPane(0, 0, width, height-iOffset, NewRawPane(nil))
Tabs.AddTab(tp)
Tabs.SetActive(len(Tabs.List) - 1)
}
// TextFilterCmd filters the selection through the command.
// Selection goes to the command input.
// On successful run command output replaces the current selection.
func (h *BufPane) TextFilterCmd(args []string) {
if len(args) == 0 {
InfoBar.Error("usage: textfilter arguments")
return
}
sel := h.Cursor.GetSelection()
if len(sel) == 0 {
h.Cursor.SelectWord()
sel = h.Cursor.GetSelection()
}
var bout, berr bytes.Buffer
cmd := exec.Command(args[0], args[1:]...)
cmd.Stdin = strings.NewReader(string(sel))
cmd.Stderr = &berr
cmd.Stdout = &bout
err := cmd.Run()
if err != nil {
InfoBar.Error(err.Error() + " " + berr.String())
return
}
h.Cursor.DeleteSelection()
h.Buf.Insert(h.Cursor.Loc, bout.String())
}
// TabMoveCmd moves the current tab to a given index (starts at 1). The
// displaced tabs are moved up.
func (h *BufPane) TabMoveCmd(args []string) {
if len(args) <= 0 {
InfoBar.Error("Not enough arguments: provide an index, starting at 1")
return
}
if len(args[0]) <= 0 {
InfoBar.Error("Invalid argument: empty string")
return
}
num, err := strconv.Atoi(args[0])
if err != nil {
InfoBar.Error("Invalid argument: ", err)
return
}
// Preserve sign for relative move, if one exists
var shiftDirection byte
if strings.Contains("-+", string([]byte{args[0][0]})) {
shiftDirection = args[0][0]
}
// Relative positions -> absolute positions
idxFrom := Tabs.Active()
idxTo := 0
offset := util.Abs(num)
if shiftDirection == '-' {
idxTo = idxFrom - offset
} else if shiftDirection == '+' {
idxTo = idxFrom + offset
} else {
idxTo = offset - 1
}
// Restrain position to within the valid range
idxTo = util.Clamp(idxTo, 0, len(Tabs.List)-1)
activeTab := Tabs.List[idxFrom]
Tabs.RemoveTab(activeTab.Panes[0].ID())
Tabs.List = append(Tabs.List, nil)
copy(Tabs.List[idxTo+1:], Tabs.List[idxTo:])
Tabs.List[idxTo] = activeTab
Tabs.UpdateNames()
Tabs.SetActive(idxTo)
// InfoBar.Message(fmt.Sprintf("Moved tab from slot %d to %d", idxFrom+1, idxTo+1))
}
// TabSwitchCmd switches to a given tab either by name or by number
func (h *BufPane) TabSwitchCmd(args []string) {
if len(args) > 0 {
num, err := strconv.Atoi(args[0])
if err != nil {
// Check for tab with this name
found := false
for i, t := range Tabs.List {
if t.Panes[t.active].Name() == args[0] {
Tabs.SetActive(i)
found = true
}
}
if !found {
InfoBar.Error("Could not find tab: ", err)
}
} else {
num--
if num >= 0 && num < len(Tabs.List) {
Tabs.SetActive(num)
} else {
InfoBar.Error("Invalid tab index")
}
}
}
}
// CdCmd changes the current working directory
func (h *BufPane) CdCmd(args []string) {
if len(args) > 0 {
path, err := util.ReplaceHome(args[0])
if err != nil {
InfoBar.Error(err)
return
}
err = os.Chdir(path)
if err != nil {
InfoBar.Error(err)
return
}
wd, _ := os.Getwd()
for _, b := range buffer.OpenBuffers {
if len(b.Path) > 0 {
b.Path, _ = util.MakeRelative(b.AbsPath, wd)
if p, _ := filepath.Abs(b.Path); !strings.Contains(p, wd) {
b.Path = b.AbsPath
}
}
}
}
}
// MemUsageCmd prints micro's memory usage
// Alloc shows how many bytes are currently in use
// Sys shows how many bytes have been requested from the operating system
// NumGC shows how many times the GC has been run
// Note that Go commonly reserves more memory from the OS than is currently in-use/required
// Additionally, even if Go returns memory to the OS, the OS does not always claim it because
// there may be plenty of memory to spare
func (h *BufPane) MemUsageCmd(args []string) {
InfoBar.Message(util.GetMemStats())
}
// PwdCmd prints the current working directory
func (h *BufPane) PwdCmd(args []string) {
wd, err := os.Getwd()
if err != nil {
InfoBar.Message(err.Error())
} else {
InfoBar.Message(wd)
}
}
// OpenCmd opens a new buffer with a given filename
func (h *BufPane) OpenCmd(args []string) {
if len(args) > 0 {
filename := args[0]
// the filename might or might not be quoted, so unquote first then join the strings.
args, err := shellquote.Split(filename)
if err != nil {
InfoBar.Error("Error parsing args ", err)
return
}
if len(args) == 0 {
return
}
filename = strings.Join(args, " ")
open := func() {
b, err := buffer.NewBufferFromFile(filename, buffer.BTDefault)
if err != nil {
InfoBar.Error(err)
return
}
h.OpenBuffer(b)
}
if h.Buf.Modified() {
InfoBar.YNPrompt("Save changes to "+h.Buf.GetName()+" before closing? (y,n,esc)", func(yes, canceled bool) {
if !canceled && !yes {
open()
} else if !canceled && yes {
h.Save()
open()
}
})
} else {
open()
}
} else {
InfoBar.Error("No filename")
}
}
// ToggleLogCmd toggles the log view
func (h *BufPane) ToggleLogCmd(args []string) {
if h.Buf.Type != buffer.BTLog {
h.OpenLogBuf()
} else {
h.Quit()
}
}
// ReloadCmd reloads all files (syntax files, colorschemes, plugins...)
func (h *BufPane) ReloadCmd(args []string) {
reloadRuntime(true)
}
// ReloadConfig reloads only the configuration
func ReloadConfig() {
reloadRuntime(false)
}
func reloadRuntime(reloadPlugins bool) {
if reloadPlugins {
err := config.RunPluginFn("deinit")
if err != nil {
screen.TermMessage(err)
}
}
config.InitRuntimeFiles(true)
if reloadPlugins {
config.InitPlugins()
}
err := config.ReadSettings()
if err != nil {
screen.TermMessage(err)
} else {
parsedSettings := config.ParsedSettings()
defaultSettings := config.DefaultAllSettings()
for k := range defaultSettings {
if _, ok := config.VolatileSettings[k]; ok {
// reload should not override volatile settings
continue
}
if _, ok := parsedSettings[k]; ok {
err = doSetGlobalOptionNative(k, parsedSettings[k])
} else {
err = doSetGlobalOptionNative(k, defaultSettings[k])
}
if err != nil {
screen.TermMessage(err)
}
}
}
if reloadPlugins {
err = config.LoadAllPlugins()
if err != nil {
screen.TermMessage(err)
}
}
InitBindings()
InitCommands()
if reloadPlugins {
err = config.RunPluginFn("preinit")
if err != nil {
screen.TermMessage(err)
}
err = config.RunPluginFn("init")
if err != nil {
screen.TermMessage(err)
}
err = config.RunPluginFn("postinit")
if err != nil {
screen.TermMessage(err)
}
}
err = config.InitColorscheme()
if err != nil {
screen.TermMessage(err)
}
for _, b := range buffer.OpenBuffers {
b.ReloadSettings(true)
}
}
// ReopenCmd reopens the buffer (reload from disk)
func (h *BufPane) ReopenCmd(args []string) {
if h.Buf.Modified() {
InfoBar.YNPrompt("Save file before reopen?", func(yes, canceled bool) {
if !canceled && yes {
h.Save()
h.ReOpen()
} else if !canceled {
h.ReOpen()
}
})
} else {
h.ReOpen()
}
}
func (h *BufPane) openHelp(page string) error {
if data, err := config.FindRuntimeFile(config.RTHelp, page).Data(); err != nil {
return errors.New(fmt.Sprintf("Unable to load help text for %s: %v", page, err))
} else {
helpBuffer := buffer.NewBufferFromString(string(data), page+".md", buffer.BTHelp)
helpBuffer.SetName("Help " + page)
helpBuffer.SetOptionNative("hltaberrors", false)
helpBuffer.SetOptionNative("hltrailingws", false)
if h.Buf.Type == buffer.BTHelp {
h.OpenBuffer(helpBuffer)
} else {
h.HSplitBuf(helpBuffer)
}
}
return nil
}
// HelpCmd tries to open the given help page in a horizontal split
func (h *BufPane) HelpCmd(args []string) {
if len(args) < 1 {
// Open the default help if the user just typed "> help"
h.openHelp("help")
} else {
if config.FindRuntimeFile(config.RTHelp, args[0]) != nil {
err := h.openHelp(args[0])
if err != nil {
InfoBar.Error(err)
}
} else {
InfoBar.Error("Sorry, no help for ", args[0])
}
}
}
// VSplitCmd opens a vertical split with file given in the first argument
// If no file is given, it opens an empty buffer in a new split
func (h *BufPane) VSplitCmd(args []string) {
if len(args) == 0 {
// Open an empty vertical split
h.VSplitAction()
return
}
buf, err := buffer.NewBufferFromFile(args[0], buffer.BTDefault)
if err != nil {
InfoBar.Error(err)
return
}
h.VSplitBuf(buf)
}
// HSplitCmd opens a horizontal split with file given in the first argument
// If no file is given, it opens an empty buffer in a new split
func (h *BufPane) HSplitCmd(args []string) {
if len(args) == 0 {
// Open an empty horizontal split
h.HSplitAction()
return
}
buf, err := buffer.NewBufferFromFile(args[0], buffer.BTDefault)
if err != nil {
InfoBar.Error(err)
return
}
h.HSplitBuf(buf)
}
// EvalCmd evaluates a lua expression
func (h *BufPane) EvalCmd(args []string) {
InfoBar.Error("Eval unsupported")
}
// NewTabCmd opens the given file in a new tab
func (h *BufPane) NewTabCmd(args []string) {
width, height := screen.Screen.Size()
iOffset := config.GetInfoBarOffset()
if len(args) > 0 {
for _, a := range args {
b, err := buffer.NewBufferFromFile(a, buffer.BTDefault)
if err != nil {
InfoBar.Error(err)
return
}
tp := NewTabFromBuffer(0, 0, width, height-1-iOffset, b)
Tabs.AddTab(tp)
Tabs.SetActive(len(Tabs.List) - 1)
}
} else {
b := buffer.NewBufferFromString("", "", buffer.BTDefault)
tp := NewTabFromBuffer(0, 0, width, height-iOffset, b)
Tabs.AddTab(tp)
Tabs.SetActive(len(Tabs.List) - 1)
}
}
func doSetGlobalOptionNative(option string, nativeValue interface{}) error {
if reflect.DeepEqual(config.GlobalSettings[option], nativeValue) {
return nil
}
config.GlobalSettings[option] = nativeValue
config.ModifiedSettings[option] = true
delete(config.VolatileSettings, option)
if option == "colorscheme" {
// LoadSyntaxFiles()
config.InitColorscheme()
for _, b := range buffer.OpenBuffers {
b.UpdateRules()
}
} else if option == "infobar" || option == "keymenu" {
Tabs.Resize()
} else if option == "mouse" {
if !nativeValue.(bool) {
screen.Screen.DisableMouse()
} else {
screen.Screen.EnableMouse()
}
} else if option == "autosave" {
if nativeValue.(float64) > 0 {
config.SetAutoTime(nativeValue.(float64))
} else {
config.SetAutoTime(0)
}
} else if option == "paste" {
screen.Screen.SetPaste(nativeValue.(bool))
} else if option == "clipboard" {
m := clipboard.SetMethod(nativeValue.(string))
err := clipboard.Initialize(m)
if err != nil {
return err
}
} else {
for _, pl := range config.Plugins {
if option == pl.Name {
if nativeValue.(bool) && !pl.Loaded {
pl.Load()
_, err := pl.Call("init")
if err != nil && err != config.ErrNoSuchFunction {
screen.TermMessage(err)
}
} else if !nativeValue.(bool) && pl.Loaded {
_, err := pl.Call("deinit")
if err != nil && err != config.ErrNoSuchFunction {
screen.TermMessage(err)
}
}
}
}
}
return nil
}
func SetGlobalOptionNative(option string, nativeValue interface{}) error {
if err := config.OptionIsValid(option, nativeValue); err != nil {
return err
}
// check for local option first...
for _, s := range config.LocalSettings {
if s == option {
return MainTab().CurPane().Buf.SetOptionNative(option, nativeValue)
}
}
// ...if it's not local continue with the globals...
if err := doSetGlobalOptionNative(option, nativeValue); err != nil {
return err
}
// ...at last check the buffer locals
for _, b := range buffer.OpenBuffers {
b.DoSetOptionNative(option, nativeValue)
delete(b.LocalSettings, option)
}
return config.WriteSettings(filepath.Join(config.ConfigDir, "settings.json"))
}
func SetGlobalOption(option, value string) error {
if _, ok := config.GlobalSettings[option]; !ok {
return config.ErrInvalidOption
}
nativeValue, err := config.GetNativeValue(option, config.GlobalSettings[option], value)
if err != nil {
return err
}
return SetGlobalOptionNative(option, nativeValue)
}
// ResetCmd resets a setting to its default value
func (h *BufPane) ResetCmd(args []string) {
if len(args) < 1 {
InfoBar.Error("Not enough arguments")
return
}
option := args[0]
defaults := config.DefaultAllSettings()
if _, ok := defaults[option]; ok {
SetGlobalOptionNative(option, defaults[option])
return
}
InfoBar.Error(config.ErrInvalidOption)
}
// SetCmd sets an option
func (h *BufPane) SetCmd(args []string) {
if len(args) < 2 {
InfoBar.Error("Not enough arguments")
return
}
option := args[0]
value := args[1]
err := SetGlobalOption(option, value)
if err == config.ErrInvalidOption {
err := h.Buf.SetOption(option, value)
if err != nil {
InfoBar.Error(err)
}
} else if err != nil {
InfoBar.Error(err)
}
}
// SetLocalCmd sets an option local to the buffer
func (h *BufPane) SetLocalCmd(args []string) {
if len(args) < 2 {
InfoBar.Error("Not enough arguments")
return
}
option := args[0]
value := args[1]
err := h.Buf.SetOption(option, value)
if err != nil {
InfoBar.Error(err)
}
}
// ShowCmd shows the value of the given option
func (h *BufPane) ShowCmd(args []string) {
if len(args) < 1 {
InfoBar.Error("Please provide an option to show")
return
}
var option interface{}
if opt, ok := h.Buf.Settings[args[0]]; ok {
option = opt
} else if opt, ok := config.GlobalSettings[args[0]]; ok {
option = opt
}
if option == nil {
InfoBar.Error(args[0], " is not a valid option")
return
}
InfoBar.Message(option)
}
func parseKeyArg(arg string) string {
// If this is a raw escape sequence, convert it to its raw byte form
return strings.ReplaceAll(arg, "\\x1b", "\x1b")
}
// ShowKeyCmd displays the action that a key is bound to
func (h *BufPane) ShowKeyCmd(args []string) {
if len(args) < 1 {
InfoBar.Error("Please provide a key to show")
return
}
event, err := findEvent(parseKeyArg(args[0]))
if err != nil {
InfoBar.Error(err)
return
}
if action, ok := config.Bindings["buffer"][event.Name()]; ok {
InfoBar.Message(action)
} else {
InfoBar.Message(args[0], " has no binding")
}
}
// BindCmd creates a new keybinding
func (h *BufPane) BindCmd(args []string) {
if len(args) < 2 {
InfoBar.Error("Not enough arguments")
return
}
_, err := TryBindKey(parseKeyArg(args[0]), args[1], true)
if err != nil {
InfoBar.Error(err)
}
}
// UnbindCmd binds a key to its default action
func (h *BufPane) UnbindCmd(args []string) {
if len(args) < 1 {
InfoBar.Error("Not enough arguments")
return
}
err := UnbindKey(parseKeyArg(args[0]))
if err != nil {
InfoBar.Error(err)
}
}
// RunCmd runs a shell command in the background
func (h *BufPane) RunCmd(args []string) {
runf, err := shell.RunBackgroundShell(shellquote.Join(args...))
if err != nil {
InfoBar.Error(err)
} else {
go func() {
InfoBar.Message(runf())
screen.Redraw()
}()
}
}
// QuitCmd closes the main view
func (h *BufPane) QuitCmd(args []string) {
h.Quit()
}
// GotoCmd is a command that will send the cursor to a certain
// position in the buffer
// For example: `goto line`, or `goto line:col`
func (h *BufPane) GotoCmd(args []string) {
line, col, err := h.parseLineCol(args)
if err != nil {
InfoBar.Error(err)
return
}
if line < 0 {
line = h.Buf.LinesNum() + 1 + line
}
line = util.Clamp(line-1, 0, h.Buf.LinesNum()-1)
col = util.Clamp(col-1, 0, util.CharacterCount(h.Buf.LineBytes(line)))
h.RemoveAllMultiCursors()
h.Cursor.Deselect(true)
h.GotoLoc(buffer.Loc{col, line})
}
// JumpCmd is a command that will send the cursor to a certain relative
// position in the buffer
// For example: `jump line`, `jump -line`, or `jump -line:col`
func (h *BufPane) JumpCmd(args []string) {
line, col, err := h.parseLineCol(args)
if err != nil {
InfoBar.Error(err)
return
}
line = h.Buf.GetActiveCursor().Y + 1 + line
line = util.Clamp(line-1, 0, h.Buf.LinesNum()-1)
col = util.Clamp(col-1, 0, util.CharacterCount(h.Buf.LineBytes(line)))
h.RemoveAllMultiCursors()
h.Cursor.Deselect(true)
h.GotoLoc(buffer.Loc{col, line})
}
// parseLineCol is a helper to parse the input of GotoCmd and JumpCmd
func (h *BufPane) parseLineCol(args []string) (line int, col int, err error) {
if len(args) <= 0 {
return 0, 0, errors.New("Not enough arguments")
}
line, col = 0, 0
if strings.Contains(args[0], ":") {
parts := strings.SplitN(args[0], ":", 2)
line, err = strconv.Atoi(parts[0])
if err != nil {
return 0, 0, err
}
col, err = strconv.Atoi(parts[1])
if err != nil {
return 0, 0, err
}
} else {
line, err = strconv.Atoi(args[0])
if err != nil {
return 0, 0, err
}
}
return line, col, nil
}
// SaveCmd saves the buffer optionally with an argument file name
func (h *BufPane) SaveCmd(args []string) {
if len(args) == 0 {
h.Save()
} else {
h.Buf.SaveAs(args[0])
}
}
// ReplaceCmd runs search and replace
func (h *BufPane) ReplaceCmd(args []string) {
if len(args) < 2 || len(args) > 4 {
// We need to find both a search and replace expression
InfoBar.Error("Invalid replace statement: " + strings.Join(args, " "))
return
}
all := false
noRegex := false
foundSearch := false
foundReplace := false
var search string
var replaceStr string
for _, arg := range args {
switch arg {
case "-a":
all = true
case "-l":
noRegex = true
default:
if !foundSearch {
foundSearch = true
search = arg
} else if !foundReplace {
foundReplace = true
replaceStr = arg
} else {
InfoBar.Error("Invalid flag: " + arg)
return
}
}
}
if noRegex {
search = regexp.QuoteMeta(search)
}
replace := []byte(replaceStr)
var regex *regexp.Regexp
var err error
if h.Buf.Settings["ignorecase"].(bool) {
regex, err = regexp.Compile("(?im)" + search)
} else {
regex, err = regexp.Compile("(?m)" + search)
}
if err != nil {
// There was an error with the user's regex
InfoBar.Error(err)
return
}
nreplaced := 0
start := h.Buf.Start()
end := h.Buf.End()
selection := h.Cursor.HasSelection()
if selection {
start = h.Cursor.CurSelection[0]
end = h.Cursor.CurSelection[1]
}
if all {
nreplaced, _ = h.Buf.ReplaceRegex(start, end, regex, replace, !noRegex)
} else {
inRange := func(l buffer.Loc) bool {
return l.GreaterEqual(start) && l.LessEqual(end)
}
searchLoc := h.Cursor.Loc
var doReplacement func()
doReplacement = func() {
locs, found, err := h.Buf.FindNext(search, start, end, searchLoc, true, true)
if err != nil {
InfoBar.Error(err)
return
}
if !found || !inRange(locs[0]) || !inRange(locs[1]) {
h.Cursor.ResetSelection()
h.Buf.RelocateCursors()
return
}
h.Cursor.SetSelectionStart(locs[0])
h.Cursor.SetSelectionEnd(locs[1])
h.GotoLoc(locs[0])
h.Buf.LastSearch = search
h.Buf.LastSearchRegex = true
h.Buf.HighlightSearch = h.Buf.Settings["hlsearch"].(bool)
InfoBar.YNPrompt("Perform replacement (y,n,esc)", func(yes, canceled bool) {
if !canceled && yes {
_, nrunes := h.Buf.ReplaceRegex(locs[0], locs[1], regex, replace, !noRegex)
searchLoc = locs[0]
searchLoc.X += nrunes + locs[0].Diff(locs[1], h.Buf)
if end.Y == locs[1].Y {
end = end.Move(nrunes, h.Buf)
}
h.Cursor.Loc = searchLoc
nreplaced++
} else if !canceled && !yes {
searchLoc = locs[1]
} else if canceled {
h.Cursor.ResetSelection()
h.Buf.RelocateCursors()
return
}
doReplacement()
})
}
doReplacement()
}
h.Buf.RelocateCursors()
h.Relocate()
var s string
if nreplaced > 1 {
s = fmt.Sprintf("Replaced %d occurrences of %s", nreplaced, search)
} else if nreplaced == 1 {
s = fmt.Sprintf("Replaced 1 occurrence of %s", search)
} else {
s = fmt.Sprintf("Nothing matched %s", search)
}
if selection {
s += " in selection"
}
InfoBar.Message(s)
}
// ReplaceAllCmd replaces search term all at once
func (h *BufPane) ReplaceAllCmd(args []string) {
// aliased to Replace command
h.ReplaceCmd(append(args, "-a"))
}
// TermCmd opens a terminal in the current view
func (h *BufPane) TermCmd(args []string) {
ps := h.tab.Panes
if !TermEmuSupported {
InfoBar.Error("Terminal emulator not supported on this system")
return
}
if len(args) == 0 {
sh := os.Getenv("SHELL")
if sh == "" {
InfoBar.Error("Shell environment not found")
return
}
args = []string{sh}
}
term := func(i int, newtab bool) {
t := new(shell.Terminal)
err := t.Start(args, false, true, nil, nil)
if err != nil {
InfoBar.Error(err)
return
}
id := h.ID()
if newtab {
h.AddTab()
i = 0
id = MainTab().Panes[0].ID()
} else {
MainTab().Panes[i].Close()
}
v := h.GetView()
tp, err := NewTermPane(v.X, v.Y, v.Width, v.Height, t, id, MainTab())
if err != nil {
InfoBar.Error(err)
return
}
MainTab().Panes[i] = tp
MainTab().SetActive(i)
}
// If there is only one open file we make a new tab instead of overwriting it
newtab := len(MainTab().Panes) == 1 && len(Tabs.List) == 1
if newtab {
term(0, true)
return
}
for i, p := range ps {
if p.ID() == h.ID() {
if h.Buf.Modified() {
InfoBar.YNPrompt("Save changes to "+h.Buf.GetName()+" before closing? (y,n,esc)", func(yes, canceled bool) {
if !canceled && !yes {
term(i, false)
} else if !canceled && yes {
h.Save()
term(i, false)
}
})
} else {
term(i, false)
}
}
}
}
// HandleCommand handles input from the user
func (h *BufPane) HandleCommand(input string) {
args, err := shellquote.Split(input)
if err != nil {
InfoBar.Error("Error parsing args ", err)
return
}
if len(args) == 0 {
return
}
inputCmd := args[0]
if _, ok := commands[inputCmd]; !ok {
InfoBar.Error("Unknown command ", inputCmd)
} else {
WriteLog("> " + input + "\n")
commands[inputCmd].action(h, args[1:])
WriteLog("\n")
}
}
```
|
/content/code_sandbox/internal/action/command.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 7,714
|
```go
package action
import (
"fmt"
"reflect"
"github.com/zyedidia/micro/v2/internal/buffer"
"github.com/zyedidia/micro/v2/internal/display"
"github.com/zyedidia/tcell/v2"
)
type RawPane struct {
*BufPane
}
func NewRawPaneFromWin(b *buffer.Buffer, win display.BWindow, tab *Tab) *RawPane {
rh := new(RawPane)
rh.BufPane = NewBufPane(b, win, tab)
return rh
}
func NewRawPane(tab *Tab) *RawPane {
b := buffer.NewBufferFromString("", "", buffer.BTRaw)
w := display.NewBufWindow(0, 0, 0, 0, b)
return NewRawPaneFromWin(b, w, tab)
}
func (h *RawPane) HandleEvent(event tcell.Event) {
switch e := event.(type) {
case *tcell.EventKey:
if e.Key() == tcell.KeyCtrlQ {
h.Quit()
}
}
h.Buf.Insert(h.Cursor.Loc, reflect.TypeOf(event).String()[7:])
e, err := ConstructEvent(event)
if err == nil {
h.Buf.Insert(h.Cursor.Loc, fmt.Sprintf(": %s", e.Name()))
}
h.Buf.Insert(h.Cursor.Loc, fmt.Sprintf(": %q\n", event.EscSeq()))
h.Relocate()
}
```
|
/content/code_sandbox/internal/action/rawpane.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 304
|
```go
package action
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"strings"
"unicode"
"github.com/zyedidia/json5"
"github.com/zyedidia/micro/v2/internal/config"
"github.com/zyedidia/micro/v2/internal/screen"
"github.com/zyedidia/tcell/v2"
)
var Binder = map[string]func(e Event, action string){
"command": InfoMapEvent,
"buffer": BufMapEvent,
"terminal": TermMapEvent,
}
func createBindingsIfNotExist(fname string) {
if _, e := os.Stat(fname); os.IsNotExist(e) {
ioutil.WriteFile(fname, []byte("{}"), 0644)
}
}
// InitBindings intializes the bindings map by reading from bindings.json
func InitBindings() {
var parsed map[string]interface{}
filename := filepath.Join(config.ConfigDir, "bindings.json")
createBindingsIfNotExist(filename)
if _, e := os.Stat(filename); e == nil {
input, err := ioutil.ReadFile(filename)
if err != nil {
screen.TermMessage("Error reading bindings.json file: " + err.Error())
return
}
err = json5.Unmarshal(input, &parsed)
if err != nil {
screen.TermMessage("Error reading bindings.json:", err.Error())
}
}
for p, bind := range Binder {
defaults := DefaultBindings(p)
for k, v := range defaults {
BindKey(k, v, bind)
}
}
for k, v := range parsed {
switch val := v.(type) {
case string:
BindKey(k, val, Binder["buffer"])
case map[string]interface{}:
bind, ok := Binder[k]
if !ok || bind == nil {
screen.TermMessage(fmt.Sprintf("%s is not a valid pane type", k))
continue
}
for e, a := range val {
s, ok := a.(string)
if !ok {
screen.TermMessage("Error reading bindings.json: non-string and non-map entry", k)
} else {
BindKey(e, s, bind)
}
}
default:
screen.TermMessage("Error reading bindings.json: non-string and non-map entry", k)
}
}
}
func BindKey(k, v string, bind func(e Event, a string)) {
event, err := findEvent(k)
if err != nil {
screen.TermMessage(err)
return
}
if strings.HasPrefix(k, "\x1b") {
screen.Screen.RegisterRawSeq(k)
}
bind(event, v)
// switch e := event.(type) {
// case KeyEvent:
// InfoMapKey(e, v)
// case KeySequenceEvent:
// InfoMapKey(e, v)
// case MouseEvent:
// InfoMapMouse(e, v)
// case RawEvent:
// InfoMapKey(e, v)
// }
}
var r = regexp.MustCompile("<(.+?)>")
func findEvents(k string) (b KeySequenceEvent, ok bool, err error) {
var events []Event = nil
for len(k) > 0 {
groups := r.FindStringSubmatchIndex(k)
if len(groups) > 3 {
if events == nil {
events = make([]Event, 0, 3)
}
e, ok := findSingleEvent(k[groups[2]:groups[3]])
if !ok {
return KeySequenceEvent{}, false, errors.New("Invalid event " + k[groups[2]:groups[3]])
}
events = append(events, e)
k = k[groups[3]+1:]
} else {
return KeySequenceEvent{}, false, nil
}
}
return KeySequenceEvent{events}, true, nil
}
// findSingleEvent will find binding Key 'b' using string 'k'
func findSingleEvent(k string) (b Event, ok bool) {
modifiers := tcell.ModNone
// First, we'll strip off all the modifiers in the name and add them to the
// ModMask
modSearch:
for {
switch {
case strings.HasPrefix(k, "-") && k != "-":
// We optionally support dashes between modifiers
k = k[1:]
case strings.HasPrefix(k, "Ctrl") && k != "CtrlH":
// CtrlH technically does not have a 'Ctrl' modifier because it is really backspace
k = k[4:]
modifiers |= tcell.ModCtrl
case strings.HasPrefix(k, "Alt"):
k = k[3:]
modifiers |= tcell.ModAlt
case strings.HasPrefix(k, "Shift"):
k = k[5:]
modifiers |= tcell.ModShift
case strings.HasPrefix(k, "\x1b"):
return RawEvent{
esc: k,
}, true
default:
break modSearch
}
}
if k == "" {
return KeyEvent{}, false
}
// Control is handled in a special way, since the terminal sends explicitly
// marked escape sequences for control keys
// We should check for Control keys first
if modifiers&tcell.ModCtrl != 0 {
// see if the key is in bindingKeys with the Ctrl prefix.
k = string(unicode.ToUpper(rune(k[0]))) + k[1:]
if code, ok := keyEvents["Ctrl"+k]; ok {
return KeyEvent{
code: code,
mod: modifiers,
}, true
}
}
// See if we can find the key in bindingKeys
if code, ok := keyEvents[k]; ok {
return KeyEvent{
code: code,
mod: modifiers,
}, true
}
var mstate MouseState = MousePress
if strings.HasSuffix(k, "Drag") {
k = k[:len(k)-4]
mstate = MouseDrag
} else if strings.HasSuffix(k, "Release") {
k = k[:len(k)-7]
mstate = MouseRelease
}
// See if we can find the key in bindingMouse
if code, ok := mouseEvents[k]; ok {
return MouseEvent{
btn: code,
mod: modifiers,
state: mstate,
}, true
}
// If we were given one character, then we've got a rune.
if len(k) == 1 {
return KeyEvent{
code: tcell.KeyRune,
mod: modifiers,
r: rune(k[0]),
}, true
}
// We don't know what happened.
return KeyEvent{}, false
}
func findEvent(k string) (Event, error) {
var event Event
event, ok, err := findEvents(k)
if err != nil {
return nil, err
}
if !ok {
event, ok = findSingleEvent(k)
if !ok {
return nil, errors.New(k + " is not a bindable event")
}
}
return event, nil
}
func eventsEqual(e1 Event, e2 Event) bool {
seq1, ok1 := e1.(KeySequenceEvent)
seq2, ok2 := e2.(KeySequenceEvent)
if ok1 && ok2 {
if len(seq1.keys) != len(seq2.keys) {
return false
}
for i := 0; i < len(seq1.keys); i++ {
if seq1.keys[i] != seq2.keys[i] {
return false
}
}
return true
}
return e1 == e2
}
// TryBindKey tries to bind a key by writing to config.ConfigDir/bindings.json
// Returns true if the keybinding already existed and a possible error
func TryBindKey(k, v string, overwrite bool) (bool, error) {
var e error
var parsed map[string]interface{}
filename := filepath.Join(config.ConfigDir, "bindings.json")
createBindingsIfNotExist(filename)
if _, e = os.Stat(filename); e == nil {
input, err := ioutil.ReadFile(filename)
if err != nil {
return false, errors.New("Error reading bindings.json file: " + err.Error())
}
err = json5.Unmarshal(input, &parsed)
if err != nil {
return false, errors.New("Error reading bindings.json: " + err.Error())
}
key, err := findEvent(k)
if err != nil {
return false, err
}
found := false
var ev string
for ev = range parsed {
if e, err := findEvent(ev); err == nil {
if eventsEqual(e, key) {
found = true
break
}
}
}
if found {
if overwrite {
parsed[ev] = v
} else {
return true, nil
}
} else {
parsed[k] = v
}
BindKey(k, v, Binder["buffer"])
txt, _ := json.MarshalIndent(parsed, "", " ")
return true, ioutil.WriteFile(filename, append(txt, '\n'), 0644)
}
return false, e
}
// UnbindKey removes the binding for a key from the bindings.json file
func UnbindKey(k string) error {
var e error
var parsed map[string]interface{}
filename := filepath.Join(config.ConfigDir, "bindings.json")
createBindingsIfNotExist(filename)
if _, e = os.Stat(filename); e == nil {
input, err := ioutil.ReadFile(filename)
if err != nil {
return errors.New("Error reading bindings.json file: " + err.Error())
}
err = json5.Unmarshal(input, &parsed)
if err != nil {
return errors.New("Error reading bindings.json: " + err.Error())
}
key, err := findEvent(k)
if err != nil {
return err
}
for ev := range parsed {
if e, err := findEvent(ev); err == nil {
if eventsEqual(e, key) {
delete(parsed, ev)
break
}
}
}
if strings.HasPrefix(k, "\x1b") {
screen.Screen.UnregisterRawSeq(k)
}
defaults := DefaultBindings("buffer")
if a, ok := defaults[k]; ok {
BindKey(k, a, Binder["buffer"])
} else if _, ok := config.Bindings["buffer"][k]; ok {
BufUnmap(key)
delete(config.Bindings["buffer"], k)
}
txt, _ := json.MarshalIndent(parsed, "", " ")
return ioutil.WriteFile(filename, append(txt, '\n'), 0644)
}
return e
}
var mouseEvents = map[string]tcell.ButtonMask{
"MouseLeft": tcell.ButtonPrimary,
"MouseMiddle": tcell.ButtonMiddle,
"MouseRight": tcell.ButtonSecondary,
"MouseWheelUp": tcell.WheelUp,
"MouseWheelDown": tcell.WheelDown,
"MouseWheelLeft": tcell.WheelLeft,
"MouseWheelRight": tcell.WheelRight,
}
var keyEvents = map[string]tcell.Key{
"Up": tcell.KeyUp,
"Down": tcell.KeyDown,
"Right": tcell.KeyRight,
"Left": tcell.KeyLeft,
"UpLeft": tcell.KeyUpLeft,
"UpRight": tcell.KeyUpRight,
"DownLeft": tcell.KeyDownLeft,
"DownRight": tcell.KeyDownRight,
"Center": tcell.KeyCenter,
"PageUp": tcell.KeyPgUp,
"PageDown": tcell.KeyPgDn,
"Home": tcell.KeyHome,
"End": tcell.KeyEnd,
"Insert": tcell.KeyInsert,
"Delete": tcell.KeyDelete,
"Help": tcell.KeyHelp,
"Exit": tcell.KeyExit,
"Clear": tcell.KeyClear,
"Cancel": tcell.KeyCancel,
"Print": tcell.KeyPrint,
"Pause": tcell.KeyPause,
"Backtab": tcell.KeyBacktab,
"F1": tcell.KeyF1,
"F2": tcell.KeyF2,
"F3": tcell.KeyF3,
"F4": tcell.KeyF4,
"F5": tcell.KeyF5,
"F6": tcell.KeyF6,
"F7": tcell.KeyF7,
"F8": tcell.KeyF8,
"F9": tcell.KeyF9,
"F10": tcell.KeyF10,
"F11": tcell.KeyF11,
"F12": tcell.KeyF12,
"F13": tcell.KeyF13,
"F14": tcell.KeyF14,
"F15": tcell.KeyF15,
"F16": tcell.KeyF16,
"F17": tcell.KeyF17,
"F18": tcell.KeyF18,
"F19": tcell.KeyF19,
"F20": tcell.KeyF20,
"F21": tcell.KeyF21,
"F22": tcell.KeyF22,
"F23": tcell.KeyF23,
"F24": tcell.KeyF24,
"F25": tcell.KeyF25,
"F26": tcell.KeyF26,
"F27": tcell.KeyF27,
"F28": tcell.KeyF28,
"F29": tcell.KeyF29,
"F30": tcell.KeyF30,
"F31": tcell.KeyF31,
"F32": tcell.KeyF32,
"F33": tcell.KeyF33,
"F34": tcell.KeyF34,
"F35": tcell.KeyF35,
"F36": tcell.KeyF36,
"F37": tcell.KeyF37,
"F38": tcell.KeyF38,
"F39": tcell.KeyF39,
"F40": tcell.KeyF40,
"F41": tcell.KeyF41,
"F42": tcell.KeyF42,
"F43": tcell.KeyF43,
"F44": tcell.KeyF44,
"F45": tcell.KeyF45,
"F46": tcell.KeyF46,
"F47": tcell.KeyF47,
"F48": tcell.KeyF48,
"F49": tcell.KeyF49,
"F50": tcell.KeyF50,
"F51": tcell.KeyF51,
"F52": tcell.KeyF52,
"F53": tcell.KeyF53,
"F54": tcell.KeyF54,
"F55": tcell.KeyF55,
"F56": tcell.KeyF56,
"F57": tcell.KeyF57,
"F58": tcell.KeyF58,
"F59": tcell.KeyF59,
"F60": tcell.KeyF60,
"F61": tcell.KeyF61,
"F62": tcell.KeyF62,
"F63": tcell.KeyF63,
"F64": tcell.KeyF64,
"CtrlSpace": tcell.KeyCtrlSpace,
"CtrlA": tcell.KeyCtrlA,
"CtrlB": tcell.KeyCtrlB,
"CtrlC": tcell.KeyCtrlC,
"CtrlD": tcell.KeyCtrlD,
"CtrlE": tcell.KeyCtrlE,
"CtrlF": tcell.KeyCtrlF,
"CtrlG": tcell.KeyCtrlG,
"CtrlH": tcell.KeyCtrlH,
"CtrlI": tcell.KeyCtrlI,
"CtrlJ": tcell.KeyCtrlJ,
"CtrlK": tcell.KeyCtrlK,
"CtrlL": tcell.KeyCtrlL,
"CtrlM": tcell.KeyCtrlM,
"CtrlN": tcell.KeyCtrlN,
"CtrlO": tcell.KeyCtrlO,
"CtrlP": tcell.KeyCtrlP,
"CtrlQ": tcell.KeyCtrlQ,
"CtrlR": tcell.KeyCtrlR,
"CtrlS": tcell.KeyCtrlS,
"CtrlT": tcell.KeyCtrlT,
"CtrlU": tcell.KeyCtrlU,
"CtrlV": tcell.KeyCtrlV,
"CtrlW": tcell.KeyCtrlW,
"CtrlX": tcell.KeyCtrlX,
"CtrlY": tcell.KeyCtrlY,
"CtrlZ": tcell.KeyCtrlZ,
"CtrlLeftSq": tcell.KeyCtrlLeftSq,
"CtrlBackslash": tcell.KeyCtrlBackslash,
"CtrlRightSq": tcell.KeyCtrlRightSq,
"CtrlCarat": tcell.KeyCtrlCarat,
"CtrlUnderscore": tcell.KeyCtrlUnderscore,
"Tab": tcell.KeyTab,
"Esc": tcell.KeyEsc,
"Escape": tcell.KeyEscape,
"Enter": tcell.KeyEnter,
"Backspace": tcell.KeyBackspace2,
"OldBackspace": tcell.KeyBackspace,
// I renamed these keys to PageUp and PageDown but I don't want to break someone's keybindings
"PgUp": tcell.KeyPgUp,
"PgDown": tcell.KeyPgDn,
}
```
|
/content/code_sandbox/internal/action/bindings.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 3,910
|
```go
package action
import (
"errors"
"fmt"
"io/fs"
"os"
"regexp"
"runtime"
"strings"
"time"
shellquote "github.com/kballard/go-shellquote"
"github.com/zyedidia/micro/v2/internal/buffer"
"github.com/zyedidia/micro/v2/internal/clipboard"
"github.com/zyedidia/micro/v2/internal/config"
"github.com/zyedidia/micro/v2/internal/display"
"github.com/zyedidia/micro/v2/internal/screen"
"github.com/zyedidia/micro/v2/internal/shell"
"github.com/zyedidia/micro/v2/internal/util"
"github.com/zyedidia/tcell/v2"
)
// ScrollUp is not an action
func (h *BufPane) ScrollUp(n int) {
v := h.GetView()
v.StartLine = h.Scroll(v.StartLine, -n)
h.SetView(v)
}
// ScrollDown is not an action
func (h *BufPane) ScrollDown(n int) {
v := h.GetView()
v.StartLine = h.Scroll(v.StartLine, n)
h.SetView(v)
}
// ScrollAdjust can be used to shift the view so that the last line is at the
// bottom if the user has scrolled past the last line.
func (h *BufPane) ScrollAdjust() {
v := h.GetView()
end := h.SLocFromLoc(h.Buf.End())
if h.Diff(v.StartLine, end) < h.BufView().Height-1 {
v.StartLine = h.Scroll(end, -h.BufView().Height+1)
}
h.SetView(v)
}
// MousePress is the event that should happen when a normal click happens
// This is almost always bound to left click
func (h *BufPane) MousePress(e *tcell.EventMouse) bool {
b := h.Buf
mx, my := e.Position()
// ignore click on the status line
if my >= h.BufView().Y+h.BufView().Height {
return false
}
mouseLoc := h.LocFromVisual(buffer.Loc{mx, my})
h.Cursor.Loc = mouseLoc
if b.NumCursors() > 1 {
b.ClearCursors()
h.Relocate()
h.Cursor = h.Buf.GetActiveCursor()
h.Cursor.Loc = mouseLoc
}
if time.Since(h.lastClickTime)/time.Millisecond < config.DoubleClickThreshold && (mouseLoc.X == h.lastLoc.X && mouseLoc.Y == h.lastLoc.Y) {
if h.doubleClick {
// Triple click
h.lastClickTime = time.Now()
h.tripleClick = true
h.doubleClick = false
h.Cursor.SelectLine()
h.Cursor.CopySelection(clipboard.PrimaryReg)
} else {
// Double click
h.lastClickTime = time.Now()
h.doubleClick = true
h.tripleClick = false
h.Cursor.SelectWord()
h.Cursor.CopySelection(clipboard.PrimaryReg)
}
} else {
h.doubleClick = false
h.tripleClick = false
h.lastClickTime = time.Now()
h.Cursor.OrigSelection[0] = h.Cursor.Loc
h.Cursor.CurSelection[0] = h.Cursor.Loc
h.Cursor.CurSelection[1] = h.Cursor.Loc
}
h.Cursor.StoreVisualX()
h.lastLoc = mouseLoc
h.Relocate()
return true
}
func (h *BufPane) MouseDrag(e *tcell.EventMouse) bool {
mx, my := e.Position()
// ignore drag on the status line
if my >= h.BufView().Y+h.BufView().Height {
return false
}
h.Cursor.Loc = h.LocFromVisual(buffer.Loc{mx, my})
if h.tripleClick {
h.Cursor.AddLineToSelection()
} else if h.doubleClick {
h.Cursor.AddWordToSelection()
} else {
h.Cursor.SelectTo(h.Cursor.Loc)
}
h.Cursor.StoreVisualX()
h.Relocate()
return true
}
func (h *BufPane) MouseRelease(e *tcell.EventMouse) bool {
// We could finish the selection based on the release location as in the
// commented out code below, to allow text selections even in a terminal
// that doesn't support mouse motion events. But when the mouse click is
// within the scroll margin, that would cause a scroll and selection
// even for a simple mouse click, which is not good.
// if !h.doubleClick && !h.tripleClick {
// mx, my := e.Position()
// h.Cursor.Loc = h.LocFromVisual(buffer.Loc{mx, my})
// h.Cursor.SetSelectionEnd(h.Cursor.Loc)
// }
if h.Cursor.HasSelection() {
h.Cursor.CopySelection(clipboard.PrimaryReg)
}
return true
}
// ScrollUpAction scrolls the view up
func (h *BufPane) ScrollUpAction() bool {
h.ScrollUp(util.IntOpt(h.Buf.Settings["scrollspeed"]))
return true
}
// ScrollDownAction scrolls the view up
func (h *BufPane) ScrollDownAction() bool {
h.ScrollDown(util.IntOpt(h.Buf.Settings["scrollspeed"]))
return true
}
// Center centers the view on the cursor
func (h *BufPane) Center() bool {
v := h.GetView()
v.StartLine = h.Scroll(h.SLocFromLoc(h.Cursor.Loc), -h.BufView().Height/2)
h.SetView(v)
h.ScrollAdjust()
return true
}
// MoveCursorUp is not an action
func (h *BufPane) MoveCursorUp(n int) {
if !h.Buf.Settings["softwrap"].(bool) {
h.Cursor.UpN(n)
} else {
vloc := h.VLocFromLoc(h.Cursor.Loc)
sloc := h.Scroll(vloc.SLoc, -n)
if sloc == vloc.SLoc {
// we are at the beginning of buffer
h.Cursor.Loc = h.Buf.Start()
h.Cursor.LastVisualX = 0
} else {
vloc.SLoc = sloc
vloc.VisualX = h.Cursor.LastVisualX
h.Cursor.Loc = h.LocFromVLoc(vloc)
}
}
}
// MoveCursorDown is not an action
func (h *BufPane) MoveCursorDown(n int) {
if !h.Buf.Settings["softwrap"].(bool) {
h.Cursor.DownN(n)
} else {
vloc := h.VLocFromLoc(h.Cursor.Loc)
sloc := h.Scroll(vloc.SLoc, n)
if sloc == vloc.SLoc {
// we are at the end of buffer
h.Cursor.Loc = h.Buf.End()
vloc = h.VLocFromLoc(h.Cursor.Loc)
h.Cursor.LastVisualX = vloc.VisualX
} else {
vloc.SLoc = sloc
vloc.VisualX = h.Cursor.LastVisualX
h.Cursor.Loc = h.LocFromVLoc(vloc)
}
}
}
// CursorUp moves the cursor up
func (h *BufPane) CursorUp() bool {
h.Cursor.Deselect(true)
h.MoveCursorUp(1)
h.Relocate()
return true
}
// CursorDown moves the cursor down
func (h *BufPane) CursorDown() bool {
h.Cursor.Deselect(false)
h.MoveCursorDown(1)
h.Relocate()
return true
}
// CursorLeft moves the cursor left
func (h *BufPane) CursorLeft() bool {
if h.Cursor.HasSelection() {
h.Cursor.Deselect(true)
} else {
tabstospaces := h.Buf.Settings["tabstospaces"].(bool)
tabmovement := h.Buf.Settings["tabmovement"].(bool)
if tabstospaces && tabmovement {
tabsize := int(h.Buf.Settings["tabsize"].(float64))
line := h.Buf.LineBytes(h.Cursor.Y)
if h.Cursor.X-tabsize >= 0 && util.IsSpaces(line[h.Cursor.X-tabsize:h.Cursor.X]) && util.IsBytesWhitespace(line[0:h.Cursor.X-tabsize]) {
for i := 0; i < tabsize; i++ {
h.Cursor.Left()
}
} else {
h.Cursor.Left()
}
} else {
h.Cursor.Left()
}
}
h.Relocate()
return true
}
// CursorRight moves the cursor right
func (h *BufPane) CursorRight() bool {
if h.Cursor.HasSelection() {
h.Cursor.Deselect(false)
h.Cursor.Right()
} else {
tabstospaces := h.Buf.Settings["tabstospaces"].(bool)
tabmovement := h.Buf.Settings["tabmovement"].(bool)
if tabstospaces && tabmovement {
tabsize := int(h.Buf.Settings["tabsize"].(float64))
line := h.Buf.LineBytes(h.Cursor.Y)
if h.Cursor.X+tabsize < util.CharacterCount(line) && util.IsSpaces(line[h.Cursor.X:h.Cursor.X+tabsize]) && util.IsBytesWhitespace(line[0:h.Cursor.X]) {
for i := 0; i < tabsize; i++ {
h.Cursor.Right()
}
} else {
h.Cursor.Right()
}
} else {
h.Cursor.Right()
}
}
h.Relocate()
return true
}
// WordRight moves the cursor one word to the right
func (h *BufPane) WordRight() bool {
h.Cursor.Deselect(false)
h.Cursor.WordRight()
h.Relocate()
return true
}
// WordLeft moves the cursor one word to the left
func (h *BufPane) WordLeft() bool {
h.Cursor.Deselect(true)
h.Cursor.WordLeft()
h.Relocate()
return true
}
// SubWordRight moves the cursor one sub-word to the right
func (h *BufPane) SubWordRight() bool {
h.Cursor.Deselect(false)
h.Cursor.SubWordRight()
h.Relocate()
return true
}
// SubWordLeft moves the cursor one sub-word to the left
func (h *BufPane) SubWordLeft() bool {
h.Cursor.Deselect(true)
h.Cursor.SubWordLeft()
h.Relocate()
return true
}
// SelectUp selects up one line
func (h *BufPane) SelectUp() bool {
if !h.Cursor.HasSelection() {
h.Cursor.OrigSelection[0] = h.Cursor.Loc
}
h.MoveCursorUp(1)
h.Cursor.SelectTo(h.Cursor.Loc)
h.Relocate()
return true
}
// SelectDown selects down one line
func (h *BufPane) SelectDown() bool {
if !h.Cursor.HasSelection() {
h.Cursor.OrigSelection[0] = h.Cursor.Loc
}
h.MoveCursorDown(1)
h.Cursor.SelectTo(h.Cursor.Loc)
h.Relocate()
return true
}
// SelectLeft selects the character to the left of the cursor
func (h *BufPane) SelectLeft() bool {
loc := h.Cursor.Loc
count := h.Buf.End()
if loc.GreaterThan(count) {
loc = count
}
if !h.Cursor.HasSelection() {
h.Cursor.OrigSelection[0] = loc
}
h.Cursor.Left()
h.Cursor.SelectTo(h.Cursor.Loc)
h.Relocate()
return true
}
// SelectRight selects the character to the right of the cursor
func (h *BufPane) SelectRight() bool {
loc := h.Cursor.Loc
count := h.Buf.End()
if loc.GreaterThan(count) {
loc = count
}
if !h.Cursor.HasSelection() {
h.Cursor.OrigSelection[0] = loc
}
h.Cursor.Right()
h.Cursor.SelectTo(h.Cursor.Loc)
h.Relocate()
return true
}
// SelectWordRight selects the word to the right of the cursor
func (h *BufPane) SelectWordRight() bool {
if !h.Cursor.HasSelection() {
h.Cursor.OrigSelection[0] = h.Cursor.Loc
}
h.Cursor.WordRight()
h.Cursor.SelectTo(h.Cursor.Loc)
h.Relocate()
return true
}
// SelectWordLeft selects the word to the left of the cursor
func (h *BufPane) SelectWordLeft() bool {
if !h.Cursor.HasSelection() {
h.Cursor.OrigSelection[0] = h.Cursor.Loc
}
h.Cursor.WordLeft()
h.Cursor.SelectTo(h.Cursor.Loc)
h.Relocate()
return true
}
// SelectSubWordRight selects the sub-word to the right of the cursor
func (h *BufPane) SelectSubWordRight() bool {
if !h.Cursor.HasSelection() {
h.Cursor.OrigSelection[0] = h.Cursor.Loc
}
h.Cursor.SubWordRight()
h.Cursor.SelectTo(h.Cursor.Loc)
h.Relocate()
return true
}
// SelectSubWordLeft selects the sub-word to the left of the cursor
func (h *BufPane) SelectSubWordLeft() bool {
if !h.Cursor.HasSelection() {
h.Cursor.OrigSelection[0] = h.Cursor.Loc
}
h.Cursor.SubWordLeft()
h.Cursor.SelectTo(h.Cursor.Loc)
h.Relocate()
return true
}
// StartOfText moves the cursor to the start of the text of the line
func (h *BufPane) StartOfText() bool {
h.Cursor.Deselect(true)
h.Cursor.StartOfText()
h.Relocate()
return true
}
// StartOfTextToggle toggles the cursor between the start of the text of the line
// and the start of the line
func (h *BufPane) StartOfTextToggle() bool {
h.Cursor.Deselect(true)
if h.Cursor.IsStartOfText() {
h.Cursor.Start()
} else {
h.Cursor.StartOfText()
}
h.Relocate()
return true
}
// StartOfLine moves the cursor to the start of the line
func (h *BufPane) StartOfLine() bool {
h.Cursor.Deselect(true)
h.Cursor.Start()
h.Relocate()
return true
}
// EndOfLine moves the cursor to the end of the line
func (h *BufPane) EndOfLine() bool {
h.Cursor.Deselect(true)
h.Cursor.End()
h.Relocate()
return true
}
// SelectLine selects the entire current line
func (h *BufPane) SelectLine() bool {
h.Cursor.SelectLine()
h.Relocate()
return true
}
// SelectToStartOfText selects to the start of the text on the current line
func (h *BufPane) SelectToStartOfText() bool {
if !h.Cursor.HasSelection() {
h.Cursor.OrigSelection[0] = h.Cursor.Loc
}
h.Cursor.StartOfText()
h.Cursor.SelectTo(h.Cursor.Loc)
h.Relocate()
return true
}
// SelectToStartOfTextToggle toggles the selection between the start of the text
// on the current line and the start of the line
func (h *BufPane) SelectToStartOfTextToggle() bool {
if !h.Cursor.HasSelection() {
h.Cursor.OrigSelection[0] = h.Cursor.Loc
}
if h.Cursor.IsStartOfText() {
h.Cursor.Start()
} else {
h.Cursor.StartOfText()
}
h.Cursor.SelectTo(h.Cursor.Loc)
h.Relocate()
return true
}
// SelectToStartOfLine selects to the start of the current line
func (h *BufPane) SelectToStartOfLine() bool {
if !h.Cursor.HasSelection() {
h.Cursor.OrigSelection[0] = h.Cursor.Loc
}
h.Cursor.Start()
h.Cursor.SelectTo(h.Cursor.Loc)
h.Relocate()
return true
}
// SelectToEndOfLine selects to the end of the current line
func (h *BufPane) SelectToEndOfLine() bool {
if !h.Cursor.HasSelection() {
h.Cursor.OrigSelection[0] = h.Cursor.Loc
}
h.Cursor.End()
h.Cursor.SelectTo(h.Cursor.Loc)
h.Relocate()
return true
}
func (h *BufPane) paragraphPrevious() {
var line int
// Skip to the first non-empty line
for line = h.Cursor.Y; line > 0; line-- {
if len(h.Buf.LineBytes(line)) != 0 {
break
}
}
// Find the first empty line
for ; line > 0; line-- {
if len(h.Buf.LineBytes(line)) == 0 {
h.Cursor.X = 0
h.Cursor.Y = line
break
}
}
// If no empty line was found, move the cursor to the start of the buffer
if line == 0 {
h.Cursor.Loc = h.Buf.Start()
}
}
func (h *BufPane) paragraphNext() {
var line int
// Skip to the first non-empty line
for line = h.Cursor.Y; line < h.Buf.LinesNum(); line++ {
if len(h.Buf.LineBytes(line)) != 0 {
break
}
}
// Find the first empty line
for ; line < h.Buf.LinesNum(); line++ {
if len(h.Buf.LineBytes(line)) == 0 {
h.Cursor.X = 0
h.Cursor.Y = line
break
}
}
// If no empty line was found, move the cursor to the end of the buffer
if line == h.Buf.LinesNum() {
h.Cursor.Loc = h.Buf.End()
}
}
// ParagraphPrevious moves the cursor to the first empty line that comes before
// the paragraph closest to the cursor, or beginning of the buffer if there
// isn't a paragraph
func (h *BufPane) ParagraphPrevious() bool {
h.Cursor.Deselect(true)
h.paragraphPrevious()
h.Relocate()
return true
}
// ParagraphNext moves the cursor to the first empty line that comes after the
// paragraph closest to the cursor, or end of the buffer if there isn't a
// paragraph
func (h *BufPane) ParagraphNext() bool {
h.Cursor.Deselect(true)
h.paragraphNext()
h.Relocate()
return true
}
// SelectToParagraphPrevious selects to the first empty line that comes before
// the paragraph closest to the cursor, or beginning of the buffer if there
// isn't a paragraph
func (h *BufPane) SelectToParagraphPrevious() bool {
if !h.Cursor.HasSelection() {
h.Cursor.OrigSelection[0] = h.Cursor.Loc
}
h.paragraphPrevious()
h.Cursor.SelectTo(h.Cursor.Loc)
h.Relocate()
return true
}
// SelectToParagraphNext selects to the first empty line that comes after the
// paragraph closest to the cursor, or end of the buffer if there isn't a
// paragraph
func (h *BufPane) SelectToParagraphNext() bool {
if !h.Cursor.HasSelection() {
h.Cursor.OrigSelection[0] = h.Cursor.Loc
}
h.paragraphNext()
h.Cursor.SelectTo(h.Cursor.Loc)
h.Relocate()
return true
}
// Retab changes all tabs to spaces or all spaces to tabs depending
// on the user's settings
func (h *BufPane) Retab() bool {
h.Buf.Retab()
h.Relocate()
return true
}
// CursorStart moves the cursor to the start of the buffer
func (h *BufPane) CursorStart() bool {
h.Cursor.Deselect(true)
h.Cursor.X = 0
h.Cursor.Y = 0
h.Cursor.StoreVisualX()
h.Relocate()
return true
}
// CursorEnd moves the cursor to the end of the buffer
func (h *BufPane) CursorEnd() bool {
h.Cursor.Deselect(true)
h.Cursor.Loc = h.Buf.End()
h.Cursor.StoreVisualX()
h.Relocate()
return true
}
// SelectToStart selects the text from the cursor to the start of the buffer
func (h *BufPane) SelectToStart() bool {
if !h.Cursor.HasSelection() {
h.Cursor.OrigSelection[0] = h.Cursor.Loc
}
h.CursorStart()
h.Cursor.SelectTo(h.Buf.Start())
h.Relocate()
return true
}
// SelectToEnd selects the text from the cursor to the end of the buffer
func (h *BufPane) SelectToEnd() bool {
if !h.Cursor.HasSelection() {
h.Cursor.OrigSelection[0] = h.Cursor.Loc
}
h.CursorEnd()
h.Cursor.SelectTo(h.Buf.End())
h.Relocate()
return true
}
// InsertNewline inserts a newline plus possible some whitespace if autoindent is on
func (h *BufPane) InsertNewline() bool {
// Insert a newline
if h.Cursor.HasSelection() {
h.Cursor.DeleteSelection()
h.Cursor.ResetSelection()
}
ws := util.GetLeadingWhitespace(h.Buf.LineBytes(h.Cursor.Y))
cx := h.Cursor.X
h.Buf.Insert(h.Cursor.Loc, "\n")
// h.Cursor.Right()
if h.Buf.Settings["autoindent"].(bool) {
if cx < len(ws) {
ws = ws[0:cx]
}
h.Buf.Insert(h.Cursor.Loc, string(ws))
// for i := 0; i < len(ws); i++ {
// h.Cursor.Right()
// }
// Remove the whitespaces if keepautoindent setting is off
if util.IsSpacesOrTabs(h.Buf.LineBytes(h.Cursor.Y-1)) && !h.Buf.Settings["keepautoindent"].(bool) {
line := h.Buf.LineBytes(h.Cursor.Y - 1)
h.Buf.Remove(buffer.Loc{X: 0, Y: h.Cursor.Y - 1}, buffer.Loc{X: util.CharacterCount(line), Y: h.Cursor.Y - 1})
}
}
h.Cursor.LastVisualX = h.Cursor.GetVisualX()
h.Relocate()
return true
}
// Backspace deletes the previous character
func (h *BufPane) Backspace() bool {
if h.Cursor.HasSelection() {
h.Cursor.DeleteSelection()
h.Cursor.ResetSelection()
} else if h.Cursor.Loc.GreaterThan(h.Buf.Start()) {
// We have to do something a bit hacky here because we want to
// delete the line by first moving left and then deleting backwards
// but the undo redo would place the cursor in the wrong place
// So instead we move left, save the position, move back, delete
// and restore the position
// If the user is using spaces instead of tabs and they are deleting
// whitespace at the start of the line, we should delete as if it's a
// tab (tabSize number of spaces)
lineStart := util.SliceStart(h.Buf.LineBytes(h.Cursor.Y), h.Cursor.X)
tabSize := int(h.Buf.Settings["tabsize"].(float64))
if h.Buf.Settings["tabstospaces"].(bool) && util.IsSpaces(lineStart) && len(lineStart) != 0 && util.CharacterCount(lineStart)%tabSize == 0 {
loc := h.Cursor.Loc
h.Buf.Remove(loc.Move(-tabSize, h.Buf), loc)
} else {
loc := h.Cursor.Loc
h.Buf.Remove(loc.Move(-1, h.Buf), loc)
}
}
h.Cursor.LastVisualX = h.Cursor.GetVisualX()
h.Relocate()
return true
}
// DeleteWordRight deletes the word to the right of the cursor
func (h *BufPane) DeleteWordRight() bool {
h.SelectWordRight()
if h.Cursor.HasSelection() {
h.Cursor.DeleteSelection()
h.Cursor.ResetSelection()
}
h.Relocate()
return true
}
// DeleteWordLeft deletes the word to the left of the cursor
func (h *BufPane) DeleteWordLeft() bool {
h.SelectWordLeft()
if h.Cursor.HasSelection() {
h.Cursor.DeleteSelection()
h.Cursor.ResetSelection()
}
h.Relocate()
return true
}
// DeleteSubWordRight deletes the sub-word to the right of the cursor
func (h *BufPane) DeleteSubWordRight() bool {
h.SelectSubWordRight()
if h.Cursor.HasSelection() {
h.Cursor.DeleteSelection()
h.Cursor.ResetSelection()
}
h.Relocate()
return true
}
// DeleteSubWordLeft deletes the sub-word to the left of the cursor
func (h *BufPane) DeleteSubWordLeft() bool {
h.SelectSubWordLeft()
if h.Cursor.HasSelection() {
h.Cursor.DeleteSelection()
h.Cursor.ResetSelection()
}
h.Relocate()
return true
}
// Delete deletes the next character
func (h *BufPane) Delete() bool {
if h.Cursor.HasSelection() {
h.Cursor.DeleteSelection()
h.Cursor.ResetSelection()
} else {
loc := h.Cursor.Loc
if loc.LessThan(h.Buf.End()) {
h.Buf.Remove(loc, loc.Move(1, h.Buf))
}
}
h.Relocate()
return true
}
// IndentSelection indents the current selection
func (h *BufPane) IndentSelection() bool {
if h.Cursor.HasSelection() {
start := h.Cursor.CurSelection[0]
end := h.Cursor.CurSelection[1]
if end.Y < start.Y {
start, end = end, start
h.Cursor.SetSelectionStart(start)
h.Cursor.SetSelectionEnd(end)
}
startY := start.Y
endY := end.Move(-1, h.Buf).Y
endX := end.Move(-1, h.Buf).X
tabsize := int(h.Buf.Settings["tabsize"].(float64))
indentsize := len(h.Buf.IndentString(tabsize))
for y := startY; y <= endY; y++ {
if len(h.Buf.LineBytes(y)) > 0 {
h.Buf.Insert(buffer.Loc{X: 0, Y: y}, h.Buf.IndentString(tabsize))
if y == startY && start.X > 0 {
h.Cursor.SetSelectionStart(start.Move(indentsize, h.Buf))
}
if y == endY {
h.Cursor.SetSelectionEnd(buffer.Loc{X: endX + indentsize + 1, Y: endY})
}
}
}
h.Buf.RelocateCursors()
h.Relocate()
return true
}
return false
}
// IndentLine moves the current line forward one indentation
func (h *BufPane) IndentLine() bool {
if h.Cursor.HasSelection() {
return false
}
tabsize := int(h.Buf.Settings["tabsize"].(float64))
indentstr := h.Buf.IndentString(tabsize)
h.Buf.Insert(buffer.Loc{X: 0, Y: h.Cursor.Y}, indentstr)
h.Buf.RelocateCursors()
h.Relocate()
return true
}
// OutdentLine moves the current line back one indentation
func (h *BufPane) OutdentLine() bool {
if h.Cursor.HasSelection() {
return false
}
for x := 0; x < len(h.Buf.IndentString(util.IntOpt(h.Buf.Settings["tabsize"]))); x++ {
if len(util.GetLeadingWhitespace(h.Buf.LineBytes(h.Cursor.Y))) == 0 {
break
}
h.Buf.Remove(buffer.Loc{X: 0, Y: h.Cursor.Y}, buffer.Loc{X: 1, Y: h.Cursor.Y})
}
h.Buf.RelocateCursors()
h.Relocate()
return true
}
// OutdentSelection takes the current selection and moves it back one indent level
func (h *BufPane) OutdentSelection() bool {
if h.Cursor.HasSelection() {
start := h.Cursor.CurSelection[0]
end := h.Cursor.CurSelection[1]
if end.Y < start.Y {
start, end = end, start
h.Cursor.SetSelectionStart(start)
h.Cursor.SetSelectionEnd(end)
}
startY := start.Y
endY := end.Move(-1, h.Buf).Y
for y := startY; y <= endY; y++ {
for x := 0; x < len(h.Buf.IndentString(util.IntOpt(h.Buf.Settings["tabsize"]))); x++ {
if len(util.GetLeadingWhitespace(h.Buf.LineBytes(y))) == 0 {
break
}
h.Buf.Remove(buffer.Loc{X: 0, Y: y}, buffer.Loc{X: 1, Y: y})
}
}
h.Buf.RelocateCursors()
h.Relocate()
return true
}
return false
}
// Autocomplete cycles the suggestions and performs autocompletion if there are suggestions
func (h *BufPane) Autocomplete() bool {
b := h.Buf
if h.Cursor.HasSelection() {
return false
}
if h.Cursor.X == 0 {
return false
}
r := h.Cursor.RuneUnder(h.Cursor.X)
prev := h.Cursor.RuneUnder(h.Cursor.X - 1)
if !util.IsAutocomplete(prev) || util.IsWordChar(r) {
// don't autocomplete if cursor is within a word
return false
}
if b.HasSuggestions {
b.CycleAutocomplete(true)
return true
}
return b.Autocomplete(buffer.BufferComplete)
}
// CycleAutocompleteBack cycles back in the autocomplete suggestion list
func (h *BufPane) CycleAutocompleteBack() bool {
if h.Cursor.HasSelection() {
return false
}
if h.Buf.HasSuggestions {
h.Buf.CycleAutocomplete(false)
return true
}
return false
}
// InsertTab inserts a tab or spaces
func (h *BufPane) InsertTab() bool {
b := h.Buf
indent := b.IndentString(util.IntOpt(b.Settings["tabsize"]))
tabBytes := len(indent)
bytesUntilIndent := tabBytes - (h.Cursor.GetVisualX() % tabBytes)
b.Insert(h.Cursor.Loc, indent[:bytesUntilIndent])
h.Relocate()
return true
}
// SaveAll saves all open buffers
func (h *BufPane) SaveAll() bool {
for _, b := range buffer.OpenBuffers {
b.Save()
}
return true
}
// SaveCB performs a save and does a callback at the very end (after all prompts have been resolved)
func (h *BufPane) SaveCB(action string, callback func()) bool {
// If this is an empty buffer, ask for a filename
if h.Buf.Path == "" {
h.SaveAsCB(action, callback)
} else {
noPrompt := h.saveBufToFile(h.Buf.Path, action, callback)
if noPrompt {
return true
}
}
return false
}
// Save the buffer to disk
func (h *BufPane) Save() bool {
return h.SaveCB("Save", nil)
}
// SaveAsCB performs a save as and does a callback at the very end (after all prompts have been resolved)
// The callback is only called if the save was successful
func (h *BufPane) SaveAsCB(action string, callback func()) bool {
InfoBar.Prompt("Filename: ", "", "Save", nil, func(resp string, canceled bool) {
if !canceled {
// the filename might or might not be quoted, so unquote first then join the strings.
args, err := shellquote.Split(resp)
if err != nil {
InfoBar.Error("Error parsing arguments: ", err)
return
}
if len(args) == 0 {
InfoBar.Error("No filename given")
return
}
filename := strings.Join(args, " ")
fileinfo, err := os.Stat(filename)
if err != nil {
if errors.Is(err, fs.ErrNotExist) || errors.Is(err, fs.ErrPermission) {
noPrompt := h.saveBufToFile(filename, action, callback)
if noPrompt {
h.completeAction(action)
return
}
}
} else {
InfoBar.YNPrompt(
fmt.Sprintf("The file %s already exists in the directory, would you like to overwrite? Y/n", fileinfo.Name()),
func(yes, canceled bool) {
if yes && !canceled {
noPrompt := h.saveBufToFile(filename, action, callback)
if noPrompt {
h.completeAction(action)
}
}
},
)
}
}
})
return false
}
// SaveAs saves the buffer to disk with the given name
func (h *BufPane) SaveAs() bool {
return h.SaveAsCB("SaveAs", nil)
}
// This function saves the buffer to `filename` and changes the buffer's path and name
// to `filename` if the save is successful
// The callback is only called if the save was successful
func (h *BufPane) saveBufToFile(filename string, action string, callback func()) bool {
err := h.Buf.SaveAs(filename)
if err != nil {
if errors.Is(err, fs.ErrPermission) {
saveWithSudo := func() {
err = h.Buf.SaveAsWithSudo(filename)
if err != nil {
InfoBar.Error(err)
} else {
h.Buf.Path = filename
h.Buf.SetName(filename)
InfoBar.Message("Saved " + filename)
if callback != nil {
callback()
}
}
}
if h.Buf.Settings["autosu"].(bool) {
saveWithSudo()
} else {
InfoBar.YNPrompt(
fmt.Sprintf("Permission denied. Do you want to save this file using %s? (y,n)", config.GlobalSettings["sucmd"].(string)),
func(yes, canceled bool) {
if yes && !canceled {
saveWithSudo()
h.completeAction(action)
}
},
)
return false
}
} else {
InfoBar.Error(err)
}
} else {
h.Buf.Path = filename
h.Buf.SetName(filename)
InfoBar.Message("Saved " + filename)
if callback != nil {
callback()
}
}
return true
}
// Find opens a prompt and searches forward for the input
func (h *BufPane) Find() bool {
return h.find(true)
}
// FindLiteral is the same as Find() but does not support regular expressions
func (h *BufPane) FindLiteral() bool {
return h.find(false)
}
// Search searches for a given string/regex in the buffer and selects the next
// match if a match is found
// This function behaves the same way as Find and FindLiteral actions:
// it affects the buffer's LastSearch and LastSearchRegex (saved searches)
// for use with FindNext and FindPrevious, and turns HighlightSearch on or off
// according to hlsearch setting
func (h *BufPane) Search(str string, useRegex bool, searchDown bool) error {
match, found, err := h.Buf.FindNext(str, h.Buf.Start(), h.Buf.End(), h.Cursor.Loc, searchDown, useRegex)
if err != nil {
return err
}
if found {
h.Cursor.SetSelectionStart(match[0])
h.Cursor.SetSelectionEnd(match[1])
h.Cursor.OrigSelection[0] = h.Cursor.CurSelection[0]
h.Cursor.OrigSelection[1] = h.Cursor.CurSelection[1]
h.GotoLoc(h.Cursor.CurSelection[1])
h.Buf.LastSearch = str
h.Buf.LastSearchRegex = useRegex
h.Buf.HighlightSearch = h.Buf.Settings["hlsearch"].(bool)
} else {
h.Cursor.ResetSelection()
}
return nil
}
func (h *BufPane) find(useRegex bool) bool {
h.searchOrig = h.Cursor.Loc
prompt := "Find: "
if useRegex {
prompt = "Find (regex): "
}
var eventCallback func(resp string)
if h.Buf.Settings["incsearch"].(bool) {
eventCallback = func(resp string) {
match, found, _ := h.Buf.FindNext(resp, h.Buf.Start(), h.Buf.End(), h.searchOrig, true, useRegex)
if found {
h.Cursor.SetSelectionStart(match[0])
h.Cursor.SetSelectionEnd(match[1])
h.Cursor.OrigSelection[0] = h.Cursor.CurSelection[0]
h.Cursor.OrigSelection[1] = h.Cursor.CurSelection[1]
h.GotoLoc(match[1])
} else {
h.GotoLoc(h.searchOrig)
h.Cursor.ResetSelection()
}
}
}
findCallback := func(resp string, canceled bool) {
// Finished callback
if !canceled {
match, found, err := h.Buf.FindNext(resp, h.Buf.Start(), h.Buf.End(), h.searchOrig, true, useRegex)
if err != nil {
InfoBar.Error(err)
}
if found {
h.Cursor.SetSelectionStart(match[0])
h.Cursor.SetSelectionEnd(match[1])
h.Cursor.OrigSelection[0] = h.Cursor.CurSelection[0]
h.Cursor.OrigSelection[1] = h.Cursor.CurSelection[1]
h.GotoLoc(h.Cursor.CurSelection[1])
h.Buf.LastSearch = resp
h.Buf.LastSearchRegex = useRegex
h.Buf.HighlightSearch = h.Buf.Settings["hlsearch"].(bool)
} else {
h.Cursor.ResetSelection()
InfoBar.Message("No matches found")
}
} else {
h.Cursor.ResetSelection()
}
}
pattern := string(h.Cursor.GetSelection())
if useRegex && pattern != "" {
pattern = regexp.QuoteMeta(pattern)
}
if eventCallback != nil && pattern != "" {
eventCallback(pattern)
}
InfoBar.Prompt(prompt, pattern, "Find", eventCallback, findCallback)
if pattern != "" {
InfoBar.SelectAll()
}
return true
}
// ToggleHighlightSearch toggles highlighting all instances of the last used search term
func (h *BufPane) ToggleHighlightSearch() bool {
h.Buf.HighlightSearch = !h.Buf.HighlightSearch
return true
}
// UnhighlightSearch unhighlights all instances of the last used search term
func (h *BufPane) UnhighlightSearch() bool {
if !h.Buf.HighlightSearch {
return false
}
h.Buf.HighlightSearch = false
return true
}
// ResetSearch resets the last used search term
func (h *BufPane) ResetSearch() bool {
if h.Buf.LastSearch != "" {
h.Buf.LastSearch = ""
return true
}
return false
}
// FindNext searches forwards for the last used search term
func (h *BufPane) FindNext() bool {
if h.Buf.LastSearch == "" {
return false
}
// If the cursor is at the start of a selection and we search we want
// to search from the end of the selection in the case that
// the selection is a search result in which case we wouldn't move at
// at all which would be bad
searchLoc := h.Cursor.Loc
if h.Cursor.HasSelection() {
searchLoc = h.Cursor.CurSelection[1]
}
match, found, err := h.Buf.FindNext(h.Buf.LastSearch, h.Buf.Start(), h.Buf.End(), searchLoc, true, h.Buf.LastSearchRegex)
if err != nil {
InfoBar.Error(err)
}
if found {
h.Cursor.SetSelectionStart(match[0])
h.Cursor.SetSelectionEnd(match[1])
h.Cursor.OrigSelection[0] = h.Cursor.CurSelection[0]
h.Cursor.OrigSelection[1] = h.Cursor.CurSelection[1]
h.GotoLoc(h.Cursor.CurSelection[1])
} else {
h.Cursor.ResetSelection()
}
return true
}
// FindPrevious searches backwards for the last used search term
func (h *BufPane) FindPrevious() bool {
if h.Buf.LastSearch == "" {
return false
}
// If the cursor is at the end of a selection and we search we want
// to search from the beginning of the selection in the case that
// the selection is a search result in which case we wouldn't move at
// at all which would be bad
searchLoc := h.Cursor.Loc
if h.Cursor.HasSelection() {
searchLoc = h.Cursor.CurSelection[0]
}
match, found, err := h.Buf.FindNext(h.Buf.LastSearch, h.Buf.Start(), h.Buf.End(), searchLoc, false, h.Buf.LastSearchRegex)
if err != nil {
InfoBar.Error(err)
}
if found {
h.Cursor.SetSelectionStart(match[0])
h.Cursor.SetSelectionEnd(match[1])
h.Cursor.OrigSelection[0] = h.Cursor.CurSelection[0]
h.Cursor.OrigSelection[1] = h.Cursor.CurSelection[1]
h.GotoLoc(h.Cursor.CurSelection[1])
} else {
h.Cursor.ResetSelection()
}
return true
}
// DiffNext searches forward until the beginning of the next block of diffs
func (h *BufPane) DiffNext() bool {
cur := h.Cursor.Loc.Y
dl, err := h.Buf.FindNextDiffLine(cur, true)
if err != nil {
return false
}
h.GotoLoc(buffer.Loc{0, dl})
return true
}
// DiffPrevious searches forward until the end of the previous block of diffs
func (h *BufPane) DiffPrevious() bool {
cur := h.Cursor.Loc.Y
dl, err := h.Buf.FindNextDiffLine(cur, false)
if err != nil {
return false
}
h.GotoLoc(buffer.Loc{0, dl})
return true
}
// Undo undoes the last action
func (h *BufPane) Undo() bool {
if !h.Buf.Undo() {
return false
}
InfoBar.Message("Undid action")
h.Relocate()
return true
}
// Redo redoes the last action
func (h *BufPane) Redo() bool {
if !h.Buf.Redo() {
return false
}
InfoBar.Message("Redid action")
h.Relocate()
return true
}
// Copy the selection to the system clipboard
func (h *BufPane) Copy() bool {
if h.Cursor.HasSelection() {
h.Cursor.CopySelection(clipboard.ClipboardReg)
h.freshClip = true
InfoBar.Message("Copied selection")
}
h.Relocate()
return true
}
// CopyLine copies the current line to the clipboard
func (h *BufPane) CopyLine() bool {
if h.Cursor.HasSelection() {
return false
}
origLoc := h.Cursor.Loc
h.Cursor.SelectLine()
h.Cursor.CopySelection(clipboard.ClipboardReg)
h.freshClip = true
InfoBar.Message("Copied line")
h.Cursor.Deselect(true)
h.Cursor.Loc = origLoc
h.Relocate()
return true
}
// CutLine cuts the current line to the clipboard
func (h *BufPane) CutLine() bool {
h.Cursor.SelectLine()
if !h.Cursor.HasSelection() {
return false
}
if h.freshClip {
if h.Cursor.HasSelection() {
if clip, err := clipboard.Read(clipboard.ClipboardReg); err != nil {
InfoBar.Error(err)
} else {
clipboard.WriteMulti(clip+string(h.Cursor.GetSelection()), clipboard.ClipboardReg, h.Cursor.Num, h.Buf.NumCursors())
}
}
} else if time.Since(h.lastCutTime)/time.Second > 10*time.Second || !h.freshClip {
h.Copy()
}
h.freshClip = true
h.lastCutTime = time.Now()
h.Cursor.DeleteSelection()
h.Cursor.ResetSelection()
InfoBar.Message("Cut line")
h.Relocate()
return true
}
// Cut the selection to the system clipboard
func (h *BufPane) Cut() bool {
if h.Cursor.HasSelection() {
h.Cursor.CopySelection(clipboard.ClipboardReg)
h.Cursor.DeleteSelection()
h.Cursor.ResetSelection()
h.freshClip = true
InfoBar.Message("Cut selection")
h.Relocate()
return true
}
return h.CutLine()
}
// DuplicateLine duplicates the current line or selection
func (h *BufPane) DuplicateLine() bool {
var infoMessage = "Duplicated line"
if h.Cursor.HasSelection() {
infoMessage = "Duplicated selection"
h.Buf.Insert(h.Cursor.CurSelection[1], string(h.Cursor.GetSelection()))
} else {
h.Cursor.End()
h.Buf.Insert(h.Cursor.Loc, "\n"+string(h.Buf.LineBytes(h.Cursor.Y)))
// h.Cursor.Right()
}
InfoBar.Message(infoMessage)
h.Relocate()
return true
}
// DeleteLine deletes the current line
func (h *BufPane) DeleteLine() bool {
h.Cursor.SelectLine()
if !h.Cursor.HasSelection() {
return false
}
h.Cursor.DeleteSelection()
h.Cursor.ResetSelection()
InfoBar.Message("Deleted line")
h.Relocate()
return true
}
// MoveLinesUp moves up the current line or selected lines if any
func (h *BufPane) MoveLinesUp() bool {
if h.Cursor.HasSelection() {
if h.Cursor.CurSelection[0].Y == 0 {
InfoBar.Message("Cannot move further up")
return false
}
start := h.Cursor.CurSelection[0].Y
end := h.Cursor.CurSelection[1].Y
sel := 1
if start > end {
end, start = start, end
sel = 0
}
compensate := false
if h.Cursor.CurSelection[sel].X != 0 {
end++
} else {
compensate = true
}
h.Buf.MoveLinesUp(
start,
end,
)
if compensate {
h.Cursor.CurSelection[sel].Y -= 1
}
} else {
if h.Cursor.Loc.Y == 0 {
InfoBar.Message("Cannot move further up")
return false
}
h.Buf.MoveLinesUp(
h.Cursor.Loc.Y,
h.Cursor.Loc.Y+1,
)
}
h.Relocate()
return true
}
// MoveLinesDown moves down the current line or selected lines if any
func (h *BufPane) MoveLinesDown() bool {
if h.Cursor.HasSelection() {
if h.Cursor.CurSelection[1].Y >= h.Buf.LinesNum() {
InfoBar.Message("Cannot move further down")
return false
}
start := h.Cursor.CurSelection[0].Y
end := h.Cursor.CurSelection[1].Y
sel := 1
if start > end {
end, start = start, end
sel = 0
}
if h.Cursor.CurSelection[sel].X != 0 {
end++
}
h.Buf.MoveLinesDown(
start,
end,
)
} else {
if h.Cursor.Loc.Y >= h.Buf.LinesNum()-1 {
InfoBar.Message("Cannot move further down")
return false
}
h.Buf.MoveLinesDown(
h.Cursor.Loc.Y,
h.Cursor.Loc.Y+1,
)
}
h.Relocate()
return true
}
// Paste whatever is in the system clipboard into the buffer
// Delete and paste if the user has a selection
func (h *BufPane) Paste() bool {
clip, err := clipboard.ReadMulti(clipboard.ClipboardReg, h.Cursor.Num, h.Buf.NumCursors())
if err != nil {
InfoBar.Error(err)
} else {
h.paste(clip)
}
h.Relocate()
return true
}
// PastePrimary pastes from the primary clipboard (only use on linux)
func (h *BufPane) PastePrimary() bool {
clip, err := clipboard.ReadMulti(clipboard.PrimaryReg, h.Cursor.Num, h.Buf.NumCursors())
if err != nil {
InfoBar.Error(err)
} else {
h.paste(clip)
}
h.Relocate()
return true
}
func (h *BufPane) paste(clip string) {
if h.Buf.Settings["smartpaste"].(bool) {
if h.Cursor.X > 0 {
leadingPasteWS := string(util.GetLeadingWhitespace([]byte(clip)))
if leadingPasteWS != " " && strings.Contains(clip, "\n"+leadingPasteWS) {
leadingWS := string(util.GetLeadingWhitespace(h.Buf.LineBytes(h.Cursor.Y)))
clip = strings.TrimPrefix(clip, leadingPasteWS)
clip = strings.ReplaceAll(clip, "\n"+leadingPasteWS, "\n"+leadingWS)
}
}
}
if h.Cursor.HasSelection() {
h.Cursor.DeleteSelection()
h.Cursor.ResetSelection()
}
h.Buf.Insert(h.Cursor.Loc, clip)
// h.Cursor.Loc = h.Cursor.Loc.Move(Count(clip), h.Buf)
h.freshClip = false
InfoBar.Message("Pasted clipboard")
}
// JumpToMatchingBrace moves the cursor to the matching brace if it is
// currently on a brace
func (h *BufPane) JumpToMatchingBrace() bool {
matchingBrace, left, found := h.Buf.FindMatchingBrace(h.Cursor.Loc)
if found {
if h.Buf.Settings["matchbraceleft"].(bool) {
if left {
h.Cursor.GotoLoc(matchingBrace)
} else {
h.Cursor.GotoLoc(matchingBrace.Move(1, h.Buf))
}
} else {
h.Cursor.GotoLoc(matchingBrace)
}
h.Relocate()
return true
}
return false
}
// SelectAll selects the entire buffer
func (h *BufPane) SelectAll() bool {
h.Cursor.SetSelectionStart(h.Buf.Start())
h.Cursor.SetSelectionEnd(h.Buf.End())
// Put the cursor at the beginning
h.Cursor.X = 0
h.Cursor.Y = 0
h.Relocate()
return true
}
// OpenFile opens a new file in the buffer
func (h *BufPane) OpenFile() bool {
InfoBar.Prompt("> ", "open ", "Open", nil, func(resp string, canceled bool) {
if !canceled {
h.HandleCommand(resp)
}
})
return true
}
// JumpLine asks the user to enter a line number to jump to
func (h *BufPane) JumpLine() bool {
InfoBar.Prompt("> ", "goto ", "Command", nil, func(resp string, canceled bool) {
if !canceled {
h.HandleCommand(resp)
}
})
return true
}
// Start moves the viewport to the start of the buffer
func (h *BufPane) Start() bool {
v := h.GetView()
v.StartLine = display.SLoc{0, 0}
h.SetView(v)
return true
}
// End moves the viewport to the end of the buffer
func (h *BufPane) End() bool {
v := h.GetView()
v.StartLine = h.Scroll(h.SLocFromLoc(h.Buf.End()), -h.BufView().Height+1)
h.SetView(v)
return true
}
// PageUp scrolls the view up a page
func (h *BufPane) PageUp() bool {
h.ScrollUp(h.BufView().Height)
return true
}
// PageDown scrolls the view down a page
func (h *BufPane) PageDown() bool {
h.ScrollDown(h.BufView().Height)
h.ScrollAdjust()
return true
}
// SelectPageUp selects up one page
func (h *BufPane) SelectPageUp() bool {
if !h.Cursor.HasSelection() {
h.Cursor.OrigSelection[0] = h.Cursor.Loc
}
h.MoveCursorUp(h.BufView().Height)
h.Cursor.SelectTo(h.Cursor.Loc)
h.Relocate()
return true
}
// SelectPageDown selects down one page
func (h *BufPane) SelectPageDown() bool {
if !h.Cursor.HasSelection() {
h.Cursor.OrigSelection[0] = h.Cursor.Loc
}
h.MoveCursorDown(h.BufView().Height)
h.Cursor.SelectTo(h.Cursor.Loc)
h.Relocate()
return true
}
// CursorPageUp places the cursor a page up
func (h *BufPane) CursorPageUp() bool {
h.Cursor.Deselect(true)
if h.Cursor.HasSelection() {
h.Cursor.Loc = h.Cursor.CurSelection[0]
h.Cursor.ResetSelection()
h.Cursor.StoreVisualX()
}
h.MoveCursorUp(h.BufView().Height)
h.Relocate()
return true
}
// CursorPageDown places the cursor a page up
func (h *BufPane) CursorPageDown() bool {
h.Cursor.Deselect(false)
if h.Cursor.HasSelection() {
h.Cursor.Loc = h.Cursor.CurSelection[1]
h.Cursor.ResetSelection()
h.Cursor.StoreVisualX()
}
h.MoveCursorDown(h.BufView().Height)
h.Relocate()
return true
}
// HalfPageUp scrolls the view up half a page
func (h *BufPane) HalfPageUp() bool {
h.ScrollUp(h.BufView().Height / 2)
return true
}
// HalfPageDown scrolls the view down half a page
func (h *BufPane) HalfPageDown() bool {
h.ScrollDown(h.BufView().Height / 2)
h.ScrollAdjust()
return true
}
// ToggleDiffGutter turns the diff gutter off and on
func (h *BufPane) ToggleDiffGutter() bool {
if !h.Buf.Settings["diffgutter"].(bool) {
h.Buf.Settings["diffgutter"] = true
h.Buf.UpdateDiff()
InfoBar.Message("Enabled diff gutter")
} else {
h.Buf.Settings["diffgutter"] = false
InfoBar.Message("Disabled diff gutter")
}
return true
}
// ToggleRuler turns line numbers off and on
func (h *BufPane) ToggleRuler() bool {
if !h.Buf.Settings["ruler"].(bool) {
h.Buf.Settings["ruler"] = true
InfoBar.Message("Enabled ruler")
} else {
h.Buf.Settings["ruler"] = false
InfoBar.Message("Disabled ruler")
}
return true
}
// ClearStatus clears the infobar. It is an alias for ClearInfo.
func (h *BufPane) ClearStatus() bool {
return h.ClearInfo()
}
// ToggleHelp toggles the help screen
func (h *BufPane) ToggleHelp() bool {
if h.Buf.Type == buffer.BTHelp {
h.Quit()
} else {
h.openHelp("help")
}
return true
}
// ToggleKeyMenu toggles the keymenu option and resizes all tabs
func (h *BufPane) ToggleKeyMenu() bool {
config.GlobalSettings["keymenu"] = !config.GetGlobalOption("keymenu").(bool)
Tabs.Resize()
return true
}
// ShellMode opens a terminal to run a shell command
func (h *BufPane) ShellMode() bool {
InfoBar.Prompt("$ ", "", "Shell", nil, func(resp string, canceled bool) {
if !canceled {
// The true here is for openTerm to make the command interactive
shell.RunInteractiveShell(resp, true, false)
}
})
return true
}
// CommandMode lets the user enter a command
func (h *BufPane) CommandMode() bool {
InfoBar.Prompt("> ", "", "Command", nil, func(resp string, canceled bool) {
if !canceled {
h.HandleCommand(resp)
}
})
return true
}
// ToggleOverwriteMode lets the user toggle the text overwrite mode
func (h *BufPane) ToggleOverwriteMode() bool {
h.isOverwriteMode = !h.isOverwriteMode
return true
}
// Escape leaves current mode
func (h *BufPane) Escape() bool {
return true
}
// Deselect deselects on the current cursor
func (h *BufPane) Deselect() bool {
if !h.Cursor.HasSelection() {
return false
}
h.Cursor.Deselect(true)
return true
}
// ClearInfo clears the infobar
func (h *BufPane) ClearInfo() bool {
if InfoBar.Msg == "" {
return false
}
InfoBar.Message("")
return true
}
// ForceQuit closes the current tab or view even if there are unsaved changes
// (no prompt)
func (h *BufPane) ForceQuit() bool {
h.Buf.Close()
if len(MainTab().Panes) > 1 {
h.Unsplit()
} else if len(Tabs.List) > 1 {
Tabs.RemoveTab(h.splitID)
} else {
screen.Screen.Fini()
InfoBar.Close()
runtime.Goexit()
}
return true
}
// Quit this will close the current tab or view that is open
func (h *BufPane) Quit() bool {
if h.Buf.Modified() {
if config.GlobalSettings["autosave"].(float64) > 0 {
// autosave on means we automatically save when quitting
h.SaveCB("Quit", func() {
h.ForceQuit()
})
} else {
InfoBar.YNPrompt("Save changes to "+h.Buf.GetName()+" before closing? (y,n,esc)", func(yes, canceled bool) {
if !canceled && !yes {
h.ForceQuit()
} else if !canceled && yes {
h.SaveCB("Quit", func() {
h.ForceQuit()
})
}
})
}
} else {
h.ForceQuit()
}
return true
}
// QuitAll quits the whole editor; all splits and tabs
func (h *BufPane) QuitAll() bool {
anyModified := false
for _, b := range buffer.OpenBuffers {
if b.Modified() {
anyModified = true
break
}
}
quit := func() {
buffer.CloseOpenBuffers()
screen.Screen.Fini()
InfoBar.Close()
runtime.Goexit()
}
if anyModified {
InfoBar.YNPrompt("Quit micro? (all open buffers will be closed without saving)", func(yes, canceled bool) {
if !canceled && yes {
quit()
}
})
} else {
quit()
}
return true
}
// AddTab adds a new tab with an empty buffer
func (h *BufPane) AddTab() bool {
width, height := screen.Screen.Size()
iOffset := config.GetInfoBarOffset()
b := buffer.NewBufferFromString("", "", buffer.BTDefault)
tp := NewTabFromBuffer(0, 0, width, height-iOffset, b)
Tabs.AddTab(tp)
Tabs.SetActive(len(Tabs.List) - 1)
return true
}
// PreviousTab switches to the previous tab in the tab list
func (h *BufPane) PreviousTab() bool {
tabsLen := len(Tabs.List)
if tabsLen == 1 {
return false
}
a := Tabs.Active() + tabsLen
Tabs.SetActive((a - 1) % tabsLen)
return true
}
// NextTab switches to the next tab in the tab list
func (h *BufPane) NextTab() bool {
tabsLen := len(Tabs.List)
if tabsLen == 1 {
return false
}
a := Tabs.Active()
Tabs.SetActive((a + 1) % tabsLen)
return true
}
// VSplitAction opens an empty vertical split
func (h *BufPane) VSplitAction() bool {
h.VSplitBuf(buffer.NewBufferFromString("", "", buffer.BTDefault))
return true
}
// HSplitAction opens an empty horizontal split
func (h *BufPane) HSplitAction() bool {
h.HSplitBuf(buffer.NewBufferFromString("", "", buffer.BTDefault))
return true
}
// Unsplit closes all splits in the current tab except the active one
func (h *BufPane) Unsplit() bool {
tab := h.tab
n := tab.GetNode(h.splitID)
ok := n.Unsplit()
if ok {
tab.RemovePane(tab.GetPane(h.splitID))
tab.Resize()
tab.SetActive(len(tab.Panes) - 1)
return true
}
return false
}
// NextSplit changes the view to the next split
func (h *BufPane) NextSplit() bool {
if len(h.tab.Panes) == 1 {
return false
}
a := h.tab.active
if a < len(h.tab.Panes)-1 {
a++
} else {
a = 0
}
h.tab.SetActive(a)
return true
}
// PreviousSplit changes the view to the previous split
func (h *BufPane) PreviousSplit() bool {
if len(h.tab.Panes) == 1 {
return false
}
a := h.tab.active
if a > 0 {
a--
} else {
a = len(h.tab.Panes) - 1
}
h.tab.SetActive(a)
return true
}
var curmacro []interface{}
var recordingMacro bool
// ToggleMacro toggles recording of a macro
func (h *BufPane) ToggleMacro() bool {
recordingMacro = !recordingMacro
if recordingMacro {
curmacro = []interface{}{}
InfoBar.Message("Recording")
} else {
InfoBar.Message("Stopped recording")
}
h.Relocate()
return true
}
// PlayMacro plays back the most recently recorded macro
func (h *BufPane) PlayMacro() bool {
if recordingMacro {
return false
}
for _, action := range curmacro {
switch t := action.(type) {
case rune:
h.DoRuneInsert(t)
case BufKeyAction:
t(h)
}
}
h.Relocate()
return true
}
// SpawnMultiCursor creates a new multiple cursor at the next occurrence of the current selection or current word
func (h *BufPane) SpawnMultiCursor() bool {
spawner := h.Buf.GetCursor(h.Buf.NumCursors() - 1)
if !spawner.HasSelection() {
spawner.SelectWord()
h.multiWord = true
h.Relocate()
return true
}
sel := spawner.GetSelection()
searchStart := spawner.CurSelection[1]
search := string(sel)
search = regexp.QuoteMeta(search)
if h.multiWord {
search = "\\b" + search + "\\b"
}
match, found, err := h.Buf.FindNext(search, h.Buf.Start(), h.Buf.End(), searchStart, true, true)
if err != nil {
InfoBar.Error(err)
}
if found {
c := buffer.NewCursor(h.Buf, buffer.Loc{})
c.SetSelectionStart(match[0])
c.SetSelectionEnd(match[1])
c.OrigSelection[0] = c.CurSelection[0]
c.OrigSelection[1] = c.CurSelection[1]
c.Loc = c.CurSelection[1]
h.Buf.AddCursor(c)
h.Buf.SetCurCursor(h.Buf.NumCursors() - 1)
h.Buf.MergeCursors()
} else {
InfoBar.Message("No matches found")
}
h.Relocate()
return true
}
// SpawnMultiCursorUpN is not an action
func (h *BufPane) SpawnMultiCursorUpN(n int) bool {
lastC := h.Buf.GetCursor(h.Buf.NumCursors() - 1)
var c *buffer.Cursor
if !h.Buf.Settings["softwrap"].(bool) {
if n > 0 && lastC.Y == 0 {
return false
}
if n < 0 && lastC.Y+1 == h.Buf.LinesNum() {
return false
}
h.Buf.DeselectCursors()
c = buffer.NewCursor(h.Buf, buffer.Loc{lastC.X, lastC.Y - n})
c.LastVisualX = lastC.LastVisualX
c.X = c.GetCharPosInLine(h.Buf.LineBytes(c.Y), c.LastVisualX)
c.Relocate()
} else {
vloc := h.VLocFromLoc(lastC.Loc)
sloc := h.Scroll(vloc.SLoc, -n)
if sloc == vloc.SLoc {
return false
}
h.Buf.DeselectCursors()
vloc.SLoc = sloc
vloc.VisualX = lastC.LastVisualX
c = buffer.NewCursor(h.Buf, h.LocFromVLoc(vloc))
c.LastVisualX = lastC.LastVisualX
}
h.Buf.AddCursor(c)
h.Buf.SetCurCursor(h.Buf.NumCursors() - 1)
h.Buf.MergeCursors()
h.Relocate()
return true
}
// SpawnMultiCursorUp creates additional cursor, at the same X (if possible), one Y less.
func (h *BufPane) SpawnMultiCursorUp() bool {
return h.SpawnMultiCursorUpN(1)
}
// SpawnMultiCursorDown creates additional cursor, at the same X (if possible), one Y more.
func (h *BufPane) SpawnMultiCursorDown() bool {
return h.SpawnMultiCursorUpN(-1)
}
// SpawnMultiCursorSelect adds a cursor at the beginning of each line of a selection
func (h *BufPane) SpawnMultiCursorSelect() bool {
// Avoid cases where multiple cursors already exist, that would create problems
if h.Buf.NumCursors() > 1 {
return false
}
var startLine int
var endLine int
a, b := h.Cursor.CurSelection[0].Y, h.Cursor.CurSelection[1].Y
if a > b {
startLine, endLine = b, a
} else {
startLine, endLine = a, b
}
if h.Cursor.HasSelection() {
h.Cursor.ResetSelection()
h.Cursor.GotoLoc(buffer.Loc{0, startLine})
for i := startLine; i <= endLine; i++ {
c := buffer.NewCursor(h.Buf, buffer.Loc{0, i})
c.StoreVisualX()
h.Buf.AddCursor(c)
}
h.Buf.MergeCursors()
} else {
return false
}
InfoBar.Message("Added cursors from selection")
return true
}
// MouseMultiCursor is a mouse action which puts a new cursor at the mouse position,
// or removes a cursor if it is already there
func (h *BufPane) MouseMultiCursor(e *tcell.EventMouse) bool {
b := h.Buf
mx, my := e.Position()
// ignore click on the status line
if my >= h.BufView().Y+h.BufView().Height {
return false
}
mouseLoc := h.LocFromVisual(buffer.Loc{X: mx, Y: my})
if h.Buf.NumCursors() > 1 {
cursors := h.Buf.GetCursors()
for _, c := range cursors {
if c.Loc == mouseLoc {
h.Buf.RemoveCursor(c.Num)
return true
}
}
}
c := buffer.NewCursor(b, mouseLoc)
b.AddCursor(c)
b.MergeCursors()
return true
}
// SkipMultiCursor moves the current multiple cursor to the next available position
func (h *BufPane) SkipMultiCursor() bool {
lastC := h.Buf.GetCursor(h.Buf.NumCursors() - 1)
if !lastC.HasSelection() {
return false
}
sel := lastC.GetSelection()
searchStart := lastC.CurSelection[1]
search := string(sel)
search = regexp.QuoteMeta(search)
if h.multiWord {
search = "\\b" + search + "\\b"
}
match, found, err := h.Buf.FindNext(search, h.Buf.Start(), h.Buf.End(), searchStart, true, true)
if err != nil {
InfoBar.Error(err)
}
if found {
lastC.SetSelectionStart(match[0])
lastC.SetSelectionEnd(match[1])
lastC.OrigSelection[0] = lastC.CurSelection[0]
lastC.OrigSelection[1] = lastC.CurSelection[1]
lastC.Loc = lastC.CurSelection[1]
h.Buf.MergeCursors()
h.Buf.SetCurCursor(h.Buf.NumCursors() - 1)
} else {
InfoBar.Message("No matches found")
}
h.Relocate()
return true
}
// RemoveMultiCursor removes the latest multiple cursor
func (h *BufPane) RemoveMultiCursor() bool {
if h.Buf.NumCursors() > 1 {
h.Buf.RemoveCursor(h.Buf.NumCursors() - 1)
h.Buf.SetCurCursor(h.Buf.NumCursors() - 1)
h.Buf.UpdateCursors()
} else if h.multiWord {
h.multiWord = false
h.Cursor.Deselect(true)
} else {
return false
}
h.Relocate()
return true
}
// RemoveAllMultiCursors removes all cursors except the base cursor
func (h *BufPane) RemoveAllMultiCursors() bool {
if h.Buf.NumCursors() > 1 || h.multiWord {
h.Buf.ClearCursors()
h.multiWord = false
} else {
return false
}
h.Relocate()
return true
}
// None is an action that does nothing
func (h *BufPane) None() bool {
return true
}
```
|
/content/code_sandbox/internal/action/actions.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 15,256
|
```go
package action
import (
"errors"
"runtime"
"github.com/zyedidia/micro/v2/internal/clipboard"
"github.com/zyedidia/micro/v2/internal/config"
"github.com/zyedidia/micro/v2/internal/display"
"github.com/zyedidia/micro/v2/internal/screen"
"github.com/zyedidia/micro/v2/internal/shell"
"github.com/zyedidia/tcell/v2"
"github.com/zyedidia/terminal"
)
type TermKeyAction func(*TermPane)
var TermBindings *KeyTree
func init() {
TermBindings = NewKeyTree()
}
func TermKeyActionGeneral(a TermKeyAction) PaneKeyAction {
return func(p Pane) bool {
a(p.(*TermPane))
return true
}
}
func TermMapEvent(k Event, action string) {
config.Bindings["terminal"][k.Name()] = action
switch e := k.(type) {
case KeyEvent, KeySequenceEvent, RawEvent:
termMapKey(e, action)
case MouseEvent:
termMapMouse(e, action)
}
}
func termMapKey(k Event, action string) {
if f, ok := TermKeyActions[action]; ok {
TermBindings.RegisterKeyBinding(k, TermKeyActionGeneral(f))
}
}
func termMapMouse(k MouseEvent, action string) {
// TODO: map mouse
termMapKey(k, action)
}
type TermPane struct {
*shell.Terminal
display.Window
mouseReleased bool
id uint64
tab *Tab
}
func NewTermPane(x, y, w, h int, t *shell.Terminal, id uint64, tab *Tab) (*TermPane, error) {
if !TermEmuSupported {
return nil, errors.New("Terminal emulator is not supported on this system")
}
th := new(TermPane)
th.Terminal = t
th.id = id
th.mouseReleased = true
th.Window = display.NewTermWindow(x, y, w, h, t)
th.tab = tab
return th, nil
}
func (t *TermPane) ID() uint64 {
return t.id
}
func (t *TermPane) SetID(i uint64) {
t.id = i
}
func (t *TermPane) Name() string {
return t.Terminal.Name()
}
func (t *TermPane) SetTab(tab *Tab) {
t.tab = tab
}
func (t *TermPane) Tab() *Tab {
return t.tab
}
func (t *TermPane) Close() {}
// Quit closes this termpane
func (t *TermPane) Quit() {
t.Close()
if len(MainTab().Panes) > 1 {
t.Unsplit()
} else if len(Tabs.List) > 1 {
Tabs.RemoveTab(t.id)
} else {
screen.Screen.Fini()
InfoBar.Close()
runtime.Goexit()
}
}
// Unsplit removes this split
func (t *TermPane) Unsplit() {
n := MainTab().GetNode(t.id)
n.Unsplit()
MainTab().RemovePane(MainTab().GetPane(t.id))
MainTab().Resize()
MainTab().SetActive(len(MainTab().Panes) - 1)
}
// HandleEvent handles a tcell event by forwarding it to the terminal emulator
// If the event is a mouse event and the program running in the emulator
// does not have mouse support, the emulator will support selections and
// copy-paste
func (t *TermPane) HandleEvent(event tcell.Event) {
if e, ok := event.(*tcell.EventKey); ok {
ke := keyEvent(e)
action, more := TermBindings.NextEvent(ke, nil)
if !more {
if action != nil {
action(t)
TermBindings.ResetEvents()
return
}
TermBindings.ResetEvents()
}
if more {
return
}
if t.Status == shell.TTDone {
switch e.Key() {
case tcell.KeyEscape, tcell.KeyCtrlQ, tcell.KeyEnter:
t.Close()
t.Quit()
default:
}
}
if e.Key() == tcell.KeyCtrlC && t.HasSelection() {
clipboard.Write(t.GetSelection(t.GetView().Width), clipboard.ClipboardReg)
InfoBar.Message("Copied selection to clipboard")
} else if t.Status != shell.TTDone {
t.WriteString(event.EscSeq())
}
} else if _, ok := event.(*tcell.EventPaste); ok {
if t.Status != shell.TTDone {
t.WriteString(event.EscSeq())
}
} else if e, ok := event.(*tcell.EventMouse); !ok || t.State.Mode(terminal.ModeMouseMask) {
// t.WriteString(event.EscSeq())
} else {
x, y := e.Position()
v := t.GetView()
x -= v.X
y -= v.Y
if e.Buttons() == tcell.Button1 {
if !t.mouseReleased {
// drag
t.Selection[1].X = x
t.Selection[1].Y = y
} else {
t.Selection[0].X = x
t.Selection[0].Y = y
t.Selection[1].X = x
t.Selection[1].Y = y
}
t.mouseReleased = false
} else if e.Buttons() == tcell.ButtonNone {
if !t.mouseReleased {
t.Selection[1].X = x
t.Selection[1].Y = y
}
t.mouseReleased = true
}
}
}
// HandleTermClose is called when a terminal has finished its job
// and should be closed. If that terminal is this termpane's terminal,
// HandleTermClose will close the terminal and the termpane itself.
func (t *TermPane) HandleTermClose() {
if t.Status == shell.TTClose {
t.Quit()
}
}
// Exit closes the termpane
func (t *TermPane) Exit() {
t.Terminal.Close()
t.Quit()
}
// CommandMode opens the termpane's command mode
func (t *TermPane) CommandMode() {
InfoBar.Prompt("> ", "", "TerminalCommand", nil, func(resp string, canceled bool) {
if !canceled {
t.HandleCommand(resp)
}
})
}
// NextSplit moves to the next split
func (t *TermPane) NextSplit() {
a := t.tab.active
if a < len(t.tab.Panes)-1 {
a++
} else {
a = 0
}
t.tab.SetActive(a)
}
// HandleCommand handles a command for the term pane
func (t *TermPane) HandleCommand(input string) {
InfoBar.Error("Commands are unsupported in term for now")
}
// TermKeyActions contains the list of all possible key actions the termpane could execute
var TermKeyActions = map[string]TermKeyAction{
"Exit": (*TermPane).Exit,
"CommandMode": (*TermPane).CommandMode,
"NextSplit": (*TermPane).NextSplit,
}
```
|
/content/code_sandbox/internal/action/termpane.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 1,553
|
```go
//go:build !darwin
// +build !darwin
package action
var bufdefaults = map[string]string{
"Up": "CursorUp",
"Down": "CursorDown",
"Right": "CursorRight",
"Left": "CursorLeft",
"ShiftUp": "SelectUp",
"ShiftDown": "SelectDown",
"ShiftLeft": "SelectLeft",
"ShiftRight": "SelectRight",
"CtrlLeft": "WordLeft",
"CtrlRight": "WordRight",
"AltUp": "MoveLinesUp",
"AltDown": "MoveLinesDown",
"CtrlShiftRight": "SelectWordRight",
"CtrlShiftLeft": "SelectWordLeft",
"AltLeft": "StartOfTextToggle",
"AltRight": "EndOfLine",
"AltShiftLeft": "SelectToStartOfTextToggle",
"ShiftHome": "SelectToStartOfTextToggle",
"AltShiftRight": "SelectToEndOfLine",
"ShiftEnd": "SelectToEndOfLine",
"CtrlUp": "CursorStart",
"CtrlDown": "CursorEnd",
"CtrlShiftUp": "SelectToStart",
"CtrlShiftDown": "SelectToEnd",
"Alt-{": "ParagraphPrevious",
"Alt-}": "ParagraphNext",
"Enter": "InsertNewline",
"CtrlH": "Backspace",
"Backspace": "Backspace",
"OldBackspace": "Backspace",
"Alt-CtrlH": "DeleteWordLeft",
"Alt-Backspace": "DeleteWordLeft",
"Tab": "Autocomplete|IndentSelection|InsertTab",
"Backtab": "CycleAutocompleteBack|OutdentSelection|OutdentLine",
"Ctrl-o": "OpenFile",
"Ctrl-s": "Save",
"Ctrl-f": "Find",
"Alt-F": "FindLiteral",
"Ctrl-n": "FindNext",
"Ctrl-p": "FindPrevious",
"Alt-[": "DiffPrevious|CursorStart",
"Alt-]": "DiffNext|CursorEnd",
"Ctrl-z": "Undo",
"Ctrl-y": "Redo",
"Ctrl-c": "CopyLine|Copy",
"Ctrl-x": "Cut",
"Ctrl-k": "CutLine",
"Ctrl-d": "DuplicateLine",
"Ctrl-v": "Paste",
"Ctrl-a": "SelectAll",
"Ctrl-t": "AddTab",
"Alt-,": "PreviousTab",
"Alt-.": "NextTab",
"Home": "StartOfTextToggle",
"End": "EndOfLine",
"CtrlHome": "CursorStart",
"CtrlEnd": "CursorEnd",
"PageUp": "CursorPageUp",
"PageDown": "CursorPageDown",
"CtrlPageUp": "PreviousTab",
"CtrlPageDown": "NextTab",
"ShiftPageUp": "SelectPageUp",
"ShiftPageDown": "SelectPageDown",
"Ctrl-g": "ToggleHelp",
"Alt-g": "ToggleKeyMenu",
"Ctrl-r": "ToggleRuler",
"Ctrl-l": "command-edit:goto ",
"Delete": "Delete",
"Ctrl-b": "ShellMode",
"Ctrl-q": "Quit",
"Ctrl-e": "CommandMode",
"Ctrl-w": "NextSplit",
"Ctrl-u": "ToggleMacro",
"Ctrl-j": "PlayMacro",
"Insert": "ToggleOverwriteMode",
// Emacs-style keybindings
"Alt-f": "WordRight",
"Alt-b": "WordLeft",
"Alt-a": "StartOfText",
"Alt-e": "EndOfLine",
// "Alt-p": "CursorUp",
// "Alt-n": "CursorDown",
// Integration with file managers
"F2": "Save",
"F3": "Find",
"F4": "Quit",
"F7": "Find",
"F10": "Quit",
"Esc": "Escape,Deselect,ClearInfo,RemoveAllMultiCursors,UnhighlightSearch",
// Mouse bindings
"MouseWheelUp": "ScrollUp",
"MouseWheelDown": "ScrollDown",
"MouseLeft": "MousePress",
"MouseLeftDrag": "MouseDrag",
"MouseLeftRelease": "MouseRelease",
"MouseMiddle": "PastePrimary",
"Ctrl-MouseLeft": "MouseMultiCursor",
"Alt-n": "SpawnMultiCursor",
"Alt-m": "SpawnMultiCursorSelect",
"AltShiftUp": "SpawnMultiCursorUp",
"AltShiftDown": "SpawnMultiCursorDown",
"Alt-p": "RemoveMultiCursor",
"Alt-c": "RemoveAllMultiCursors",
"Alt-x": "SkipMultiCursor",
}
var infodefaults = map[string]string{
"Up": "HistoryUp",
"Down": "HistoryDown",
"Right": "CursorRight",
"Left": "CursorLeft",
"ShiftUp": "SelectUp",
"ShiftDown": "SelectDown",
"ShiftLeft": "SelectLeft",
"ShiftRight": "SelectRight",
"AltLeft": "StartOfTextToggle",
"AltRight": "EndOfLine",
"AltUp": "CursorStart",
"AltDown": "CursorEnd",
"AltShiftRight": "SelectWordRight",
"AltShiftLeft": "SelectWordLeft",
"CtrlLeft": "WordLeft",
"CtrlRight": "WordRight",
"CtrlShiftLeft": "SelectToStartOfTextToggle",
"ShiftHome": "SelectToStartOfTextToggle",
"CtrlShiftRight": "SelectToEndOfLine",
"ShiftEnd": "SelectToEndOfLine",
"CtrlUp": "CursorStart",
"CtrlDown": "CursorEnd",
"CtrlShiftUp": "SelectToStart",
"CtrlShiftDown": "SelectToEnd",
"Enter": "ExecuteCommand",
"CtrlH": "Backspace",
"Backspace": "Backspace",
"OldBackspace": "Backspace",
"Alt-CtrlH": "DeleteWordLeft",
"Alt-Backspace": "DeleteWordLeft",
"Tab": "CommandComplete",
"Backtab": "CycleAutocompleteBack",
"Ctrl-z": "Undo",
"Ctrl-y": "Redo",
"Ctrl-c": "CopyLine|Copy",
"Ctrl-x": "Cut",
"Ctrl-k": "CutLine",
"Ctrl-v": "Paste",
"Home": "StartOfTextToggle",
"End": "EndOfLine",
"CtrlHome": "CursorStart",
"CtrlEnd": "CursorEnd",
"Delete": "Delete",
"Ctrl-q": "AbortCommand",
"Ctrl-e": "EndOfLine",
"Ctrl-a": "StartOfLine",
"Ctrl-w": "DeleteWordLeft",
"Insert": "ToggleOverwriteMode",
"Ctrl-b": "WordLeft",
"Ctrl-f": "WordRight",
"Ctrl-d": "DeleteWordLeft",
"Ctrl-m": "ExecuteCommand",
"Ctrl-n": "HistoryDown",
"Ctrl-p": "HistoryUp",
"Ctrl-u": "SelectToStart",
// Emacs-style keybindings
"Alt-f": "WordRight",
"Alt-b": "WordLeft",
"Alt-a": "StartOfText",
"Alt-e": "EndOfLine",
// Integration with file managers
"F10": "AbortCommand",
"Esc": "AbortCommand",
// Mouse bindings
"MouseWheelUp": "HistoryUp",
"MouseWheelDown": "HistoryDown",
"MouseLeft": "MousePress",
"MouseLeftDrag": "MouseDrag",
"MouseLeftRelease": "MouseRelease",
"MouseMiddle": "PastePrimary",
}
```
|
/content/code_sandbox/internal/action/defaults_other.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 1,859
|
```go
package action
import (
"strings"
"time"
luar "layeh.com/gopher-luar"
lua "github.com/yuin/gopher-lua"
"github.com/zyedidia/micro/v2/internal/buffer"
"github.com/zyedidia/micro/v2/internal/config"
"github.com/zyedidia/micro/v2/internal/display"
ulua "github.com/zyedidia/micro/v2/internal/lua"
"github.com/zyedidia/micro/v2/internal/screen"
"github.com/zyedidia/micro/v2/internal/util"
"github.com/zyedidia/tcell/v2"
)
type BufAction interface{}
// BufKeyAction represents an action bound to a key.
type BufKeyAction func(*BufPane) bool
// BufMouseAction is an action that must be bound to a mouse event.
type BufMouseAction func(*BufPane, *tcell.EventMouse) bool
// BufBindings stores the bindings for the buffer pane type.
var BufBindings *KeyTree
// BufKeyActionGeneral makes a general pane action from a BufKeyAction.
func BufKeyActionGeneral(a BufKeyAction) PaneKeyAction {
return func(p Pane) bool {
return a(p.(*BufPane))
}
}
// BufMouseActionGeneral makes a general pane mouse action from a BufKeyAction.
func BufMouseActionGeneral(a BufMouseAction) PaneMouseAction {
return func(p Pane, me *tcell.EventMouse) bool {
return a(p.(*BufPane), me)
}
}
func init() {
BufBindings = NewKeyTree()
}
// LuaAction makes an action from a lua function. It returns either a BufKeyAction
// or a BufMouseAction depending on the event type.
func LuaAction(fn string, k Event) BufAction {
luaFn := strings.Split(fn, ".")
if len(luaFn) <= 1 {
return nil
}
plName, plFn := luaFn[0], luaFn[1]
pl := config.FindPlugin(plName)
if pl == nil {
return nil
}
var action BufAction
switch k.(type) {
case KeyEvent, KeySequenceEvent, RawEvent:
action = BufKeyAction(func(h *BufPane) bool {
val, err := pl.Call(plFn, luar.New(ulua.L, h))
if err != nil {
screen.TermMessage(err)
}
if v, ok := val.(lua.LBool); !ok {
return false
} else {
return bool(v)
}
})
case MouseEvent:
action = BufMouseAction(func(h *BufPane, te *tcell.EventMouse) bool {
val, err := pl.Call(plFn, luar.New(ulua.L, h), luar.New(ulua.L, te))
if err != nil {
screen.TermMessage(err)
}
if v, ok := val.(lua.LBool); !ok {
return false
} else {
return bool(v)
}
})
}
return action
}
// BufMapEvent maps an event to an action
func BufMapEvent(k Event, action string) {
config.Bindings["buffer"][k.Name()] = action
var actionfns []BufAction
var names []string
var types []byte
for i := 0; ; i++ {
if action == "" {
break
}
// TODO: fix problem when complex bindings have these
// characters (escape them?)
idx := strings.IndexAny(action, "&|,")
a := action
if idx >= 0 {
a = action[:idx]
types = append(types, action[idx])
action = action[idx+1:]
} else {
types = append(types, ' ')
action = ""
}
var afn BufAction
if strings.HasPrefix(a, "command:") {
a = strings.SplitN(a, ":", 2)[1]
afn = CommandAction(a)
names = append(names, "")
} else if strings.HasPrefix(a, "command-edit:") {
a = strings.SplitN(a, ":", 2)[1]
afn = CommandEditAction(a)
names = append(names, "")
} else if strings.HasPrefix(a, "lua:") {
a = strings.SplitN(a, ":", 2)[1]
afn = LuaAction(a, k)
if afn == nil {
screen.TermMessage("Lua Error:", a, "does not exist")
continue
}
split := strings.SplitN(a, ".", 2)
if len(split) > 1 {
a = strings.Title(split[0]) + strings.Title(split[1])
} else {
a = strings.Title(a)
}
names = append(names, a)
} else if f, ok := BufKeyActions[a]; ok {
afn = f
names = append(names, a)
} else if f, ok := BufMouseActions[a]; ok {
afn = f
names = append(names, a)
} else {
screen.TermMessage("Error in bindings: action", a, "does not exist")
continue
}
actionfns = append(actionfns, afn)
}
bufAction := func(h *BufPane, te *tcell.EventMouse) bool {
for i, a := range actionfns {
var success bool
if _, ok := MultiActions[names[i]]; ok {
success = true
for _, c := range h.Buf.GetCursors() {
h.Buf.SetCurCursor(c.Num)
h.Cursor = c
success = success && h.execAction(a, names[i], te)
}
} else {
h.Buf.SetCurCursor(0)
h.Cursor = h.Buf.GetActiveCursor()
success = h.execAction(a, names[i], te)
}
// if the action changed the current pane, update the reference
h = MainTab().CurPane()
if h == nil {
// stop, in case the current pane is not a BufPane
break
}
if (!success && types[i] == '&') || (success && types[i] == '|') {
break
}
}
return true
}
switch e := k.(type) {
case KeyEvent, KeySequenceEvent, RawEvent:
BufBindings.RegisterKeyBinding(e, BufKeyActionGeneral(func(h *BufPane) bool {
return bufAction(h, nil)
}))
case MouseEvent:
BufBindings.RegisterMouseBinding(e, BufMouseActionGeneral(bufAction))
}
}
// BufUnmap unmaps a key or mouse event from any action
func BufUnmap(k Event) {
// TODO
// delete(BufKeyBindings, k)
//
// switch e := k.(type) {
// case MouseEvent:
// delete(BufMouseBindings, e)
// }
}
// The BufPane connects the buffer and the window
// It provides a cursor (or multiple) and defines a set of actions
// that can be taken on the buffer
// The ActionHandler can access the window for necessary info about
// visual positions for mouse clicks and scrolling
type BufPane struct {
display.BWindow
// Buf is the buffer this BufPane views
Buf *buffer.Buffer
// Bindings stores the association of key events and actions
bindings *KeyTree
// Cursor is the currently active buffer cursor
Cursor *buffer.Cursor
// Since tcell doesn't differentiate between a mouse press event
// and a mouse move event with button pressed (nor between a mouse
// release event and a mouse move event with no buttons pressed),
// we need to keep track of whether or not the mouse was previously
// pressed, to determine mouse release and mouse drag events.
// Moreover, since in case of a release event tcell doesn't tell us
// which button was released, we need to keep track of which
// (possibly multiple) buttons were pressed previously.
mousePressed map[MouseEvent]bool
// We need to keep track of insert key press toggle
isOverwriteMode bool
// This stores when the last click was
// This is useful for detecting double and triple clicks
lastClickTime time.Time
lastLoc buffer.Loc
// lastCutTime stores when the last ctrl+k was issued.
// It is used for clearing the clipboard to replace it with fresh cut lines.
lastCutTime time.Time
// freshClip returns true if the clipboard has never been pasted.
freshClip bool
// Was the last mouse event actually a double click?
// Useful for detecting triple clicks -- if a double click is detected
// but the last mouse event was actually a double click, it's a triple click
doubleClick bool
// Same here, just to keep track for mouse move events
tripleClick bool
// Should the current multiple cursor selection search based on word or
// based on selection (false for selection, true for word)
multiWord bool
splitID uint64
tab *Tab
// remember original location of a search in case the search is canceled
searchOrig buffer.Loc
// The pane may not yet be fully initialized after its creation
// since we may not know the window geometry yet. In such case we finish
// its initialization a bit later, after the initial resize.
initialized bool
}
func newBufPane(buf *buffer.Buffer, win display.BWindow, tab *Tab) *BufPane {
h := new(BufPane)
h.Buf = buf
h.BWindow = win
h.tab = tab
h.Cursor = h.Buf.GetActiveCursor()
h.mousePressed = make(map[MouseEvent]bool)
return h
}
// NewBufPane creates a new buffer pane with the given window.
func NewBufPane(buf *buffer.Buffer, win display.BWindow, tab *Tab) *BufPane {
h := newBufPane(buf, win, tab)
h.finishInitialize()
return h
}
// NewBufPaneFromBuf constructs a new pane from the given buffer and automatically
// creates a buf window.
func NewBufPaneFromBuf(buf *buffer.Buffer, tab *Tab) *BufPane {
w := display.NewBufWindow(0, 0, 0, 0, buf)
h := newBufPane(buf, w, tab)
// Postpone finishing initializing the pane until we know the actual geometry
// of the buf window.
return h
}
// TODO: make sure splitID and tab are set before finishInitialize is called
func (h *BufPane) finishInitialize() {
h.initialRelocate()
h.initialized = true
err := config.RunPluginFn("onBufPaneOpen", luar.New(ulua.L, h))
if err != nil {
screen.TermMessage(err)
}
}
// Resize resizes the pane
func (h *BufPane) Resize(width, height int) {
h.BWindow.Resize(width, height)
if !h.initialized {
h.finishInitialize()
}
}
// SetTab sets this pane's tab.
func (h *BufPane) SetTab(t *Tab) {
h.tab = t
}
// Tab returns this pane's tab.
func (h *BufPane) Tab() *Tab {
return h.tab
}
func (h *BufPane) ResizePane(size int) {
n := h.tab.GetNode(h.splitID)
n.ResizeSplit(size)
h.tab.Resize()
}
// PluginCB calls all plugin callbacks with a certain name and displays an
// error if there is one and returns the aggregate boolean response
func (h *BufPane) PluginCB(cb string) bool {
b, err := config.RunPluginFnBool(h.Buf.Settings, cb, luar.New(ulua.L, h))
if err != nil {
screen.TermMessage(err)
}
return b
}
// PluginCBRune is the same as PluginCB but also passes a rune to the plugins
func (h *BufPane) PluginCBRune(cb string, r rune) bool {
b, err := config.RunPluginFnBool(h.Buf.Settings, cb, luar.New(ulua.L, h), luar.New(ulua.L, string(r)))
if err != nil {
screen.TermMessage(err)
}
return b
}
func (h *BufPane) resetMouse() {
for me := range h.mousePressed {
delete(h.mousePressed, me)
}
}
// OpenBuffer opens the given buffer in this pane.
func (h *BufPane) OpenBuffer(b *buffer.Buffer) {
h.Buf.Close()
h.Buf = b
h.BWindow.SetBuffer(b)
h.Cursor = b.GetActiveCursor()
h.Resize(h.GetView().Width, h.GetView().Height)
h.initialRelocate()
// Set mouseReleased to true because we assume the mouse is not being
// pressed when the editor is opened
h.resetMouse()
// Set isOverwriteMode to false, because we assume we are in the default
// mode when editor is opened
h.isOverwriteMode = false
h.lastClickTime = time.Time{}
}
// GotoLoc moves the cursor to a new location and adjusts the view accordingly.
// Use GotoLoc when the new location may be far away from the current location.
func (h *BufPane) GotoLoc(loc buffer.Loc) {
sloc := h.SLocFromLoc(loc)
d := h.Diff(h.SLocFromLoc(h.Cursor.Loc), sloc)
h.Cursor.GotoLoc(loc)
// If the new location is far away from the previous one,
// ensure the cursor is at 25% of the window height
height := h.BufView().Height
if util.Abs(d) >= height {
v := h.GetView()
v.StartLine = h.Scroll(sloc, -height/4)
h.ScrollAdjust()
v.StartCol = 0
}
h.Relocate()
}
func (h *BufPane) initialRelocate() {
sloc := h.SLocFromLoc(h.Cursor.Loc)
height := h.BufView().Height
// If the initial cursor location is far away from the beginning
// of the buffer, ensure the cursor is at 25% of the window height
v := h.GetView()
if h.Diff(display.SLoc{0, 0}, sloc) < height {
v.StartLine = display.SLoc{0, 0}
} else {
v.StartLine = h.Scroll(sloc, -height/4)
h.ScrollAdjust()
}
v.StartCol = 0
h.Relocate()
}
// ID returns this pane's split id.
func (h *BufPane) ID() uint64 {
return h.splitID
}
// SetID sets the split ID of this pane.
func (h *BufPane) SetID(i uint64) {
h.splitID = i
}
// Name returns the BufPane's name.
func (h *BufPane) Name() string {
n := h.Buf.GetName()
if h.Buf.Modified() {
n += " +"
}
return n
}
// ReOpen reloads the file opened in the bufpane from disk
func (h *BufPane) ReOpen() {
h.Buf.ReOpen()
h.Relocate()
}
func (h *BufPane) getReloadSetting() string {
reloadSetting := h.Buf.Settings["reload"]
return reloadSetting.(string)
}
// HandleEvent executes the tcell event properly
func (h *BufPane) HandleEvent(event tcell.Event) {
if h.Buf.ExternallyModified() && !h.Buf.ReloadDisabled {
reload := h.getReloadSetting()
if reload == "prompt" {
InfoBar.YNPrompt("The file on disk has changed. Reload file? (y,n,esc)", func(yes, canceled bool) {
if canceled {
h.Buf.DisableReload()
}
if !yes || canceled {
h.Buf.UpdateModTime()
} else {
h.ReOpen()
}
})
} else if reload == "auto" {
h.ReOpen()
} else if reload == "disabled" {
h.Buf.DisableReload()
} else {
InfoBar.Message("Invalid reload setting")
}
}
switch e := event.(type) {
case *tcell.EventRaw:
re := RawEvent{
esc: e.EscSeq(),
}
h.DoKeyEvent(re)
case *tcell.EventPaste:
h.paste(e.Text())
h.Relocate()
case *tcell.EventKey:
ke := keyEvent(e)
done := h.DoKeyEvent(ke)
if !done && e.Key() == tcell.KeyRune {
h.DoRuneInsert(e.Rune())
}
case *tcell.EventMouse:
if e.Buttons() != tcell.ButtonNone {
me := MouseEvent{
btn: e.Buttons(),
mod: metaToAlt(e.Modifiers()),
state: MousePress,
}
isDrag := len(h.mousePressed) > 0
if e.Buttons() & ^(tcell.WheelUp|tcell.WheelDown|tcell.WheelLeft|tcell.WheelRight) != tcell.ButtonNone {
h.mousePressed[me] = true
}
if isDrag {
me.state = MouseDrag
}
h.DoMouseEvent(me, e)
} else {
// Mouse event with no click - mouse was just released.
// If there were multiple mouse buttons pressed, we don't know which one
// was actually released, so we assume they all were released.
pressed := len(h.mousePressed) > 0
for me := range h.mousePressed {
delete(h.mousePressed, me)
me.state = MouseRelease
h.DoMouseEvent(me, e)
}
if !pressed {
// Propagate the mouse release in case the press wasn't for this BufPane
Tabs.ResetMouse()
}
}
}
h.Buf.MergeCursors()
if h.IsActive() {
// Display any gutter messages for this line
c := h.Buf.GetActiveCursor()
none := true
for _, m := range h.Buf.Messages {
if c.Y == m.Start.Y || c.Y == m.End.Y {
InfoBar.GutterMessage(m.Msg)
none = false
break
}
}
if none && InfoBar.HasGutter {
InfoBar.ClearGutter()
}
}
cursors := h.Buf.GetCursors()
for _, c := range cursors {
if c.NewTrailingWsY != c.Y && (!c.HasSelection() ||
(c.NewTrailingWsY != c.CurSelection[0].Y && c.NewTrailingWsY != c.CurSelection[1].Y)) {
c.NewTrailingWsY = -1
}
}
}
// Bindings returns the current bindings tree for this buffer.
func (h *BufPane) Bindings() *KeyTree {
if h.bindings != nil {
return h.bindings
}
return BufBindings
}
// DoKeyEvent executes a key event by finding the action it is bound
// to and executing it (possibly multiple times for multiple cursors).
// Returns true if the action was executed OR if there are more keys
// remaining to process before executing an action (if this is a key
// sequence event). Returns false if no action found.
func (h *BufPane) DoKeyEvent(e Event) bool {
binds := h.Bindings()
action, more := binds.NextEvent(e, nil)
if action != nil && !more {
action(h)
binds.ResetEvents()
return true
} else if action == nil && !more {
binds.ResetEvents()
}
return more
}
func (h *BufPane) execAction(action BufAction, name string, te *tcell.EventMouse) bool {
if name != "Autocomplete" && name != "CycleAutocompleteBack" {
h.Buf.HasSuggestions = false
}
if !h.PluginCB("pre" + name) {
return false
}
var success bool
switch a := action.(type) {
case BufKeyAction:
success = a(h)
case BufMouseAction:
success = a(h, te)
}
success = success && h.PluginCB("on"+name)
if _, ok := MultiActions[name]; ok {
if recordingMacro {
if name != "ToggleMacro" && name != "PlayMacro" {
curmacro = append(curmacro, action)
}
}
}
return success
}
func (h *BufPane) completeAction(action string) {
h.PluginCB("on" + action)
}
func (h *BufPane) HasKeyEvent(e Event) bool {
// TODO
return true
// _, ok := BufKeyBindings[e]
// return ok
}
// DoMouseEvent executes a mouse event by finding the action it is bound
// to and executing it
func (h *BufPane) DoMouseEvent(e MouseEvent, te *tcell.EventMouse) bool {
binds := h.Bindings()
action, _ := binds.NextEvent(e, te)
if action != nil {
action(h)
binds.ResetEvents()
return true
}
// TODO
return false
// if action, ok := BufMouseBindings[e]; ok {
// if action(h, te) {
// h.Relocate()
// }
// return true
// } else if h.HasKeyEvent(e) {
// return h.DoKeyEvent(e)
// }
// return false
}
// DoRuneInsert inserts a given rune into the current buffer
// (possibly multiple times for multiple cursors)
func (h *BufPane) DoRuneInsert(r rune) {
cursors := h.Buf.GetCursors()
for _, c := range cursors {
// Insert a character
h.Buf.SetCurCursor(c.Num)
h.Cursor = c
if !h.PluginCBRune("preRune", r) {
continue
}
if c.HasSelection() {
c.DeleteSelection()
c.ResetSelection()
}
if h.isOverwriteMode {
next := c.Loc
next.X++
h.Buf.Replace(c.Loc, next, string(r))
} else {
h.Buf.Insert(c.Loc, string(r))
}
if recordingMacro {
curmacro = append(curmacro, r)
}
h.Relocate()
h.PluginCBRune("onRune", r)
}
}
// VSplitIndex opens the given buffer in a vertical split on the given side.
func (h *BufPane) VSplitIndex(buf *buffer.Buffer, right bool) *BufPane {
e := NewBufPaneFromBuf(buf, h.tab)
e.splitID = MainTab().GetNode(h.splitID).VSplit(right)
MainTab().Panes = append(MainTab().Panes, e)
MainTab().Resize()
MainTab().SetActive(len(MainTab().Panes) - 1)
return e
}
// HSplitIndex opens the given buffer in a horizontal split on the given side.
func (h *BufPane) HSplitIndex(buf *buffer.Buffer, bottom bool) *BufPane {
e := NewBufPaneFromBuf(buf, h.tab)
e.splitID = MainTab().GetNode(h.splitID).HSplit(bottom)
MainTab().Panes = append(MainTab().Panes, e)
MainTab().Resize()
MainTab().SetActive(len(MainTab().Panes) - 1)
return e
}
// VSplitBuf opens the given buffer in a new vertical split.
func (h *BufPane) VSplitBuf(buf *buffer.Buffer) *BufPane {
return h.VSplitIndex(buf, h.Buf.Settings["splitright"].(bool))
}
// HSplitBuf opens the given buffer in a new horizontal split.
func (h *BufPane) HSplitBuf(buf *buffer.Buffer) *BufPane {
return h.HSplitIndex(buf, h.Buf.Settings["splitbottom"].(bool))
}
// Close this pane.
func (h *BufPane) Close() {
h.Buf.Close()
}
// SetActive marks this pane as active.
func (h *BufPane) SetActive(b bool) {
if h.IsActive() == b {
return
}
h.BWindow.SetActive(b)
if b {
// Display any gutter messages for this line
c := h.Buf.GetActiveCursor()
none := true
for _, m := range h.Buf.Messages {
if c.Y == m.Start.Y || c.Y == m.End.Y {
InfoBar.GutterMessage(m.Msg)
none = false
break
}
}
if none && InfoBar.HasGutter {
InfoBar.ClearGutter()
}
err := config.RunPluginFn("onSetActive", luar.New(ulua.L, h))
if err != nil {
screen.TermMessage(err)
}
}
}
// BufKeyActions contains the list of all possible key actions the bufhandler could execute
var BufKeyActions = map[string]BufKeyAction{
"CursorUp": (*BufPane).CursorUp,
"CursorDown": (*BufPane).CursorDown,
"CursorPageUp": (*BufPane).CursorPageUp,
"CursorPageDown": (*BufPane).CursorPageDown,
"CursorLeft": (*BufPane).CursorLeft,
"CursorRight": (*BufPane).CursorRight,
"CursorStart": (*BufPane).CursorStart,
"CursorEnd": (*BufPane).CursorEnd,
"SelectToStart": (*BufPane).SelectToStart,
"SelectToEnd": (*BufPane).SelectToEnd,
"SelectUp": (*BufPane).SelectUp,
"SelectDown": (*BufPane).SelectDown,
"SelectLeft": (*BufPane).SelectLeft,
"SelectRight": (*BufPane).SelectRight,
"WordRight": (*BufPane).WordRight,
"WordLeft": (*BufPane).WordLeft,
"SubWordRight": (*BufPane).SubWordRight,
"SubWordLeft": (*BufPane).SubWordLeft,
"SelectWordRight": (*BufPane).SelectWordRight,
"SelectWordLeft": (*BufPane).SelectWordLeft,
"SelectSubWordRight": (*BufPane).SelectSubWordRight,
"SelectSubWordLeft": (*BufPane).SelectSubWordLeft,
"DeleteWordRight": (*BufPane).DeleteWordRight,
"DeleteWordLeft": (*BufPane).DeleteWordLeft,
"DeleteSubWordRight": (*BufPane).DeleteSubWordRight,
"DeleteSubWordLeft": (*BufPane).DeleteSubWordLeft,
"SelectLine": (*BufPane).SelectLine,
"SelectToStartOfLine": (*BufPane).SelectToStartOfLine,
"SelectToStartOfText": (*BufPane).SelectToStartOfText,
"SelectToStartOfTextToggle": (*BufPane).SelectToStartOfTextToggle,
"SelectToEndOfLine": (*BufPane).SelectToEndOfLine,
"ParagraphPrevious": (*BufPane).ParagraphPrevious,
"ParagraphNext": (*BufPane).ParagraphNext,
"SelectToParagraphPrevious": (*BufPane).SelectToParagraphPrevious,
"SelectToParagraphNext": (*BufPane).SelectToParagraphNext,
"InsertNewline": (*BufPane).InsertNewline,
"Backspace": (*BufPane).Backspace,
"Delete": (*BufPane).Delete,
"InsertTab": (*BufPane).InsertTab,
"Save": (*BufPane).Save,
"SaveAll": (*BufPane).SaveAll,
"SaveAs": (*BufPane).SaveAs,
"Find": (*BufPane).Find,
"FindLiteral": (*BufPane).FindLiteral,
"FindNext": (*BufPane).FindNext,
"FindPrevious": (*BufPane).FindPrevious,
"DiffNext": (*BufPane).DiffNext,
"DiffPrevious": (*BufPane).DiffPrevious,
"Center": (*BufPane).Center,
"Undo": (*BufPane).Undo,
"Redo": (*BufPane).Redo,
"Copy": (*BufPane).Copy,
"CopyLine": (*BufPane).CopyLine,
"Cut": (*BufPane).Cut,
"CutLine": (*BufPane).CutLine,
"DuplicateLine": (*BufPane).DuplicateLine,
"DeleteLine": (*BufPane).DeleteLine,
"MoveLinesUp": (*BufPane).MoveLinesUp,
"MoveLinesDown": (*BufPane).MoveLinesDown,
"IndentSelection": (*BufPane).IndentSelection,
"OutdentSelection": (*BufPane).OutdentSelection,
"Autocomplete": (*BufPane).Autocomplete,
"CycleAutocompleteBack": (*BufPane).CycleAutocompleteBack,
"OutdentLine": (*BufPane).OutdentLine,
"IndentLine": (*BufPane).IndentLine,
"Paste": (*BufPane).Paste,
"PastePrimary": (*BufPane).PastePrimary,
"SelectAll": (*BufPane).SelectAll,
"OpenFile": (*BufPane).OpenFile,
"Start": (*BufPane).Start,
"End": (*BufPane).End,
"PageUp": (*BufPane).PageUp,
"PageDown": (*BufPane).PageDown,
"SelectPageUp": (*BufPane).SelectPageUp,
"SelectPageDown": (*BufPane).SelectPageDown,
"HalfPageUp": (*BufPane).HalfPageUp,
"HalfPageDown": (*BufPane).HalfPageDown,
"StartOfText": (*BufPane).StartOfText,
"StartOfTextToggle": (*BufPane).StartOfTextToggle,
"StartOfLine": (*BufPane).StartOfLine,
"EndOfLine": (*BufPane).EndOfLine,
"ToggleHelp": (*BufPane).ToggleHelp,
"ToggleKeyMenu": (*BufPane).ToggleKeyMenu,
"ToggleDiffGutter": (*BufPane).ToggleDiffGutter,
"ToggleRuler": (*BufPane).ToggleRuler,
"ToggleHighlightSearch": (*BufPane).ToggleHighlightSearch,
"UnhighlightSearch": (*BufPane).UnhighlightSearch,
"ResetSearch": (*BufPane).ResetSearch,
"ClearStatus": (*BufPane).ClearStatus,
"ShellMode": (*BufPane).ShellMode,
"CommandMode": (*BufPane).CommandMode,
"ToggleOverwriteMode": (*BufPane).ToggleOverwriteMode,
"Escape": (*BufPane).Escape,
"Quit": (*BufPane).Quit,
"QuitAll": (*BufPane).QuitAll,
"ForceQuit": (*BufPane).ForceQuit,
"AddTab": (*BufPane).AddTab,
"PreviousTab": (*BufPane).PreviousTab,
"NextTab": (*BufPane).NextTab,
"NextSplit": (*BufPane).NextSplit,
"PreviousSplit": (*BufPane).PreviousSplit,
"Unsplit": (*BufPane).Unsplit,
"VSplit": (*BufPane).VSplitAction,
"HSplit": (*BufPane).HSplitAction,
"ToggleMacro": (*BufPane).ToggleMacro,
"PlayMacro": (*BufPane).PlayMacro,
"Suspend": (*BufPane).Suspend,
"ScrollUp": (*BufPane).ScrollUpAction,
"ScrollDown": (*BufPane).ScrollDownAction,
"SpawnMultiCursor": (*BufPane).SpawnMultiCursor,
"SpawnMultiCursorUp": (*BufPane).SpawnMultiCursorUp,
"SpawnMultiCursorDown": (*BufPane).SpawnMultiCursorDown,
"SpawnMultiCursorSelect": (*BufPane).SpawnMultiCursorSelect,
"RemoveMultiCursor": (*BufPane).RemoveMultiCursor,
"RemoveAllMultiCursors": (*BufPane).RemoveAllMultiCursors,
"SkipMultiCursor": (*BufPane).SkipMultiCursor,
"JumpToMatchingBrace": (*BufPane).JumpToMatchingBrace,
"JumpLine": (*BufPane).JumpLine,
"Deselect": (*BufPane).Deselect,
"ClearInfo": (*BufPane).ClearInfo,
"None": (*BufPane).None,
// This was changed to InsertNewline but I don't want to break backwards compatibility
"InsertEnter": (*BufPane).InsertNewline,
}
// BufMouseActions contains the list of all possible mouse actions the bufhandler could execute
var BufMouseActions = map[string]BufMouseAction{
"MousePress": (*BufPane).MousePress,
"MouseDrag": (*BufPane).MouseDrag,
"MouseRelease": (*BufPane).MouseRelease,
"MouseMultiCursor": (*BufPane).MouseMultiCursor,
}
// MultiActions is a list of actions that should be executed multiple
// times if there are multiple cursors (one per cursor)
// Generally actions that modify global editor state like quitting or
// saving should not be included in this list
var MultiActions = map[string]bool{
"CursorUp": true,
"CursorDown": true,
"CursorPageUp": true,
"CursorPageDown": true,
"CursorLeft": true,
"CursorRight": true,
"CursorStart": true,
"CursorEnd": true,
"SelectToStart": true,
"SelectToEnd": true,
"SelectUp": true,
"SelectDown": true,
"SelectLeft": true,
"SelectRight": true,
"WordRight": true,
"WordLeft": true,
"SubWordRight": true,
"SubWordLeft": true,
"SelectWordRight": true,
"SelectWordLeft": true,
"SelectSubWordRight": true,
"SelectSubWordLeft": true,
"DeleteWordRight": true,
"DeleteWordLeft": true,
"DeleteSubWordRight": true,
"DeleteSubWordLeft": true,
"SelectLine": true,
"SelectToStartOfLine": true,
"SelectToStartOfText": true,
"SelectToStartOfTextToggle": true,
"SelectToEndOfLine": true,
"ParagraphPrevious": true,
"ParagraphNext": true,
"InsertNewline": true,
"Backspace": true,
"Delete": true,
"InsertTab": true,
"FindNext": true,
"FindPrevious": true,
"CopyLine": true,
"Copy": true,
"Cut": true,
"CutLine": true,
"DuplicateLine": true,
"DeleteLine": true,
"MoveLinesUp": true,
"MoveLinesDown": true,
"IndentSelection": true,
"OutdentSelection": true,
"OutdentLine": true,
"IndentLine": true,
"Paste": true,
"PastePrimary": true,
"SelectPageUp": true,
"SelectPageDown": true,
"StartOfLine": true,
"StartOfText": true,
"StartOfTextToggle": true,
"EndOfLine": true,
"JumpToMatchingBrace": true,
}
```
|
/content/code_sandbox/internal/action/bufpane.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 7,834
|
```go
package config
import (
"time"
)
var Autosave chan bool
var autotime chan float64
func init() {
Autosave = make(chan bool)
autotime = make(chan float64)
}
func SetAutoTime(a float64) {
autotime <- a
}
func StartAutoSave() {
go func() {
var a float64
var t *time.Timer
var elapsed <-chan time.Time
for {
select {
case a = <-autotime:
if t != nil {
t.Stop()
for len(elapsed) > 0 {
<-elapsed
}
}
if a > 0 {
if t != nil {
t.Reset(time.Duration(a * float64(time.Second)))
} else {
t = time.NewTimer(time.Duration(a * float64(time.Second)))
elapsed = t.C
}
}
case <-elapsed:
if a > 0 {
t.Reset(time.Duration(a * float64(time.Second)))
Autosave <- true
}
}
}
}()
}
```
|
/content/code_sandbox/internal/config/autosave.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 240
|
```go
package config
const (
DoubleClickThreshold = 400 // How many milliseconds to wait before a second click is not a double click
)
var Bindings map[string]map[string]string
func init() {
Bindings = map[string]map[string]string{
"command": make(map[string]string),
"buffer": make(map[string]string),
"terminal": make(map[string]string),
}
}
```
|
/content/code_sandbox/internal/config/globals.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 88
|
```go
package config
import (
"errors"
"os"
"path/filepath"
homedir "github.com/mitchellh/go-homedir"
)
var ConfigDir string
// InitConfigDir finds the configuration directory for micro according to the XDG spec.
// If no directory is found, it creates one.
func InitConfigDir(flagConfigDir string) error {
var e error
microHome := os.Getenv("MICRO_CONFIG_HOME")
if microHome == "" {
// The user has not set $MICRO_CONFIG_HOME so we'll try $XDG_CONFIG_HOME
xdgHome := os.Getenv("XDG_CONFIG_HOME")
if xdgHome == "" {
// The user has not set $XDG_CONFIG_HOME so we should act like it was set to ~/.config
home, err := homedir.Dir()
if err != nil {
return errors.New("Error finding your home directory\nCan't load config files: " + err.Error())
}
xdgHome = filepath.Join(home, ".config")
}
microHome = filepath.Join(xdgHome, "micro")
}
ConfigDir = microHome
if len(flagConfigDir) > 0 {
if _, err := os.Stat(flagConfigDir); os.IsNotExist(err) {
e = errors.New("Error: " + flagConfigDir + " does not exist. Defaulting to " + ConfigDir + ".")
} else {
ConfigDir = flagConfigDir
return nil
}
}
// Create micro config home directory if it does not exist
// This creates parent directories and does nothing if it already exists
err := os.MkdirAll(ConfigDir, os.ModePerm)
if err != nil {
return errors.New("Error creating configuration directory: " + err.Error())
}
return e
}
```
|
/content/code_sandbox/internal/config/config.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 391
|
```go
package config
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/zyedidia/tcell/v2"
)
func TestSimpleStringToStyle(t *testing.T) {
s := StringToStyle("lightblue,magenta")
fg, bg, _ := s.Decompose()
assert.Equal(t, tcell.ColorBlue, fg)
assert.Equal(t, tcell.ColorPurple, bg)
}
func TestAttributeStringToStyle(t *testing.T) {
s := StringToStyle("bold cyan,brightcyan")
fg, bg, attr := s.Decompose()
assert.Equal(t, tcell.ColorTeal, fg)
assert.Equal(t, tcell.ColorAqua, bg)
assert.NotEqual(t, 0, attr&tcell.AttrBold)
}
func TestMultiAttributesStringToStyle(t *testing.T) {
s := StringToStyle("bold italic underline cyan,brightcyan")
fg, bg, attr := s.Decompose()
assert.Equal(t, tcell.ColorTeal, fg)
assert.Equal(t, tcell.ColorAqua, bg)
assert.NotEqual(t, 0, attr&tcell.AttrBold)
assert.NotEqual(t, 0, attr&tcell.AttrItalic)
assert.NotEqual(t, 0, attr&tcell.AttrUnderline)
}
func TestColor256StringToStyle(t *testing.T) {
s := StringToStyle("128,60")
fg, bg, _ := s.Decompose()
assert.Equal(t, tcell.Color128, fg)
assert.Equal(t, tcell.Color60, bg)
}
func TestColorHexStringToStyle(t *testing.T) {
s := StringToStyle("#deadbe,#ef1234")
fg, bg, _ := s.Decompose()
assert.Equal(t, tcell.NewRGBColor(222, 173, 190), fg)
assert.Equal(t, tcell.NewRGBColor(239, 18, 52), bg)
}
func TestColorschemeParser(t *testing.T) {
testColorscheme := `color-link default "#F8F8F2,#282828"
color-link comment "#75715E,#282828"
# comment
color-link identifier "#66D9EF,#282828" #comment
color-link constant "#AE81FF,#282828"
color-link constant.string "#E6DB74,#282828"
color-link constant.string.char "#BDE6AD,#282828"`
c, err := ParseColorscheme("testColorscheme", testColorscheme, nil)
assert.Nil(t, err)
fg, bg, _ := c["comment"].Decompose()
assert.Equal(t, tcell.NewRGBColor(117, 113, 94), fg)
assert.Equal(t, tcell.NewRGBColor(40, 40, 40), bg)
}
```
|
/content/code_sandbox/internal/config/colorscheme_test.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 586
|
```go
package config
import (
"testing"
"github.com/stretchr/testify/assert"
)
func init() {
InitRuntimeFiles(false)
}
func TestAddFile(t *testing.T) {
AddRuntimeFile(RTPlugin, memoryFile{"foo.lua", []byte("hello world\n")})
AddRuntimeFile(RTSyntax, memoryFile{"bar", []byte("some syntax file\n")})
f1 := FindRuntimeFile(RTPlugin, "foo.lua")
assert.NotNil(t, f1)
assert.Equal(t, "foo.lua", f1.Name())
data, err := f1.Data()
assert.Nil(t, err)
assert.Equal(t, []byte("hello world\n"), data)
f2 := FindRuntimeFile(RTSyntax, "bar")
assert.NotNil(t, f2)
assert.Equal(t, "bar", f2.Name())
data, err = f2.Data()
assert.Nil(t, err)
assert.Equal(t, []byte("some syntax file\n"), data)
}
func TestFindFile(t *testing.T) {
f := FindRuntimeFile(RTSyntax, "go")
assert.NotNil(t, f)
assert.Equal(t, "go", f.Name())
data, err := f.Data()
assert.Nil(t, err)
assert.Equal(t, []byte("filetype: go"), data[:12])
e := FindRuntimeFile(RTSyntax, "foobar")
assert.Nil(t, e)
}
```
|
/content/code_sandbox/internal/config/rtfiles_test.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 285
|
```go
package config
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"reflect"
"runtime"
"strconv"
"strings"
"github.com/zyedidia/glob"
"github.com/zyedidia/json5"
"github.com/zyedidia/micro/v2/internal/util"
"golang.org/x/text/encoding/htmlindex"
)
type optionValidator func(string, interface{}) error
// a list of settings that need option validators
var optionValidators = map[string]optionValidator{
"autosave": validateNonNegativeValue,
"clipboard": validateChoice,
"colorcolumn": validateNonNegativeValue,
"colorscheme": validateColorscheme,
"detectlimit": validateNonNegativeValue,
"encoding": validateEncoding,
"fileformat": validateChoice,
"matchbracestyle": validateChoice,
"multiopen": validateChoice,
"reload": validateChoice,
"scrollmargin": validateNonNegativeValue,
"scrollspeed": validateNonNegativeValue,
"tabsize": validatePositiveValue,
}
// a list of settings with pre-defined choices
var OptionChoices = map[string][]string{
"clipboard": {"internal", "external", "terminal"},
"fileformat": {"unix", "dos"},
"matchbracestyle": {"underline", "highlight"},
"multiopen": {"tab", "hsplit", "vsplit"},
"reload": {"prompt", "auto", "disabled"},
}
// a list of settings that can be globally and locally modified and their
// default values
var defaultCommonSettings = map[string]interface{}{
"autoindent": true,
"autosu": false,
"backup": true,
"backupdir": "",
"basename": false,
"colorcolumn": float64(0),
"cursorline": true,
"detectlimit": float64(100),
"diffgutter": false,
"encoding": "utf-8",
"eofnewline": true,
"fastdirty": false,
"fileformat": defaultFileFormat(),
"filetype": "unknown",
"hlsearch": false,
"hltaberrors": false,
"hltrailingws": false,
"incsearch": true,
"ignorecase": true,
"indentchar": " ",
"keepautoindent": false,
"matchbrace": true,
"matchbraceleft": true,
"matchbracestyle": "underline",
"mkparents": false,
"permbackup": false,
"readonly": false,
"reload": "prompt",
"rmtrailingws": false,
"ruler": true,
"relativeruler": false,
"savecursor": false,
"saveundo": false,
"scrollbar": false,
"scrollmargin": float64(3),
"scrollspeed": float64(2),
"smartpaste": true,
"softwrap": false,
"splitbottom": true,
"splitright": true,
"statusformatl": "$(filename) $(modified)($(line),$(col)) $(status.paste)| ft:$(opt:filetype) | $(opt:fileformat) | $(opt:encoding)",
"statusformatr": "$(bind:ToggleKeyMenu): bindings, $(bind:ToggleHelp): help",
"statusline": true,
"syntax": true,
"tabmovement": false,
"tabsize": float64(4),
"tabstospaces": false,
"useprimary": true,
"wordwrap": false,
}
// a list of settings that should only be globally modified and their
// default values
var DefaultGlobalOnlySettings = map[string]interface{}{
"autosave": float64(0),
"clipboard": "external",
"colorscheme": "default",
"divchars": "|-",
"divreverse": true,
"fakecursor": false,
"infobar": true,
"keymenu": false,
"mouse": true,
"multiopen": "tab",
"parsecursor": false,
"paste": false,
"pluginchannels": []string{"path_to_url"},
"pluginrepos": []string{},
"savehistory": true,
"scrollbarchar": "|",
"sucmd": "sudo",
"tabhighlight": false,
"tabreverse": true,
"xterm": false,
}
// a list of settings that should never be globally modified
var LocalSettings = []string{
"filetype",
"readonly",
}
var (
ErrInvalidOption = errors.New("Invalid option")
ErrInvalidValue = errors.New("Invalid value")
// The options that the user can set
GlobalSettings map[string]interface{}
// This is the raw parsed json
parsedSettings map[string]interface{}
settingsParseError bool
// ModifiedSettings is a map of settings which should be written to disk
// because they have been modified by the user in this session
ModifiedSettings map[string]bool
// VolatileSettings is a map of settings which should not be written to disk
// because they have been temporarily set for this session only
VolatileSettings map[string]bool
)
func init() {
ModifiedSettings = make(map[string]bool)
VolatileSettings = make(map[string]bool)
}
func validateParsedSettings() error {
var err error
defaults := DefaultAllSettings()
for k, v := range parsedSettings {
if strings.HasPrefix(reflect.TypeOf(v).String(), "map") {
if strings.HasPrefix(k, "ft:") {
for k1, v1 := range v.(map[string]interface{}) {
if _, ok := defaults[k1]; ok {
if e := verifySetting(k1, v1, defaults[k1]); e != nil {
err = e
parsedSettings[k].(map[string]interface{})[k1] = defaults[k1]
continue
}
}
}
} else {
if _, e := glob.Compile(k); e != nil {
err = errors.New("Error with glob setting " + k + ": " + e.Error())
delete(parsedSettings, k)
continue
}
for k1, v1 := range v.(map[string]interface{}) {
if _, ok := defaults[k1]; ok {
if e := verifySetting(k1, v1, defaults[k1]); e != nil {
err = e
parsedSettings[k].(map[string]interface{})[k1] = defaults[k1]
continue
}
}
}
}
continue
}
if k == "autosave" {
// if autosave is a boolean convert it to float
s, ok := v.(bool)
if ok {
if s {
parsedSettings["autosave"] = 8.0
} else {
parsedSettings["autosave"] = 0.0
}
}
continue
}
if _, ok := defaults[k]; ok {
if e := verifySetting(k, v, defaults[k]); e != nil {
err = e
parsedSettings[k] = defaults[k]
continue
}
}
}
return err
}
func ReadSettings() error {
parsedSettings = make(map[string]interface{})
filename := filepath.Join(ConfigDir, "settings.json")
if _, e := os.Stat(filename); e == nil {
input, err := ioutil.ReadFile(filename)
if err != nil {
settingsParseError = true
return errors.New("Error reading settings.json file: " + err.Error())
}
if !strings.HasPrefix(string(input), "null") {
// Unmarshal the input into the parsed map
err = json5.Unmarshal(input, &parsedSettings)
if err != nil {
settingsParseError = true
return errors.New("Error reading settings.json: " + err.Error())
}
err = validateParsedSettings()
if err != nil {
return err
}
}
}
return nil
}
func ParsedSettings() map[string]interface{} {
s := make(map[string]interface{})
for k, v := range parsedSettings {
s[k] = v
}
return s
}
func verifySetting(option string, value interface{}, def interface{}) error {
var interfaceArr []interface{}
valType := reflect.TypeOf(value)
defType := reflect.TypeOf(def)
assignable := false
switch option {
case "pluginrepos", "pluginchannels":
assignable = valType.AssignableTo(reflect.TypeOf(interfaceArr))
default:
assignable = defType.AssignableTo(valType)
}
if !assignable {
return fmt.Errorf("Error: setting '%s' has incorrect type (%s), using default value: %v (%s)", option, valType, def, defType)
}
if err := OptionIsValid(option, value); err != nil {
return err
}
return nil
}
// InitGlobalSettings initializes the options map and sets all options to their default values
// Must be called after ReadSettings
func InitGlobalSettings() error {
var err error
GlobalSettings = DefaultAllSettings()
for k, v := range parsedSettings {
if !strings.HasPrefix(reflect.TypeOf(v).String(), "map") {
GlobalSettings[k] = v
}
}
return err
}
// InitLocalSettings scans the json in settings.json and sets the options locally based
// on whether the filetype or path matches ft or glob local settings
// Must be called after ReadSettings
func InitLocalSettings(settings map[string]interface{}, path string) {
for k, v := range parsedSettings {
if strings.HasPrefix(reflect.TypeOf(v).String(), "map") {
if strings.HasPrefix(k, "ft:") {
if settings["filetype"].(string) == k[3:] {
for k1, v1 := range v.(map[string]interface{}) {
settings[k1] = v1
}
}
} else {
g, _ := glob.Compile(k)
if g.MatchString(path) {
for k1, v1 := range v.(map[string]interface{}) {
settings[k1] = v1
}
}
}
}
}
}
// WriteSettings writes the settings to the specified filename as JSON
func WriteSettings(filename string) error {
if settingsParseError {
// Don't write settings if there was a parse error
// because this will delete the settings.json if it
// is invalid. Instead we should allow the user to fix
// it manually.
return nil
}
var err error
if _, e := os.Stat(ConfigDir); e == nil {
defaults := DefaultAllSettings()
// remove any options froms parsedSettings that have since been marked as default
for k, v := range parsedSettings {
if !strings.HasPrefix(reflect.TypeOf(v).String(), "map") {
cur, okcur := GlobalSettings[k]
_, vol := VolatileSettings[k]
if def, ok := defaults[k]; ok && okcur && !vol && reflect.DeepEqual(cur, def) {
delete(parsedSettings, k)
}
}
}
// add any options to parsedSettings that have since been marked as non-default
for k, v := range GlobalSettings {
if def, ok := defaults[k]; !ok || !reflect.DeepEqual(v, def) {
if _, wr := ModifiedSettings[k]; wr {
parsedSettings[k] = v
}
}
}
txt, _ := json.MarshalIndent(parsedSettings, "", " ")
err = ioutil.WriteFile(filename, append(txt, '\n'), 0644)
}
return err
}
// OverwriteSettings writes the current settings to settings.json and
// resets any user configuration of local settings present in settings.json
func OverwriteSettings(filename string) error {
settings := make(map[string]interface{})
var err error
if _, e := os.Stat(ConfigDir); e == nil {
defaults := DefaultAllSettings()
for k, v := range GlobalSettings {
if def, ok := defaults[k]; !ok || !reflect.DeepEqual(v, def) {
if _, wr := ModifiedSettings[k]; wr {
settings[k] = v
}
}
}
txt, _ := json.MarshalIndent(settings, "", " ")
err = ioutil.WriteFile(filename, append(txt, '\n'), 0644)
}
return err
}
// RegisterCommonOptionPlug creates a new option (called pl.name). This is meant to be called by plugins to add options.
func RegisterCommonOptionPlug(pl string, name string, defaultvalue interface{}) error {
return RegisterCommonOption(pl+"."+name, defaultvalue)
}
// RegisterGlobalOptionPlug creates a new global-only option (named pl.name)
func RegisterGlobalOptionPlug(pl string, name string, defaultvalue interface{}) error {
return RegisterGlobalOption(pl+"."+name, defaultvalue)
}
// RegisterCommonOption creates a new option
func RegisterCommonOption(name string, defaultvalue interface{}) error {
if _, ok := GlobalSettings[name]; !ok {
GlobalSettings[name] = defaultvalue
}
defaultCommonSettings[name] = defaultvalue
return nil
}
// RegisterGlobalOption creates a new global-only option
func RegisterGlobalOption(name string, defaultvalue interface{}) error {
if _, ok := GlobalSettings[name]; !ok {
GlobalSettings[name] = defaultvalue
}
DefaultGlobalOnlySettings[name] = defaultvalue
return nil
}
// GetGlobalOption returns the global value of the given option
func GetGlobalOption(name string) interface{} {
return GlobalSettings[name]
}
func defaultFileFormat() string {
if runtime.GOOS == "windows" {
return "dos"
}
return "unix"
}
func GetInfoBarOffset() int {
offset := 0
if GetGlobalOption("infobar").(bool) {
offset++
}
if GetGlobalOption("keymenu").(bool) {
offset += 2
}
return offset
}
// DefaultCommonSettings returns a map of all common buffer settings
// and their default values
func DefaultCommonSettings() map[string]interface{} {
commonsettings := make(map[string]interface{})
for k, v := range defaultCommonSettings {
commonsettings[k] = v
}
return commonsettings
}
// DefaultAllSettings returns a map of all common buffer & global-only settings
// and their default values
func DefaultAllSettings() map[string]interface{} {
allsettings := make(map[string]interface{})
for k, v := range defaultCommonSettings {
allsettings[k] = v
}
for k, v := range DefaultGlobalOnlySettings {
allsettings[k] = v
}
return allsettings
}
// GetNativeValue parses and validates a value for a given option
func GetNativeValue(option string, realValue interface{}, value string) (interface{}, error) {
var native interface{}
kind := reflect.TypeOf(realValue).Kind()
if kind == reflect.Bool {
b, err := util.ParseBool(value)
if err != nil {
return nil, ErrInvalidValue
}
native = b
} else if kind == reflect.String {
native = value
} else if kind == reflect.Float64 {
f, err := strconv.ParseFloat(value, 64)
if err != nil {
return nil, ErrInvalidValue
}
native = f
} else {
return nil, ErrInvalidValue
}
return native, nil
}
// OptionIsValid checks if a value is valid for a certain option
func OptionIsValid(option string, value interface{}) error {
if validator, ok := optionValidators[option]; ok {
return validator(option, value)
}
return nil
}
// Option validators
func validatePositiveValue(option string, value interface{}) error {
nativeValue, ok := value.(float64)
if !ok {
return errors.New("Expected numeric type for " + option)
}
if nativeValue < 1 {
return errors.New(option + " must be greater than 0")
}
return nil
}
func validateNonNegativeValue(option string, value interface{}) error {
nativeValue, ok := value.(float64)
if !ok {
return errors.New("Expected numeric type for " + option)
}
if nativeValue < 0 {
return errors.New(option + " must be non-negative")
}
return nil
}
func validateChoice(option string, value interface{}) error {
if choices, ok := OptionChoices[option]; ok {
val, ok := value.(string)
if !ok {
return errors.New("Expected string type for " + option)
}
for _, v := range choices {
if val == v {
return nil
}
}
choicesStr := strings.Join(choices, ", ")
return errors.New(option + " must be one of: " + choicesStr)
}
return errors.New("Option has no pre-defined choices")
}
func validateColorscheme(option string, value interface{}) error {
colorscheme, ok := value.(string)
if !ok {
return errors.New("Expected string type for colorscheme")
}
if !ColorschemeExists(colorscheme) {
return errors.New(colorscheme + " is not a valid colorscheme")
}
return nil
}
func validateEncoding(option string, value interface{}) error {
_, err := htmlindex.Get(value.(string))
return err
}
```
|
/content/code_sandbox/internal/config/settings.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 3,829
|
```go
package config
import (
"errors"
"io/ioutil"
"log"
"os"
"path"
"path/filepath"
"regexp"
"strings"
rt "github.com/zyedidia/micro/v2/runtime"
)
const (
RTColorscheme = 0
RTSyntax = 1
RTHelp = 2
RTPlugin = 3
RTSyntaxHeader = 4
)
var (
NumTypes = 5 // How many filetypes are there
)
type RTFiletype int
// RuntimeFile allows the program to read runtime data like colorschemes or syntax files
type RuntimeFile interface {
// Name returns a name of the file without paths or extensions
Name() string
// Data returns the content of the file.
Data() ([]byte, error)
}
// allFiles contains all available files, mapped by filetype
var allFiles [][]RuntimeFile
var realFiles [][]RuntimeFile
func init() {
initRuntimeVars()
}
func initRuntimeVars() {
allFiles = make([][]RuntimeFile, NumTypes)
realFiles = make([][]RuntimeFile, NumTypes)
}
// NewRTFiletype creates a new RTFiletype
func NewRTFiletype() int {
NumTypes++
allFiles = append(allFiles, []RuntimeFile{})
realFiles = append(realFiles, []RuntimeFile{})
return NumTypes - 1
}
// some file on filesystem
type realFile string
// some asset file
type assetFile string
// some file on filesystem but with a different name
type namedFile struct {
realFile
name string
}
// a file with the data stored in memory
type memoryFile struct {
name string
data []byte
}
func (mf memoryFile) Name() string {
return mf.name
}
func (mf memoryFile) Data() ([]byte, error) {
return mf.data, nil
}
func (rf realFile) Name() string {
fn := filepath.Base(string(rf))
return fn[:len(fn)-len(filepath.Ext(fn))]
}
func (rf realFile) Data() ([]byte, error) {
return ioutil.ReadFile(string(rf))
}
func (af assetFile) Name() string {
fn := path.Base(string(af))
return fn[:len(fn)-len(path.Ext(fn))]
}
func (af assetFile) Data() ([]byte, error) {
return rt.Asset(string(af))
}
func (nf namedFile) Name() string {
return nf.name
}
// AddRuntimeFile registers a file for the given filetype
func AddRuntimeFile(fileType RTFiletype, file RuntimeFile) {
allFiles[fileType] = append(allFiles[fileType], file)
}
// AddRealRuntimeFile registers a file for the given filetype
func AddRealRuntimeFile(fileType RTFiletype, file RuntimeFile) {
allFiles[fileType] = append(allFiles[fileType], file)
realFiles[fileType] = append(realFiles[fileType], file)
}
// AddRuntimeFilesFromDirectory registers each file from the given directory for
// the filetype which matches the file-pattern
func AddRuntimeFilesFromDirectory(fileType RTFiletype, directory, pattern string) {
files, _ := ioutil.ReadDir(directory)
for _, f := range files {
if ok, _ := filepath.Match(pattern, f.Name()); !f.IsDir() && ok {
fullPath := filepath.Join(directory, f.Name())
AddRealRuntimeFile(fileType, realFile(fullPath))
}
}
}
// AddRuntimeFilesFromAssets registers each file from the given asset-directory for
// the filetype which matches the file-pattern
func AddRuntimeFilesFromAssets(fileType RTFiletype, directory, pattern string) {
files, err := rt.AssetDir(directory)
if err != nil {
return
}
assetLoop:
for _, f := range files {
if ok, _ := path.Match(pattern, f); ok {
af := assetFile(path.Join(directory, f))
for _, rf := range realFiles[fileType] {
if af.Name() == rf.Name() {
continue assetLoop
}
}
AddRuntimeFile(fileType, af)
}
}
}
// FindRuntimeFile finds a runtime file of the given filetype and name
// will return nil if no file was found
func FindRuntimeFile(fileType RTFiletype, name string) RuntimeFile {
for _, f := range ListRuntimeFiles(fileType) {
if f.Name() == name {
return f
}
}
return nil
}
// ListRuntimeFiles lists all known runtime files for the given filetype
func ListRuntimeFiles(fileType RTFiletype) []RuntimeFile {
return allFiles[fileType]
}
// ListRealRuntimeFiles lists all real runtime files (on disk) for a filetype
// these runtime files will be ones defined by the user and loaded from the config directory
func ListRealRuntimeFiles(fileType RTFiletype) []RuntimeFile {
return realFiles[fileType]
}
// InitRuntimeFiles initializes all assets files and the config directory.
// If `user` is false, InitRuntimeFiles ignores the config directory and
// initializes asset files only.
func InitRuntimeFiles(user bool) {
add := func(fileType RTFiletype, dir, pattern string) {
if user {
AddRuntimeFilesFromDirectory(fileType, filepath.Join(ConfigDir, dir), pattern)
}
AddRuntimeFilesFromAssets(fileType, path.Join("runtime", dir), pattern)
}
initRuntimeVars()
add(RTColorscheme, "colorschemes", "*.micro")
add(RTSyntax, "syntax", "*.yaml")
add(RTSyntaxHeader, "syntax", "*.hdr")
add(RTHelp, "help", "*.md")
}
// InitPlugins initializes the plugins
func InitPlugins() {
Plugins = Plugins[:0]
initlua := filepath.Join(ConfigDir, "init.lua")
if _, err := os.Stat(initlua); !os.IsNotExist(err) {
p := new(Plugin)
p.Name = "initlua"
p.DirName = "initlua"
p.Srcs = append(p.Srcs, realFile(initlua))
Plugins = append(Plugins, p)
}
// Search ConfigDir for plugin-scripts
plugdir := filepath.Join(ConfigDir, "plug")
files, _ := ioutil.ReadDir(plugdir)
isID := regexp.MustCompile(`^[_A-Za-z0-9]+$`).MatchString
for _, d := range files {
plugpath := filepath.Join(plugdir, d.Name())
if stat, err := os.Stat(plugpath); err == nil && stat.IsDir() {
srcs, _ := ioutil.ReadDir(plugpath)
p := new(Plugin)
p.Name = d.Name()
p.DirName = d.Name()
for _, f := range srcs {
if strings.HasSuffix(f.Name(), ".lua") {
p.Srcs = append(p.Srcs, realFile(filepath.Join(plugdir, d.Name(), f.Name())))
} else if strings.HasSuffix(f.Name(), ".json") {
data, err := ioutil.ReadFile(filepath.Join(plugdir, d.Name(), f.Name()))
if err != nil {
continue
}
p.Info, err = NewPluginInfo(data)
if err != nil {
continue
}
p.Name = p.Info.Name
}
}
if !isID(p.Name) || len(p.Srcs) <= 0 {
log.Println(p.Name, "is not a plugin")
continue
}
Plugins = append(Plugins, p)
}
}
plugdir = filepath.Join("runtime", "plugins")
if files, err := rt.AssetDir(plugdir); err == nil {
outer:
for _, d := range files {
for _, p := range Plugins {
if p.Name == d {
log.Println(p.Name, "built-in plugin overridden by user-defined one")
continue outer
}
}
if srcs, err := rt.AssetDir(filepath.Join(plugdir, d)); err == nil {
p := new(Plugin)
p.Name = d
p.DirName = d
p.Default = true
for _, f := range srcs {
if strings.HasSuffix(f, ".lua") {
p.Srcs = append(p.Srcs, assetFile(filepath.Join(plugdir, d, f)))
} else if strings.HasSuffix(f, ".json") {
data, err := rt.Asset(filepath.Join(plugdir, d, f))
if err != nil {
continue
}
p.Info, err = NewPluginInfo(data)
if err != nil {
continue
}
p.Name = p.Info.Name
}
}
if !isID(p.Name) || len(p.Srcs) <= 0 {
log.Println(p.Name, "is not a plugin")
continue
}
Plugins = append(Plugins, p)
}
}
}
}
// PluginReadRuntimeFile allows plugin scripts to read the content of a runtime file
func PluginReadRuntimeFile(fileType RTFiletype, name string) string {
if file := FindRuntimeFile(fileType, name); file != nil {
if data, err := file.Data(); err == nil {
return string(data)
}
}
return ""
}
// PluginListRuntimeFiles allows plugins to lists all runtime files of the given type
func PluginListRuntimeFiles(fileType RTFiletype) []string {
files := ListRuntimeFiles(fileType)
result := make([]string, len(files))
for i, f := range files {
result[i] = f.Name()
}
return result
}
// PluginAddRuntimeFile adds a file to the runtime files for a plugin
func PluginAddRuntimeFile(plugin string, filetype RTFiletype, filePath string) error {
pl := FindPlugin(plugin)
if pl == nil {
return errors.New("Plugin " + plugin + " does not exist")
}
pldir := pl.DirName
fullpath := filepath.Join(ConfigDir, "plug", pldir, filePath)
if _, err := os.Stat(fullpath); err == nil {
AddRealRuntimeFile(filetype, realFile(fullpath))
} else {
fullpath = path.Join("runtime", "plugins", pldir, filePath)
AddRuntimeFile(filetype, assetFile(fullpath))
}
return nil
}
// PluginAddRuntimeFilesFromDirectory adds files from a directory to the runtime files for a plugin
func PluginAddRuntimeFilesFromDirectory(plugin string, filetype RTFiletype, directory, pattern string) error {
pl := FindPlugin(plugin)
if pl == nil {
return errors.New("Plugin " + plugin + " does not exist")
}
pldir := pl.DirName
fullpath := filepath.Join(ConfigDir, "plug", pldir, directory)
if _, err := os.Stat(fullpath); err == nil {
AddRuntimeFilesFromDirectory(filetype, fullpath, pattern)
} else {
fullpath = path.Join("runtime", "plugins", pldir, directory)
AddRuntimeFilesFromAssets(filetype, fullpath, pattern)
}
return nil
}
// PluginAddRuntimeFileFromMemory adds a file to the runtime files for a plugin from a given string
func PluginAddRuntimeFileFromMemory(filetype RTFiletype, filename, data string) {
AddRealRuntimeFile(filetype, memoryFile{filename, []byte(data)})
}
```
|
/content/code_sandbox/internal/config/rtfiles.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 2,424
|
```go
package config
import (
"testing"
"github.com/blang/semver"
"github.com/zyedidia/json5"
)
func TestDependencyResolving(t *testing.T) {
js := `
[{
"Name": "Foo",
"Versions": [{ "Version": "1.0.0" }, { "Version": "1.5.0" },{ "Version": "2.0.0" }]
}, {
"Name": "Bar",
"Versions": [{ "Version": "1.0.0", "Require": {"Foo": ">1.0.0 <2.0.0"} }]
}, {
"Name": "Unresolvable",
"Versions": [{ "Version": "1.0.0", "Require": {"Foo": "<=1.0.0", "Bar": ">0.0.0"} }]
}]
`
var all PluginPackages
err := json5.Unmarshal([]byte(js), &all)
if err != nil {
t.Error(err)
}
selected, err := all.Resolve(PluginVersions{}, PluginDependencies{
&PluginDependency{"Bar", semver.MustParseRange(">=1.0.0")},
})
check := func(name, version string) {
v := selected.find(name)
expected := semver.MustParse(version)
if v == nil {
t.Errorf("Failed to resolve %s", name)
} else if expected.NE(v.Version) {
t.Errorf("%s resolved in wrong version %v", name, v)
}
}
if err != nil {
t.Error(err)
} else {
check("Foo", "1.5.0")
check("Bar", "1.0.0")
}
selected, err = all.Resolve(PluginVersions{}, PluginDependencies{
&PluginDependency{"Unresolvable", semver.MustParseRange(">0.0.0")},
})
if err == nil {
t.Error("Unresolvable package resolved:", selected)
}
}
```
|
/content/code_sandbox/internal/config/plugin_installer_test.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 427
|
```go
package config
import (
"bytes"
"encoding/json"
"errors"
)
var (
ErrMissingName = errors.New("Missing or empty name field")
ErrMissingDesc = errors.New("Missing or empty description field")
ErrMissingSite = errors.New("Missing or empty website field")
)
// PluginInfo contains all the needed info about a plugin
// The info is just strings and are not used beyond that (except
// the Site and Install fields should be valid URLs). This means
// that the requirements for example can be formatted however the
// plugin maker decides, the fields will only be parsed by humans
// Name: name of plugin
// Desc: description of plugin
// Site: home website of plugin
// Install: install link for plugin (can be link to repo or zip file)
// Vstr: version
// Require: list of dependencies and requirements
type PluginInfo struct {
Name string `json:"Name"`
Desc string `json:"Description"`
Site string `json:"Website"`
}
// NewPluginInfo parses a JSON input into a valid PluginInfo struct
// Returns an error if there are any missing fields or any invalid fields
// There are no optional fields in a plugin info json file
func NewPluginInfo(data []byte) (*PluginInfo, error) {
var info []PluginInfo
dec := json.NewDecoder(bytes.NewReader(data))
// dec.DisallowUnknownFields() // Force errors
if err := dec.Decode(&info); err != nil {
return nil, err
}
return &info[0], nil
}
```
|
/content/code_sandbox/internal/config/plugin_manager.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 327
|
```go
package config
import (
"errors"
"regexp"
"strconv"
"strings"
"github.com/zyedidia/tcell/v2"
)
// DefStyle is Micro's default style
var DefStyle tcell.Style = tcell.StyleDefault
// Colorscheme is the current colorscheme
var Colorscheme map[string]tcell.Style
// GetColor takes in a syntax group and returns the colorscheme's style for that group
func GetColor(color string) tcell.Style {
st := DefStyle
if color == "" {
return st
}
groups := strings.Split(color, ".")
if len(groups) > 1 {
curGroup := ""
for i, g := range groups {
if i != 0 {
curGroup += "."
}
curGroup += g
if style, ok := Colorscheme[curGroup]; ok {
st = style
}
}
} else if style, ok := Colorscheme[color]; ok {
st = style
} else {
st = StringToStyle(color)
}
return st
}
// ColorschemeExists checks if a given colorscheme exists
func ColorschemeExists(colorschemeName string) bool {
return FindRuntimeFile(RTColorscheme, colorschemeName) != nil
}
// InitColorscheme picks and initializes the colorscheme when micro starts
func InitColorscheme() error {
Colorscheme = make(map[string]tcell.Style)
DefStyle = tcell.StyleDefault
c, err := LoadDefaultColorscheme()
if err == nil {
Colorscheme = c
}
return err
}
// LoadDefaultColorscheme loads the default colorscheme from $(ConfigDir)/colorschemes
func LoadDefaultColorscheme() (map[string]tcell.Style, error) {
var parsedColorschemes []string
return LoadColorscheme(GlobalSettings["colorscheme"].(string), &parsedColorschemes)
}
// LoadColorscheme loads the given colorscheme from a directory
func LoadColorscheme(colorschemeName string, parsedColorschemes *[]string) (map[string]tcell.Style, error) {
c := make(map[string]tcell.Style)
file := FindRuntimeFile(RTColorscheme, colorschemeName)
if file == nil {
return c, errors.New(colorschemeName + " is not a valid colorscheme")
}
if data, err := file.Data(); err != nil {
return c, errors.New("Error loading colorscheme: " + err.Error())
} else {
var err error
c, err = ParseColorscheme(file.Name(), string(data), parsedColorschemes)
if err != nil {
return c, err
}
}
return c, nil
}
// 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(name string, text string, parsedColorschemes *[]string) (map[string]tcell.Style, error) {
var err error
colorParser := regexp.MustCompile(`color-link\s+(\S*)\s+"(.*)"`)
includeParser := regexp.MustCompile(`include\s+"(.*)"`)
lines := strings.Split(text, "\n")
c := make(map[string]tcell.Style)
if parsedColorschemes != nil {
*parsedColorschemes = append(*parsedColorschemes, name)
}
lineLoop:
for _, line := range lines {
if strings.TrimSpace(line) == "" ||
strings.TrimSpace(line)[0] == '#' {
// Ignore this line
continue
}
matches := includeParser.FindSubmatch([]byte(line))
if len(matches) == 2 {
// support includes only in case parsedColorschemes are given
if parsedColorschemes != nil {
include := string(matches[1])
for _, name := range *parsedColorschemes {
// check for circular includes...
if name == include {
// ...and prevent them
continue lineLoop
}
}
includeScheme, err := LoadColorscheme(include, parsedColorschemes)
if err != nil {
return c, err
}
for k, v := range includeScheme {
c[k] = v
}
}
continue
}
matches = colorParser.FindSubmatch([]byte(line))
if len(matches) == 3 {
link := string(matches[1])
colors := string(matches[2])
style := StringToStyle(colors)
c[link] = style
if link == "default" {
DefStyle = style
}
} else {
err = errors.New("Color-link statement is not valid: " + line)
}
}
return c, err
}
// StringToStyle returns a style from a string
// The strings must be in the format "extra foregroundcolor,backgroundcolor"
// The 'extra' can be bold, reverse, italic or underline
func StringToStyle(str string) tcell.Style {
var fg, bg string
spaceSplit := strings.Split(str, " ")
split := strings.Split(spaceSplit[len(spaceSplit)-1], ",")
if len(split) > 1 {
fg, bg = split[0], split[1]
} else {
fg = split[0]
}
fg = strings.TrimSpace(fg)
bg = strings.TrimSpace(bg)
var fgColor, bgColor tcell.Color
var ok bool
if fg == "" || fg == "default" {
fgColor, _, _ = DefStyle.Decompose()
} else {
fgColor, ok = StringToColor(fg)
if !ok {
fgColor, _, _ = DefStyle.Decompose()
}
}
if bg == "" || bg == "default" {
_, bgColor, _ = DefStyle.Decompose()
} else {
bgColor, ok = StringToColor(bg)
if !ok {
_, bgColor, _ = DefStyle.Decompose()
}
}
style := DefStyle.Foreground(fgColor).Background(bgColor)
if strings.Contains(str, "bold") {
style = style.Bold(true)
}
if strings.Contains(str, "italic") {
style = style.Italic(true)
}
if strings.Contains(str, "reverse") {
style = style.Reverse(true)
}
if strings.Contains(str, "underline") {
style = style.Underline(true)
}
return style
}
// 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, bool) {
switch str {
case "black":
return tcell.ColorBlack, true
case "red":
return tcell.ColorMaroon, true
case "green":
return tcell.ColorGreen, true
case "yellow":
return tcell.ColorOlive, true
case "blue":
return tcell.ColorNavy, true
case "magenta":
return tcell.ColorPurple, true
case "cyan":
return tcell.ColorTeal, true
case "white":
return tcell.ColorSilver, true
case "brightblack", "lightblack":
return tcell.ColorGray, true
case "brightred", "lightred":
return tcell.ColorRed, true
case "brightgreen", "lightgreen":
return tcell.ColorLime, true
case "brightyellow", "lightyellow":
return tcell.ColorYellow, true
case "brightblue", "lightblue":
return tcell.ColorBlue, true
case "brightmagenta", "lightmagenta":
return tcell.ColorFuchsia, true
case "brightcyan", "lightcyan":
return tcell.ColorAqua, true
case "brightwhite", "lightwhite":
return tcell.ColorWhite, true
case "default":
return tcell.ColorDefault, true
default:
// Check if this is a 256 color
if num, err := strconv.Atoi(str); err == nil {
return GetColor256(num), true
}
// Check if this is a truecolor hex value
if len(str) == 7 && str[0] == '#' {
return tcell.GetColor(str), true
}
return tcell.ColorDefault, false
}
}
// GetColor256 returns the tcell color for a number between 0 and 255
func GetColor256(color int) tcell.Color {
if color == 0 {
return tcell.ColorDefault
}
return tcell.PaletteColor(color)
}
```
|
/content/code_sandbox/internal/config/colorscheme.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 1,879
|
```go
package config
import (
"errors"
"log"
lua "github.com/yuin/gopher-lua"
ulua "github.com/zyedidia/micro/v2/internal/lua"
)
// ErrNoSuchFunction is returned when Call is executed on a function that does not exist
var ErrNoSuchFunction = errors.New("No such function exists")
// LoadAllPlugins loads all detected plugins (in runtime/plugins and ConfigDir/plugins)
func LoadAllPlugins() error {
var reterr error
for _, p := range Plugins {
err := p.Load()
if err != nil {
reterr = err
}
}
return reterr
}
// RunPluginFn runs a given function in all plugins
// returns an error if any of the plugins had an error
func RunPluginFn(fn string, args ...lua.LValue) error {
var reterr error
for _, p := range Plugins {
if !p.IsLoaded() {
continue
}
_, err := p.Call(fn, args...)
if err != nil && err != ErrNoSuchFunction {
reterr = errors.New("Plugin " + p.Name + ": " + err.Error())
}
}
return reterr
}
// RunPluginFnBool runs a function in all plugins and returns
// false if any one of them returned false
// also returns an error if any of the plugins had an error
func RunPluginFnBool(settings map[string]interface{}, fn string, args ...lua.LValue) (bool, error) {
var reterr error
retbool := true
for _, p := range Plugins {
if !p.IsLoaded() || (settings != nil && settings[p.Name] == false) {
continue
}
val, err := p.Call(fn, args...)
if err == ErrNoSuchFunction {
continue
}
if err != nil {
reterr = errors.New("Plugin " + p.Name + ": " + err.Error())
continue
}
if v, ok := val.(lua.LBool); ok {
retbool = retbool && bool(v)
}
}
return retbool, reterr
}
// Plugin stores information about the source files/info for a plugin
type Plugin struct {
DirName string // name of plugin folder
Name string // name of plugin
Info *PluginInfo // json file containing info
Srcs []RuntimeFile // lua files
Loaded bool
Default bool // pre-installed plugin
}
// IsLoaded returns if a plugin is enabled
func (p *Plugin) IsLoaded() bool {
if v, ok := GlobalSettings[p.Name]; ok {
return v.(bool) && p.Loaded
}
return true
}
// Plugins is a list of all detected plugins (enabled or disabled)
var Plugins []*Plugin
// Load creates an option for the plugin and runs all source files
func (p *Plugin) Load() error {
if v, ok := GlobalSettings[p.Name]; ok && !v.(bool) {
return nil
}
for _, f := range p.Srcs {
dat, err := f.Data()
if err != nil {
return err
}
err = ulua.LoadFile(p.Name, f.Name(), dat)
if err != nil {
return err
}
}
p.Loaded = true
RegisterCommonOption(p.Name, true)
return nil
}
// Call calls a given function in this plugin
func (p *Plugin) Call(fn string, args ...lua.LValue) (lua.LValue, error) {
plug := ulua.L.GetGlobal(p.Name)
if plug == lua.LNil {
log.Println("Plugin does not exist:", p.Name, "at", p.DirName, ":", p)
return nil, nil
}
luafn := ulua.L.GetField(plug, fn)
if luafn == lua.LNil {
return nil, ErrNoSuchFunction
}
err := ulua.L.CallByParam(lua.P{
Fn: luafn,
NRet: 1,
Protect: true,
}, args...)
if err != nil {
return nil, err
}
ret := ulua.L.Get(-1)
ulua.L.Pop(1)
return ret, nil
}
// FindPlugin returns the plugin with the given name
func FindPlugin(name string) *Plugin {
var pl *Plugin
for _, p := range Plugins {
if !p.IsLoaded() {
continue
}
if p.Name == name {
pl = p
break
}
}
return pl
}
// FindAnyPlugin does not require the plugin to be enabled
func FindAnyPlugin(name string) *Plugin {
var pl *Plugin
for _, p := range Plugins {
if p.Name == name {
pl = p
break
}
}
return pl
}
```
|
/content/code_sandbox/internal/config/plugin.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 1,048
|
```go
package config
import (
"archive/zip"
"bytes"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"github.com/blang/semver"
lua "github.com/yuin/gopher-lua"
"github.com/zyedidia/json5"
ulua "github.com/zyedidia/micro/v2/internal/lua"
"github.com/zyedidia/micro/v2/internal/util"
)
var (
allPluginPackages PluginPackages
)
// CorePluginName is a plugin dependency name for the micro core.
const CorePluginName = "micro"
// PluginChannel contains an url to a json list of PluginRepository
type PluginChannel string
// PluginChannels is a slice of PluginChannel
type PluginChannels []PluginChannel
// PluginRepository contains an url to json file containing PluginPackages
type PluginRepository string
// PluginPackage contains the meta-data of a plugin and all available versions
type PluginPackage struct {
Name string
Description string
Author string
Tags []string
Versions PluginVersions
}
// PluginPackages is a list of PluginPackage instances.
type PluginPackages []*PluginPackage
// PluginVersion descripes a version of a PluginPackage. Containing a version, download url and also dependencies.
type PluginVersion struct {
pack *PluginPackage
Version semver.Version
Url string
Require PluginDependencies
}
func (pv *PluginVersion) Pack() *PluginPackage {
return pv.pack
}
// PluginVersions is a slice of PluginVersion
type PluginVersions []*PluginVersion
// PluginDependency descripes a dependency to another plugin or micro itself.
type PluginDependency struct {
Name string
Range semver.Range
}
// PluginDependencies is a slice of PluginDependency
type PluginDependencies []*PluginDependency
func (pp *PluginPackage) String() string {
buf := new(bytes.Buffer)
buf.WriteString("Plugin: ")
buf.WriteString(pp.Name)
buf.WriteRune('\n')
if pp.Author != "" {
buf.WriteString("Author: ")
buf.WriteString(pp.Author)
buf.WriteRune('\n')
}
if pp.Description != "" {
buf.WriteRune('\n')
buf.WriteString(pp.Description)
}
return buf.String()
}
func fetchAllSources(count int, fetcher func(i int) PluginPackages) PluginPackages {
wgQuery := new(sync.WaitGroup)
wgQuery.Add(count)
results := make(chan PluginPackages)
wgDone := new(sync.WaitGroup)
wgDone.Add(1)
var packages PluginPackages
for i := 0; i < count; i++ {
go func(i int) {
results <- fetcher(i)
wgQuery.Done()
}(i)
}
go func() {
packages = make(PluginPackages, 0)
for res := range results {
packages = append(packages, res...)
}
wgDone.Done()
}()
wgQuery.Wait()
close(results)
wgDone.Wait()
return packages
}
// Fetch retrieves all available PluginPackages from the given channels
func (pc PluginChannels) Fetch(out io.Writer) PluginPackages {
return fetchAllSources(len(pc), func(i int) PluginPackages {
return pc[i].Fetch(out)
})
}
// Fetch retrieves all available PluginPackages from the given channel
func (pc PluginChannel) Fetch(out io.Writer) PluginPackages {
resp, err := http.Get(string(pc))
if err != nil {
fmt.Fprintln(out, "Failed to query plugin channel:\n", err)
return PluginPackages{}
}
defer resp.Body.Close()
decoder := json5.NewDecoder(resp.Body)
var repositories []PluginRepository
if err := decoder.Decode(&repositories); err != nil {
fmt.Fprintln(out, "Failed to decode channel data:\n", err)
return PluginPackages{}
}
return fetchAllSources(len(repositories), func(i int) PluginPackages {
return repositories[i].Fetch(out)
})
}
// Fetch retrieves all available PluginPackages from the given repository
func (pr PluginRepository) Fetch(out io.Writer) PluginPackages {
resp, err := http.Get(string(pr))
if err != nil {
fmt.Fprintln(out, "Failed to query plugin repository:\n", err)
return PluginPackages{}
}
defer resp.Body.Close()
decoder := json5.NewDecoder(resp.Body)
var plugins PluginPackages
if err := decoder.Decode(&plugins); err != nil {
fmt.Fprintln(out, "Failed to decode repository data:\n", err)
return PluginPackages{}
}
if len(plugins) > 0 {
return PluginPackages{plugins[0]}
}
return nil
// return plugins
}
// UnmarshalJSON unmarshals raw json to a PluginVersion
func (pv *PluginVersion) UnmarshalJSON(data []byte) error {
var values struct {
Version semver.Version
Url string
Require map[string]string
}
if err := json5.Unmarshal(data, &values); err != nil {
return err
}
pv.Version = values.Version
pv.Url = values.Url
pv.Require = make(PluginDependencies, 0)
for k, v := range values.Require {
// don't add the dependency if it's the core and
// we have a unknown version number.
// in that case just accept that dependency (which equals to not adding it.)
if k != CorePluginName || !isUnknownCoreVersion() {
if vRange, err := semver.ParseRange(v); err == nil {
pv.Require = append(pv.Require, &PluginDependency{k, vRange})
}
}
}
return nil
}
// UnmarshalJSON unmarshals raw json to a PluginPackage
func (pp *PluginPackage) UnmarshalJSON(data []byte) error {
var values struct {
Name string
Description string
Author string
Tags []string
Versions PluginVersions
}
if err := json5.Unmarshal(data, &values); err != nil {
return err
}
pp.Name = values.Name
pp.Description = values.Description
pp.Author = values.Author
pp.Tags = values.Tags
pp.Versions = values.Versions
for _, v := range pp.Versions {
v.pack = pp
}
return nil
}
// GetAllPluginPackages gets all PluginPackages which may be available.
func GetAllPluginPackages(out io.Writer) PluginPackages {
if allPluginPackages == nil {
getOption := func(name string) []string {
data := GetGlobalOption(name)
if strs, ok := data.([]string); ok {
return strs
}
if ifs, ok := data.([]interface{}); ok {
result := make([]string, len(ifs))
for i, urlIf := range ifs {
if url, ok := urlIf.(string); ok {
result[i] = url
} else {
return nil
}
}
return result
}
return nil
}
channels := PluginChannels{}
for _, url := range getOption("pluginchannels") {
channels = append(channels, PluginChannel(url))
}
repos := []PluginRepository{}
for _, url := range getOption("pluginrepos") {
repos = append(repos, PluginRepository(url))
}
allPluginPackages = fetchAllSources(len(repos)+1, func(i int) PluginPackages {
if i == 0 {
return channels.Fetch(out)
}
return repos[i-1].Fetch(out)
})
}
return allPluginPackages
}
func (pv PluginVersions) find(ppName string) *PluginVersion {
for _, v := range pv {
if v.pack.Name == ppName {
return v
}
}
return nil
}
// Len returns the number of pluginversions in this slice
func (pv PluginVersions) Len() int {
return len(pv)
}
// Swap two entries of the slice
func (pv PluginVersions) Swap(i, j int) {
pv[i], pv[j] = pv[j], pv[i]
}
// Less returns true if the version at position i is greater then the version at position j (used for sorting)
func (pv PluginVersions) Less(i, j int) bool {
return pv[i].Version.GT(pv[j].Version)
}
// Match returns true if the package matches a given search text
func (pp PluginPackage) Match(text string) bool {
text = strings.ToLower(text)
for _, t := range pp.Tags {
if strings.ToLower(t) == text {
return true
}
}
if strings.Contains(strings.ToLower(pp.Name), text) {
return true
}
if strings.Contains(strings.ToLower(pp.Description), text) {
return true
}
return false
}
// IsInstallable returns true if the package can be installed.
func (pp PluginPackage) IsInstallable(out io.Writer) error {
_, err := GetAllPluginPackages(out).Resolve(GetInstalledVersions(true), PluginDependencies{
&PluginDependency{
Name: pp.Name,
Range: semver.Range(func(v semver.Version) bool { return true }),
}})
return err
}
// SearchPlugin retrieves a list of all PluginPackages which match the given search text and
// could be or are already installed
func SearchPlugin(out io.Writer, texts []string) (plugins PluginPackages) {
plugins = make(PluginPackages, 0)
pluginLoop:
for _, pp := range GetAllPluginPackages(out) {
for _, text := range texts {
if !pp.Match(text) {
continue pluginLoop
}
}
if err := pp.IsInstallable(out); err == nil {
plugins = append(plugins, pp)
}
}
return
}
func isUnknownCoreVersion() bool {
_, err := semver.ParseTolerant(util.Version)
return err != nil
}
func newStaticPluginVersion(name, version string) *PluginVersion {
vers, err := semver.ParseTolerant(version)
if err != nil {
if vers, err = semver.ParseTolerant("0.0.0-" + version); err != nil {
vers = semver.MustParse("0.0.0-unknown")
}
}
pl := &PluginPackage{
Name: name,
}
pv := &PluginVersion{
pack: pl,
Version: vers,
}
pl.Versions = PluginVersions{pv}
return pv
}
// GetInstalledVersions returns a list of all currently installed plugins including an entry for
// micro itself. This can be used to resolve dependencies.
func GetInstalledVersions(withCore bool) PluginVersions {
result := PluginVersions{}
if withCore {
result = append(result, newStaticPluginVersion(CorePluginName, util.Version))
}
for _, p := range Plugins {
if !p.IsLoaded() {
continue
}
version := GetInstalledPluginVersion(p.Name)
if pv := newStaticPluginVersion(p.Name, version); pv != nil {
result = append(result, pv)
}
}
return result
}
// GetInstalledPluginVersion returns the string of the exported VERSION variable of a loaded plugin
func GetInstalledPluginVersion(name string) string {
plugin := ulua.L.GetGlobal(name)
if plugin != lua.LNil {
version := ulua.L.GetField(plugin, "VERSION")
if str, ok := version.(lua.LString); ok {
return string(str)
}
}
return ""
}
// DownloadAndInstall downloads and installs the given plugin and version
func (pv *PluginVersion) DownloadAndInstall(out io.Writer) error {
fmt.Fprintf(out, "Downloading %q (%s) from %q\n", pv.pack.Name, pv.Version, pv.Url)
resp, err := http.Get(pv.Url)
if err != nil {
return err
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
zipbuf := bytes.NewReader(data)
z, err := zip.NewReader(zipbuf, zipbuf.Size())
if err != nil {
return err
}
targetDir := filepath.Join(ConfigDir, "plug", pv.pack.Name)
dirPerm := os.FileMode(0755)
if err = os.MkdirAll(targetDir, dirPerm); err != nil {
return err
}
// Check if all files in zip are in the same directory.
// this might be the case if the plugin zip contains the whole plugin dir
// instead of its content.
var prefix string
allPrefixed := false
for i, f := range z.File {
parts := strings.Split(f.Name, "/")
if i == 0 {
prefix = parts[0]
} else if parts[0] != prefix {
allPrefixed = false
break
} else {
// switch to true since we have at least a second file
allPrefixed = true
}
}
// Install files and directory's
for _, f := range z.File {
parts := strings.Split(f.Name, "/")
if allPrefixed {
parts = parts[1:]
}
targetName := filepath.Join(targetDir, filepath.Join(parts...))
if f.FileInfo().IsDir() {
if err := os.MkdirAll(targetName, dirPerm); err != nil {
return err
}
} else {
basepath := filepath.Dir(targetName)
if err := os.MkdirAll(basepath, dirPerm); err != nil {
return err
}
content, err := f.Open()
if err != nil {
return err
}
defer content.Close()
target, err := os.Create(targetName)
if err != nil {
return err
}
defer target.Close()
if _, err = io.Copy(target, content); err != nil {
return err
}
}
}
return nil
}
func (pl PluginPackages) Get(name string) *PluginPackage {
for _, p := range pl {
if p.Name == name {
return p
}
}
return nil
}
func (pl PluginPackages) GetAllVersions(name string) PluginVersions {
result := make(PluginVersions, 0)
p := pl.Get(name)
if p != nil {
result = append(result, p.Versions...)
}
return result
}
func (req PluginDependencies) Join(other PluginDependencies) PluginDependencies {
m := make(map[string]*PluginDependency)
for _, r := range req {
m[r.Name] = r
}
for _, o := range other {
cur, ok := m[o.Name]
if ok {
m[o.Name] = &PluginDependency{
o.Name,
o.Range.AND(cur.Range),
}
} else {
m[o.Name] = o
}
}
result := make(PluginDependencies, 0, len(m))
for _, v := range m {
result = append(result, v)
}
return result
}
// Resolve resolves dependencies between different plugins
func (all PluginPackages) Resolve(selectedVersions PluginVersions, open PluginDependencies) (PluginVersions, error) {
if len(open) == 0 {
return selectedVersions, nil
}
currentRequirement, stillOpen := open[0], open[1:]
if currentRequirement != nil {
if selVersion := selectedVersions.find(currentRequirement.Name); selVersion != nil {
if currentRequirement.Range(selVersion.Version) {
return all.Resolve(selectedVersions, stillOpen)
}
return nil, fmt.Errorf("unable to find a matching version for \"%s\"", currentRequirement.Name)
}
availableVersions := all.GetAllVersions(currentRequirement.Name)
sort.Sort(availableVersions)
for _, version := range availableVersions {
if currentRequirement.Range(version.Version) {
resolved, err := all.Resolve(append(selectedVersions, version), stillOpen.Join(version.Require))
if err == nil {
return resolved, nil
}
}
}
return nil, fmt.Errorf("unable to find a matching version for \"%s\"", currentRequirement.Name)
}
return selectedVersions, nil
}
func (pv PluginVersions) install(out io.Writer) {
anyInstalled := false
currentlyInstalled := GetInstalledVersions(true)
for _, sel := range pv {
if sel.pack.Name != CorePluginName {
shouldInstall := true
if pv := currentlyInstalled.find(sel.pack.Name); pv != nil {
if pv.Version.NE(sel.Version) {
fmt.Fprintln(out, "Uninstalling", sel.pack.Name)
UninstallPlugin(out, sel.pack.Name)
} else {
shouldInstall = false
}
}
if shouldInstall {
if err := sel.DownloadAndInstall(out); err != nil {
fmt.Fprintln(out, err)
return
}
anyInstalled = true
}
}
}
if anyInstalled {
fmt.Fprintln(out, "One or more plugins installed.")
} else {
fmt.Fprintln(out, "Nothing to install / update")
}
}
// UninstallPlugin deletes the plugin folder of the given plugin
func UninstallPlugin(out io.Writer, name string) {
for _, p := range Plugins {
if !p.IsLoaded() {
continue
}
if p.Name == name {
p.Loaded = false
if err := os.RemoveAll(filepath.Join(ConfigDir, "plug", p.DirName)); err != nil {
fmt.Fprintln(out, err)
return
}
break
}
}
}
// Install installs the plugin
func (pl PluginPackage) Install(out io.Writer) {
selected, err := GetAllPluginPackages(out).Resolve(GetInstalledVersions(true), PluginDependencies{
&PluginDependency{
Name: pl.Name,
Range: semver.Range(func(v semver.Version) bool { return true }),
}})
if err != nil {
fmt.Fprintln(out, err)
return
}
selected.install(out)
}
// UpdatePlugins updates the given plugins
func UpdatePlugins(out io.Writer, plugins []string) {
// if no plugins are specified, update all installed plugins.
if len(plugins) == 0 {
for _, p := range Plugins {
if !p.IsLoaded() || p.Default {
continue
}
plugins = append(plugins, p.Name)
}
}
fmt.Fprintln(out, "Checking for plugin updates")
microVersion := PluginVersions{
newStaticPluginVersion(CorePluginName, util.Version),
}
var updates = make(PluginDependencies, 0)
for _, name := range plugins {
pv := GetInstalledPluginVersion(name)
r, err := semver.ParseRange(">=" + pv) // Try to get newer versions.
if err == nil {
updates = append(updates, &PluginDependency{
Name: name,
Range: r,
})
}
}
selected, err := GetAllPluginPackages(out).Resolve(microVersion, updates)
if err != nil {
fmt.Fprintln(out, err)
return
}
selected.install(out)
}
func PluginCommand(out io.Writer, cmd string, args []string) {
switch cmd {
case "install":
installedVersions := GetInstalledVersions(false)
for _, plugin := range args {
pp := GetAllPluginPackages(out).Get(plugin)
if pp == nil {
fmt.Fprintln(out, "Unknown plugin \""+plugin+"\"")
} else if err := pp.IsInstallable(out); err != nil {
fmt.Fprintln(out, "Error installing ", plugin, ": ", err)
} else {
for _, installed := range installedVersions {
if pp.Name == installed.Pack().Name {
if pp.Versions[0].Version.Compare(installed.Version) == 1 {
fmt.Fprintln(out, pp.Name, " is already installed but out-of-date: use 'plugin update ", pp.Name, "' to update")
} else {
fmt.Fprintln(out, pp.Name, " is already installed")
}
}
}
pp.Install(out)
}
}
case "remove":
removed := ""
for _, plugin := range args {
// check if the plugin exists.
for _, p := range Plugins {
if p.Name == plugin && p.Default {
fmt.Fprintln(out, "Default plugins cannot be removed, but can be disabled via settings.")
continue
}
if p.Name == plugin {
UninstallPlugin(out, plugin)
removed += plugin + " "
continue
}
}
}
if removed != "" {
fmt.Fprintln(out, "Removed ", removed)
} else {
fmt.Fprintln(out, "No plugins removed")
}
case "update":
UpdatePlugins(out, args)
case "list":
plugins := GetInstalledVersions(false)
fmt.Fprintln(out, "The following plugins are currently installed:")
for _, p := range plugins {
fmt.Fprintf(out, "%s (%s)\n", p.Pack().Name, p.Version)
}
case "search":
plugins := SearchPlugin(out, args)
fmt.Fprintln(out, len(plugins), " plugins found")
for _, p := range plugins {
fmt.Fprintln(out, "----------------")
fmt.Fprintln(out, p.String())
}
fmt.Fprintln(out, "----------------")
case "available":
packages := GetAllPluginPackages(out)
fmt.Fprintln(out, "Available Plugins:")
for _, pkg := range packages {
fmt.Fprintln(out, pkg.Name)
}
default:
fmt.Fprintln(out, "Invalid plugin command")
}
}
```
|
/content/code_sandbox/internal/config/plugin_installer.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 4,662
|
```go
package shell
import (
"bytes"
"errors"
"fmt"
"io"
"os"
"os/exec"
"os/signal"
shellquote "github.com/kballard/go-shellquote"
"github.com/zyedidia/micro/v2/internal/screen"
"github.com/zyedidia/micro/v2/internal/util"
)
// ExecCommand executes a command using exec
// It returns any output/errors
func ExecCommand(name string, arg ...string) (string, error) {
var err error
cmd := exec.Command(name, arg...)
outputBytes := &bytes.Buffer{}
cmd.Stdout = outputBytes
cmd.Stderr = outputBytes
err = cmd.Start()
if err != nil {
return "", err
}
err = cmd.Wait() // wait for command to finish
outstring := outputBytes.String()
return outstring, err
}
// RunCommand executes a shell command and returns the output/error
func RunCommand(input string) (string, error) {
args, err := shellquote.Split(input)
if err != nil {
return "", err
}
if len(args) == 0 {
return "", errors.New("No arguments")
}
inputCmd := args[0]
return ExecCommand(inputCmd, args[1:]...)
}
// RunBackgroundShell runs a shell command in the background
// It returns a function which will run the command and returns a string
// message result
func RunBackgroundShell(input string) (func() string, error) {
args, err := shellquote.Split(input)
if err != nil {
return nil, err
}
if len(args) == 0 {
return nil, errors.New("No arguments")
}
inputCmd := args[0]
return func() string {
output, err := RunCommand(input)
str := output
if err != nil {
str = fmt.Sprint(inputCmd, " exited with error: ", err, ": ", output)
}
return str
}, nil
}
// RunInteractiveShell runs a shellcommand interactively
func RunInteractiveShell(input string, wait bool, getOutput bool) (string, error) {
args, err := shellquote.Split(input)
if err != nil {
return "", err
}
if len(args) == 0 {
return "", errors.New("No arguments")
}
inputCmd := args[0]
// Shut down the screen because we're going to interact directly with the shell
screenb := screen.TempFini()
args = args[1:]
// Set up everything for the command
outputBytes := &bytes.Buffer{}
cmd := exec.Command(inputCmd, args...)
cmd.Stdin = os.Stdin
if getOutput {
cmd.Stdout = io.MultiWriter(os.Stdout, outputBytes)
} else {
cmd.Stdout = os.Stdout
}
cmd.Stderr = os.Stderr
// This is a trap for Ctrl-C so that it doesn't kill micro
// micro is killed if the signal is ignored only on Windows, so it is
// received
c := make(chan os.Signal, 1)
signal.Reset(os.Interrupt)
signal.Notify(c, os.Interrupt)
err = cmd.Start()
if err == nil {
err = cmd.Wait()
if wait {
// This is just so we don't return right away and let the user press enter to return
screen.TermMessage("")
}
} else {
screen.TermMessage(err)
}
output := outputBytes.String()
// Start the screen back up
screen.TempStart(screenb)
signal.Notify(util.Sigterm, os.Interrupt)
signal.Stop(c)
return output, err
}
// UserCommand runs the shell command
// The openTerm argument specifies whether a terminal should be opened (for viewing output
// or interacting with stdin)
// func UserCommand(input string, openTerm bool, waitToFinish bool) string {
// if !openTerm {
// RunBackgroundShell(input)
// return ""
// } else {
// output, _ := RunInteractiveShell(input, waitToFinish, false)
// return output
// }
// }
```
|
/content/code_sandbox/internal/shell/shell.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 860
|
```go
package shell
import (
"bytes"
"os/exec"
"strconv"
"github.com/zyedidia/micro/v2/internal/buffer"
"github.com/zyedidia/micro/v2/internal/screen"
"github.com/zyedidia/terminal"
)
type TermType int
type CallbackFunc func(string)
const (
TTClose = iota // Should be closed
TTRunning // Currently running a command
TTDone // Finished running a command
)
var CloseTerms chan bool
func init() {
CloseTerms = make(chan bool)
}
// A Terminal holds information for the terminal emulator
type Terminal struct {
State terminal.State
Term *terminal.VT
title string
Status TermType
Selection [2]buffer.Loc
wait bool
getOutput bool
output *bytes.Buffer
callback CallbackFunc
}
// HasSelection returns whether this terminal has a valid selection
func (t *Terminal) HasSelection() bool {
return t.Selection[0] != t.Selection[1]
}
func (t *Terminal) Name() string {
return t.title
}
// GetSelection returns the selected text
func (t *Terminal) GetSelection(width int) string {
start := t.Selection[0]
end := t.Selection[1]
if start.GreaterThan(end) {
start, end = end, start
}
var ret string
var l buffer.Loc
for y := start.Y; y <= end.Y; y++ {
for x := 0; x < width; x++ {
l.X, l.Y = x, y
if l.GreaterEqual(start) && l.LessThan(end) {
c, _, _ := t.State.Cell(x, y)
ret += string(c)
}
}
}
return ret
}
// Start begins a new command in this terminal with a given view
func (t *Terminal) Start(execCmd []string, getOutput bool, wait bool, callback func(out string, userargs []interface{}), userargs []interface{}) error {
if len(execCmd) <= 0 {
return nil
}
cmd := exec.Command(execCmd[0], execCmd[1:]...)
t.output = nil
if getOutput {
t.output = bytes.NewBuffer([]byte{})
cmd.Stdout = t.output
}
Term, _, err := terminal.Start(&t.State, cmd)
if err != nil {
return err
}
t.Term = Term
t.getOutput = getOutput
t.Status = TTRunning
t.title = execCmd[0] + ":" + strconv.Itoa(cmd.Process.Pid)
t.wait = wait
t.callback = func(out string) {
callback(out, userargs)
}
go func() {
for {
err := Term.Parse()
if err != nil {
Term.Write([]byte("Press enter to close"))
screen.Redraw()
break
}
screen.Redraw()
}
t.Stop()
}()
return nil
}
// Stop stops execution of the terminal and sets the Status
// to TTDone
func (t *Terminal) Stop() {
t.Term.File().Close()
t.Term.Close()
if t.wait {
t.Status = TTDone
} else {
t.Close()
CloseTerms <- true
}
}
// Close sets the Status to TTClose indicating that the terminal
// is done and should be closed
func (t *Terminal) Close() {
t.Status = TTClose
// call the lua function that the user has given as a callback
if t.getOutput {
if t.callback != nil {
Jobs <- JobFunction{
Function: func(out string, args []interface{}) {
t.callback(out)
},
Output: t.output.String(),
Args: nil,
}
}
}
}
// WriteString writes a given string to this terminal's pty
func (t *Terminal) WriteString(str string) {
t.Term.File().WriteString(str)
}
```
|
/content/code_sandbox/internal/shell/terminal.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 852
|
```go
package info
// A GutterMessage is a message displayed on the side of the editor
type GutterMessage struct {
lineNum int
msg string
kind int
}
// These are the different types of messages
const (
// GutterInfo represents a simple info message
GutterInfo = iota
// GutterWarning represents a compiler warning
GutterWarning
// GutterError represents a compiler error
GutterError
)
```
|
/content/code_sandbox/internal/info/gutter.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 97
|
```go
package shell
import (
"bytes"
"io"
"os/exec"
)
var Jobs chan JobFunction
func init() {
Jobs = make(chan JobFunction, 100)
}
// Jobs are the way plugins can run processes in the background
// A job is simply a process that gets executed asynchronously
// There are callbacks for when the job exits, when the job creates stdout
// and when the job creates stderr
// These jobs run in a separate goroutine but the lua callbacks need to be
// executed in the main thread (where the Lua VM is running) so they are
// put into the jobs channel which gets read by the main loop
// JobFunction is a representation of a job (this data structure is what is loaded
// into the jobs channel)
type JobFunction struct {
Function func(string, []interface{})
Output string
Args []interface{}
}
// A CallbackFile is the data structure that makes it possible to catch stderr and stdout write events
type CallbackFile struct {
io.Writer
callback func(string, []interface{})
args []interface{}
}
// Job stores the executing command for the job, and the stdin pipe
type Job struct {
*exec.Cmd
Stdin io.WriteCloser
}
func (f *CallbackFile) Write(data []byte) (int, error) {
// This is either stderr or stdout
// In either case we create a new job function callback and put it in the jobs channel
jobFunc := JobFunction{f.callback, string(data), f.args}
Jobs <- jobFunc
return f.Writer.Write(data)
}
// JobStart starts a shell command in the background with the given callbacks
// It returns an *exec.Cmd as the job id
func JobStart(cmd string, onStdout, onStderr, onExit func(string, []interface{}), userargs ...interface{}) *Job {
return JobSpawn("sh", []string{"-c", cmd}, onStdout, onStderr, onExit, userargs...)
}
// JobSpawn starts a process with args in the background with the given callbacks
// It returns an *exec.Cmd as the job id
func JobSpawn(cmdName string, cmdArgs []string, onStdout, onStderr, onExit func(string, []interface{}), userargs ...interface{}) *Job {
// Set up everything correctly if the functions have been provided
proc := exec.Command(cmdName, cmdArgs...)
var outbuf bytes.Buffer
if onStdout != nil {
proc.Stdout = &CallbackFile{&outbuf, onStdout, userargs}
} else {
proc.Stdout = &outbuf
}
if onStderr != nil {
proc.Stderr = &CallbackFile{&outbuf, onStderr, userargs}
} else {
proc.Stderr = &outbuf
}
stdin, _ := proc.StdinPipe()
go func() {
// Run the process in the background and create the onExit callback
proc.Run()
jobFunc := JobFunction{onExit, outbuf.String(), userargs}
Jobs <- jobFunc
}()
return &Job{proc, stdin}
}
// JobStop kills a job
func JobStop(j *Job) {
j.Process.Kill()
}
// JobSend sends the given data into the job's stdin stream
func JobSend(j *Job, data string) {
j.Stdin.Write([]byte(data))
}
```
|
/content/code_sandbox/internal/shell/job.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 724
|
```go
package info
import (
"encoding/gob"
"os"
"path/filepath"
"strings"
"github.com/zyedidia/micro/v2/internal/config"
"github.com/zyedidia/micro/v2/internal/util"
)
// LoadHistory attempts to load user history from configDir/buffers/history
// into the history map
// The savehistory option must be on
func (i *InfoBuf) LoadHistory() {
if config.GetGlobalOption("savehistory").(bool) {
file, err := os.Open(filepath.Join(config.ConfigDir, "buffers", "history"))
var decodedMap map[string][]string
if err == nil {
defer file.Close()
decoder := gob.NewDecoder(file)
err = decoder.Decode(&decodedMap)
if err != nil {
i.Error("Error loading history:", err)
return
}
}
if decodedMap != nil {
i.History = decodedMap
} else {
i.History = make(map[string][]string)
}
} else {
i.History = make(map[string][]string)
}
}
// SaveHistory saves the user's command history to configDir/buffers/history
// only if the savehistory option is on
func (i *InfoBuf) SaveHistory() {
if config.GetGlobalOption("savehistory").(bool) {
// Don't save history past 100
for k, v := range i.History {
if len(v) > 100 {
i.History[k] = v[len(i.History[k])-100:]
}
}
file, err := os.Create(filepath.Join(config.ConfigDir, "buffers", "history"))
if err == nil {
defer file.Close()
encoder := gob.NewEncoder(file)
err = encoder.Encode(i.History)
if err != nil {
i.Error("Error saving history:", err)
return
}
}
}
}
// AddToHistory adds a new item to the history for the prompt type `ptype`.
// This function is not used by micro itself. It is useful for plugins
// which add their own items to the history, bypassing the infobar command line.
func (i *InfoBuf) AddToHistory(ptype string, item string) {
if i.HasPrompt && i.PromptType == ptype {
return
}
if _, ok := i.History[ptype]; !ok {
i.History[ptype] = []string{item}
} else {
i.History[ptype] = append(i.History[ptype], item)
// avoid duplicates
h := i.History[ptype]
for j := len(h) - 2; j >= 0; j-- {
if h[j] == h[len(h)-1] {
i.History[ptype] = append(h[:j], h[j+1:]...)
break
}
}
}
}
// UpHistory fetches the previous item in the history
func (i *InfoBuf) UpHistory(history []string) {
if i.HistoryNum > 0 && i.HasPrompt && !i.HasYN {
i.HistoryNum--
i.Replace(i.Start(), i.End(), history[i.HistoryNum])
i.Buffer.GetActiveCursor().GotoLoc(i.End())
}
}
// DownHistory fetches the next item in the history
func (i *InfoBuf) DownHistory(history []string) {
if i.HistoryNum < len(history)-1 && i.HasPrompt && !i.HasYN {
i.HistoryNum++
i.Replace(i.Start(), i.End(), history[i.HistoryNum])
i.Buffer.GetActiveCursor().GotoLoc(i.End())
}
}
// SearchUpHistory fetches the previous item in the history
// beginning with the text in the infobuffer before cursor
func (i *InfoBuf) SearchUpHistory(history []string) {
if i.HistoryNum > 0 && i.HasPrompt && !i.HasYN {
i.searchHistory(history, false)
}
}
// SearchDownHistory fetches the next item in the history
// beginning with the text in the infobuffer before cursor
func (i *InfoBuf) SearchDownHistory(history []string) {
if i.HistoryNum < len(history)-1 && i.HasPrompt && !i.HasYN {
i.searchHistory(history, true)
}
}
func (i *InfoBuf) searchHistory(history []string, down bool) {
line := string(i.LineBytes(0))
c := i.Buffer.GetActiveCursor()
if !i.HistorySearch || !strings.HasPrefix(line, i.HistorySearchPrefix) {
i.HistorySearch = true
i.HistorySearchPrefix = util.SliceStartStr(line, c.X)
}
found := -1
if down {
for j := i.HistoryNum + 1; j < len(history); j++ {
if strings.HasPrefix(history[j], i.HistorySearchPrefix) {
found = j
break
}
}
} else {
for j := i.HistoryNum - 1; j >= 0; j-- {
if strings.HasPrefix(history[j], i.HistorySearchPrefix) {
found = j
break
}
}
}
if found != -1 {
i.HistoryNum = found
i.Replace(i.Start(), i.End(), history[found])
c.GotoLoc(i.End())
}
}
```
|
/content/code_sandbox/internal/info/history.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 1,163
|
```go
package info
import (
"fmt"
"github.com/zyedidia/micro/v2/internal/buffer"
)
// The InfoBuf displays messages and other info at the bottom of the screen.
// It is represented as a buffer and a message with a style.
type InfoBuf struct {
*buffer.Buffer
HasPrompt bool
HasMessage bool
HasError bool
HasYN bool
PromptType string
Msg string
YNResp bool
// This map stores the history for all the different kinds of uses Prompt has
// It's a map of history type -> history array
History map[string][]string
HistoryNum int
// HistorySearch indicates whether we are searching for history items
// beginning with HistorySearchPrefix
HistorySearch bool
HistorySearchPrefix string
// Is the current message a message from the gutter
HasGutter bool
PromptCallback func(resp string, canceled bool)
EventCallback func(resp string)
YNCallback func(yes bool, canceled bool)
}
// NewBuffer returns a new infobuffer
func NewBuffer() *InfoBuf {
ib := new(InfoBuf)
ib.History = make(map[string][]string)
ib.Buffer = buffer.NewBufferFromString("", "", buffer.BTInfo)
ib.LoadHistory()
return ib
}
// Close performs any cleanup necessary when shutting down the infobuffer
func (i *InfoBuf) Close() {
i.SaveHistory()
}
// Message sends a message to the user
func (i *InfoBuf) Message(msg ...interface{}) {
// only display a new message if there isn't an active prompt
// this is to prevent overwriting an existing prompt to the user
if !i.HasPrompt {
displayMessage := fmt.Sprint(msg...)
// if there is no active prompt then style and display the message as normal
i.Msg = displayMessage
i.HasMessage, i.HasError = true, false
}
}
// GutterMessage displays a message and marks it as a gutter message
func (i *InfoBuf) GutterMessage(msg ...interface{}) {
i.Message(msg...)
i.HasGutter = true
}
// ClearGutter clears the info bar and unmarks the message
func (i *InfoBuf) ClearGutter() {
i.HasGutter = false
i.Message("")
}
// Error sends an error message to the user
func (i *InfoBuf) Error(msg ...interface{}) {
// only display a new message if there isn't an active prompt
// this is to prevent overwriting an existing prompt to the user
if !i.HasPrompt {
// if there is no active prompt then style and display the message as normal
i.Msg = fmt.Sprint(msg...)
i.HasMessage, i.HasError = false, true
}
// TODO: add to log?
}
// Prompt starts a prompt for the user, it takes a prompt, a possibly partially filled in msg
// and callbacks executed when the user executes an event and when the user finishes the prompt
// The eventcb passes the current user response as the argument and donecb passes the user's message
// and a boolean indicating if the prompt was canceled
func (i *InfoBuf) Prompt(prompt string, msg string, ptype string, eventcb func(string), donecb func(string, bool)) {
// If we get another prompt mid-prompt we cancel the one getting overwritten
if i.HasPrompt {
i.DonePrompt(true)
}
if _, ok := i.History[ptype]; !ok {
i.History[ptype] = []string{""}
} else {
i.History[ptype] = append(i.History[ptype], "")
}
i.HistoryNum = len(i.History[ptype]) - 1
i.HistorySearch = false
i.PromptType = ptype
i.Msg = prompt
i.HasPrompt = true
i.HasMessage, i.HasError, i.HasYN = false, false, false
i.HasGutter = false
i.PromptCallback = donecb
i.EventCallback = eventcb
i.Buffer.Insert(i.Buffer.Start(), msg)
}
// YNPrompt creates a yes or no prompt, and the callback returns the yes/no result and whether
// the prompt was canceled
func (i *InfoBuf) YNPrompt(prompt string, donecb func(bool, bool)) {
if i.HasPrompt {
i.DonePrompt(true)
}
i.Msg = prompt
i.HasPrompt = true
i.HasYN = true
i.HasMessage, i.HasError = false, false
i.HasGutter = false
i.YNCallback = donecb
}
// DonePrompt finishes the current prompt and indicates whether or not it was canceled
func (i *InfoBuf) DonePrompt(canceled bool) {
hadYN := i.HasYN
i.HasPrompt = false
i.HasYN = false
i.HasGutter = false
if !hadYN {
if i.PromptCallback != nil {
if canceled {
i.Replace(i.Start(), i.End(), "")
h := i.History[i.PromptType]
i.History[i.PromptType] = h[:len(h)-1]
i.PromptCallback("", true)
} else {
resp := string(i.LineBytes(0))
i.Replace(i.Start(), i.End(), "")
h := i.History[i.PromptType]
h[len(h)-1] = resp
// avoid duplicates
for j := len(h) - 2; j >= 0; j-- {
if h[j] == h[len(h)-1] {
i.History[i.PromptType] = append(h[:j], h[j+1:]...)
break
}
}
i.PromptCallback(resp, false)
}
// i.PromptCallback = nil
}
}
if i.YNCallback != nil && hadYN {
i.YNCallback(i.YNResp, canceled)
}
}
// Reset resets the infobuffer's msg and info
func (i *InfoBuf) Reset() {
i.Msg = ""
i.HasPrompt, i.HasMessage, i.HasError = false, false, false
i.HasGutter = false
}
```
|
/content/code_sandbox/internal/info/infobuffer.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 1,333
|
```go
package screen
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
// TermMessage sends a message to the user in the terminal. This usually occurs before
// micro has been fully initialized -- ie if there is an error in the syntax highlighting
// regular expressions
// 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 ...interface{}) {
screenb := TempFini()
fmt.Println(msg...)
fmt.Print("\nPress enter to continue")
reader := bufio.NewReader(os.Stdin)
reader.ReadString('\n')
TempStart(screenb)
}
// TermPrompt prints a prompt and requests the user for a response
// The result is matched against a list of options and the index of
// the match is returned
// If wait is true, the prompt re-prompts until a valid option is
// chosen, otherwise if wait is false, -1 is returned for no match
func TermPrompt(prompt string, options []string, wait bool) int {
screenb := TempFini()
idx := -1
// same behavior as do { ... } while (wait && idx == -1)
for ok := true; ok; ok = wait && idx == -1 {
reader := bufio.NewReader(os.Stdin)
fmt.Print(prompt)
resp, _ := reader.ReadString('\n')
resp = strings.TrimSpace(resp)
for i, opt := range options {
if resp == opt {
idx = i
}
}
if wait && idx == -1 {
fmt.Println("\nInvalid choice.")
}
}
TempStart(screenb)
return idx
}
// TermError sends an error to the user in the terminal. Like TermMessage except formatted
// as an error
func TermError(filename string, lineNum int, err string) {
TermMessage(filename + ", " + strconv.Itoa(lineNum) + ": " + err)
}
```
|
/content/code_sandbox/internal/screen/message.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 422
|
```go
package screen
import (
"errors"
"log"
"os"
"sync"
"github.com/zyedidia/micro/v2/internal/config"
"github.com/zyedidia/micro/v2/internal/util"
"github.com/zyedidia/tcell/v2"
)
// Screen is the tcell screen we use to draw to the terminal
// Synchronization is used because we poll the screen on a separate
// thread and sometimes the screen is shut down by the main thread
// (for example on TermMessage) so we don't want to poll a nil/shutdown
// screen. TODO: maybe we should worry about polling and drawing at the
// same time too.
var Screen tcell.Screen
// Events is the channel of tcell events
var Events chan (tcell.Event)
// RestartCallback is called when the screen is restarted after it was
// temporarily shut down
var RestartCallback func()
// The lock is necessary since the screen is polled on a separate thread
var lock sync.Mutex
// drawChan is a channel that will cause the screen to redraw when
// written to even if no event user event has occurred
var drawChan chan bool
// Lock locks the screen lock
func Lock() {
lock.Lock()
}
// Unlock unlocks the screen lock
func Unlock() {
lock.Unlock()
}
// Redraw schedules a redraw with the draw channel
func Redraw() {
select {
case drawChan <- true:
default:
// channel is full
}
}
// DrawChan returns the draw channel
func DrawChan() chan bool {
return drawChan
}
type screenCell struct {
x, y int
r rune
combc []rune
style tcell.Style
}
var lastCursor screenCell
// ShowFakeCursor displays a cursor at the given position by modifying the
// style of the given column instead of actually using the terminal cursor
// This can be useful in certain terminals such as the windows console where
// modifying the cursor location is slow and frequent modifications cause flashing
// This keeps track of the most recent fake cursor location and resets it when
// a new fake cursor location is specified
func ShowFakeCursor(x, y int) {
r, combc, style, _ := Screen.GetContent(x, y)
Screen.SetContent(lastCursor.x, lastCursor.y, lastCursor.r, lastCursor.combc, lastCursor.style)
Screen.SetContent(x, y, r, combc, config.DefStyle.Reverse(true))
lastCursor.x, lastCursor.y = x, y
lastCursor.r = r
lastCursor.combc = combc
lastCursor.style = style
}
func UseFake() bool {
return util.FakeCursor || config.GetGlobalOption("fakecursor").(bool)
}
// ShowFakeCursorMulti is the same as ShowFakeCursor except it does not
// reset previous locations of the cursor
// Fake cursors are also necessary to display multiple cursors
func ShowFakeCursorMulti(x, y int) {
r, _, _, _ := Screen.GetContent(x, y)
Screen.SetContent(x, y, r, nil, config.DefStyle.Reverse(true))
}
// ShowCursor puts the cursor at the given location using a fake cursor
// if enabled or using the terminal cursor otherwise
// By default only the windows console will use a fake cursor
func ShowCursor(x, y int) {
if UseFake() {
ShowFakeCursor(x, y)
} else {
Screen.ShowCursor(x, y)
}
}
// SetContent sets a cell at a point on the screen and makes sure that it is
// synced with the last cursor location
func SetContent(x, y int, mainc rune, combc []rune, style tcell.Style) {
if !Screen.CanDisplay(mainc, true) {
mainc = ''
}
Screen.SetContent(x, y, mainc, combc, style)
if UseFake() && lastCursor.x == x && lastCursor.y == y {
lastCursor.r = mainc
lastCursor.style = style
lastCursor.combc = combc
}
}
// TempFini shuts the screen down temporarily
func TempFini() bool {
screenWasNil := Screen == nil
if !screenWasNil {
Screen.Fini()
Lock()
Screen = nil
}
return screenWasNil
}
// TempStart restarts the screen after it was temporarily disabled
func TempStart(screenWasNil bool) {
if !screenWasNil {
Init()
Unlock()
if RestartCallback != nil {
RestartCallback()
}
}
}
// Init creates and initializes the tcell screen
func Init() error {
drawChan = make(chan bool, 8)
// Should we enable true color?
truecolor := os.Getenv("MICRO_TRUECOLOR") == "1"
if !truecolor {
os.Setenv("TCELL_TRUECOLOR", "disable")
}
var oldTerm string
modifiedTerm := false
setXterm := func() {
oldTerm = os.Getenv("TERM")
os.Setenv("TERM", "xterm-256color")
modifiedTerm = true
}
if config.GetGlobalOption("xterm").(bool) {
setXterm()
}
// Initilize tcell
var err error
Screen, err = tcell.NewScreen()
if err != nil {
log.Println("Warning: during screen initialization:", err)
log.Println("Falling back to TERM=xterm-256color")
setXterm()
Screen, err = tcell.NewScreen()
if err != nil {
return err
}
}
if err = Screen.Init(); err != nil {
return err
}
Screen.SetPaste(config.GetGlobalOption("paste").(bool))
// restore TERM
if modifiedTerm {
os.Setenv("TERM", oldTerm)
}
if config.GetGlobalOption("mouse").(bool) {
Screen.EnableMouse()
}
return nil
}
// InitSimScreen initializes a simulation screen for testing purposes
func InitSimScreen() (tcell.SimulationScreen, error) {
drawChan = make(chan bool, 8)
// Initilize tcell
var err error
s := tcell.NewSimulationScreen("")
if s == nil {
return nil, errors.New("Failed to get a simulation screen")
}
if err = s.Init(); err != nil {
return nil, err
}
s.SetSize(80, 24)
Screen = s
if config.GetGlobalOption("mouse").(bool) {
Screen.EnableMouse()
}
return s, nil
}
```
|
/content/code_sandbox/internal/screen/screen.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 1,402
|
```go
package buffer
import (
"regexp"
"github.com/zyedidia/micro/v2/internal/util"
)
func (b *Buffer) findDown(r *regexp.Regexp, start, end Loc) ([2]Loc, bool) {
lastcn := util.CharacterCount(b.LineBytes(b.LinesNum() - 1))
if start.Y > b.LinesNum()-1 {
start.X = lastcn - 1
}
if end.Y > b.LinesNum()-1 {
end.X = lastcn
}
start.Y = util.Clamp(start.Y, 0, b.LinesNum()-1)
end.Y = util.Clamp(end.Y, 0, b.LinesNum()-1)
if start.GreaterThan(end) {
start, end = end, start
}
for i := start.Y; i <= end.Y; i++ {
l := b.LineBytes(i)
charpos := 0
if i == start.Y && start.Y == end.Y {
nchars := util.CharacterCount(l)
start.X = util.Clamp(start.X, 0, nchars)
end.X = util.Clamp(end.X, 0, nchars)
l = util.SliceStart(l, end.X)
l = util.SliceEnd(l, start.X)
charpos = start.X
} else if i == start.Y {
nchars := util.CharacterCount(l)
start.X = util.Clamp(start.X, 0, nchars)
l = util.SliceEnd(l, start.X)
charpos = start.X
} else if i == end.Y {
nchars := util.CharacterCount(l)
end.X = util.Clamp(end.X, 0, nchars)
l = util.SliceStart(l, end.X)
}
match := r.FindIndex(l)
if match != nil {
start := Loc{charpos + util.RunePos(l, match[0]), i}
end := Loc{charpos + util.RunePos(l, match[1]), i}
return [2]Loc{start, end}, true
}
}
return [2]Loc{}, false
}
func (b *Buffer) findUp(r *regexp.Regexp, start, end Loc) ([2]Loc, bool) {
lastcn := util.CharacterCount(b.LineBytes(b.LinesNum() - 1))
if start.Y > b.LinesNum()-1 {
start.X = lastcn - 1
}
if end.Y > b.LinesNum()-1 {
end.X = lastcn
}
start.Y = util.Clamp(start.Y, 0, b.LinesNum()-1)
end.Y = util.Clamp(end.Y, 0, b.LinesNum()-1)
if start.GreaterThan(end) {
start, end = end, start
}
for i := end.Y; i >= start.Y; i-- {
l := b.LineBytes(i)
charpos := 0
if i == start.Y && start.Y == end.Y {
nchars := util.CharacterCount(l)
start.X = util.Clamp(start.X, 0, nchars)
end.X = util.Clamp(end.X, 0, nchars)
l = util.SliceStart(l, end.X)
l = util.SliceEnd(l, start.X)
charpos = start.X
} else if i == start.Y {
nchars := util.CharacterCount(l)
start.X = util.Clamp(start.X, 0, nchars)
l = util.SliceEnd(l, start.X)
charpos = start.X
} else if i == end.Y {
nchars := util.CharacterCount(l)
end.X = util.Clamp(end.X, 0, nchars)
l = util.SliceStart(l, end.X)
}
allMatches := r.FindAllIndex(l, -1)
if allMatches != nil {
match := allMatches[len(allMatches)-1]
start := Loc{charpos + util.RunePos(l, match[0]), i}
end := Loc{charpos + util.RunePos(l, match[1]), i}
return [2]Loc{start, end}, true
}
}
return [2]Loc{}, false
}
// FindNext finds the next occurrence of a given string in the buffer
// It returns the start and end location of the match (if found) and
// a boolean indicating if it was found
// May also return an error if the search regex is invalid
func (b *Buffer) FindNext(s string, start, end, from Loc, down bool, useRegex bool) ([2]Loc, bool, error) {
if s == "" {
return [2]Loc{}, false, nil
}
var r *regexp.Regexp
var err error
if !useRegex {
s = regexp.QuoteMeta(s)
}
if b.Settings["ignorecase"].(bool) {
r, err = regexp.Compile("(?i)" + s)
} else {
r, err = regexp.Compile(s)
}
if err != nil {
return [2]Loc{}, false, err
}
var found bool
var l [2]Loc
if down {
l, found = b.findDown(r, from, end)
if !found {
l, found = b.findDown(r, start, end)
}
} else {
l, found = b.findUp(r, from, start)
if !found {
l, found = b.findUp(r, end, start)
}
}
return l, found, nil
}
// ReplaceRegex replaces all occurrences of 'search' with 'replace' in the given area
// and returns the number of replacements made and the number of runes
// added or removed on the last line of the range
func (b *Buffer) ReplaceRegex(start, end Loc, search *regexp.Regexp, replace []byte, captureGroups bool) (int, int) {
if start.GreaterThan(end) {
start, end = end, start
}
netrunes := 0
found := 0
var deltas []Delta
for i := start.Y; i <= end.Y; i++ {
l := b.lines[i].data
charpos := 0
if start.Y == end.Y && i == start.Y {
l = util.SliceStart(l, end.X)
l = util.SliceEnd(l, start.X)
charpos = start.X
} else if i == start.Y {
l = util.SliceEnd(l, start.X)
charpos = start.X
} else if i == end.Y {
l = util.SliceStart(l, end.X)
}
newText := search.ReplaceAllFunc(l, func(in []byte) []byte {
var result []byte
if captureGroups {
for _, submatches := range search.FindAllSubmatchIndex(in, -1) {
result = search.Expand(result, replace, in, submatches)
}
} else {
result = replace
}
found++
if i == end.Y {
netrunes += util.CharacterCount(result) - util.CharacterCount(in)
}
return result
})
from := Loc{charpos, i}
to := Loc{charpos + util.CharacterCount(l), i}
deltas = append(deltas, Delta{newText, from, to})
}
b.MultipleReplace(deltas)
return found, netrunes
}
```
|
/content/code_sandbox/internal/buffer/search.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 1,603
|
```go
package buffer
import (
"bufio"
"bytes"
"io"
"sync"
"github.com/zyedidia/micro/v2/internal/util"
"github.com/zyedidia/micro/v2/pkg/highlight"
)
// Finds the byte index of the nth rune in a byte slice
func runeToByteIndex(n int, txt []byte) int {
if n == 0 {
return 0
}
count := 0
i := 0
for len(txt) > 0 {
_, _, size := util.DecodeCharacter(txt)
txt = txt[size:]
count += size
i++
if i == n {
break
}
}
return count
}
// A searchState contains the search match info for a single line
type searchState struct {
search string
useRegex bool
ignorecase bool
match [][2]int
done bool
}
// A Line contains the data in bytes as well as a highlight state, match
// and a flag for whether the highlighting needs to be updated
type Line struct {
data []byte
state highlight.State
match highlight.LineMatch
lock sync.Mutex
// The search states for the line, used for highlighting of search matches,
// separately from the syntax highlighting.
// A map is used because the line array may be shared between multiple buffers
// (multiple instances of the same file opened in different edit panes)
// which have distinct searches, so in the general case there are multiple
// searches per a line, one search per a Buffer containing this line.
search map[*Buffer]*searchState
}
const (
// Line ending file formats
FFAuto = 0 // Autodetect format
FFUnix = 1 // LF line endings (unix style '\n')
FFDos = 2 // CRLF line endings (dos style '\r\n')
)
type FileFormat byte
// A LineArray simply stores and array of lines and makes it easy to insert
// and delete in it
type LineArray struct {
lines []Line
Endings FileFormat
initsize uint64
lock sync.Mutex
}
// Append efficiently appends lines together
// It allocates an additional 10000 lines if the original estimate
// is incorrect
func Append(slice []Line, data ...Line) []Line {
l := len(slice)
if l+len(data) > cap(slice) { // reallocate
newSlice := make([]Line, (l+len(data))+10000)
copy(newSlice, slice)
slice = newSlice
}
slice = slice[0 : l+len(data)]
for i, c := range data {
slice[l+i] = c
}
return slice
}
// NewLineArray returns a new line array from an array of bytes
func NewLineArray(size uint64, endings FileFormat, reader io.Reader) *LineArray {
la := new(LineArray)
la.lines = make([]Line, 0, 1000)
la.initsize = size
br := bufio.NewReader(reader)
var loaded int
la.Endings = endings
n := 0
for {
data, err := br.ReadBytes('\n')
// Detect the line ending by checking to see if there is a '\r' char
// before the '\n'
// Even if the file format is set to DOS, the '\r' is removed so
// that all lines end with '\n'
dlen := len(data)
if dlen > 1 && data[dlen-2] == '\r' {
data = append(data[:dlen-2], '\n')
if la.Endings == FFAuto {
la.Endings = FFDos
}
dlen = len(data)
} else if dlen > 0 {
if la.Endings == FFAuto {
la.Endings = FFUnix
}
}
// If we are loading a large file (greater than 1000) we use the file
// size and the length of the first 1000 lines to try to estimate
// how many lines will need to be allocated for the rest of the file
// We add an extra 10000 to the original estimate to be safe and give
// plenty of room for expansion
if n >= 1000 && loaded >= 0 {
totalLinesNum := int(float64(size) * (float64(n) / float64(loaded)))
newSlice := make([]Line, len(la.lines), totalLinesNum+10000)
copy(newSlice, la.lines)
la.lines = newSlice
loaded = -1
}
// Counter for the number of bytes in the first 1000 lines
if loaded >= 0 {
loaded += dlen
}
if err != nil {
if err == io.EOF {
la.lines = Append(la.lines, Line{
data: data,
state: nil,
match: nil,
})
}
// Last line was read
break
} else {
la.lines = Append(la.lines, Line{
data: data[:dlen-1],
state: nil,
match: nil,
})
}
n++
}
return la
}
// Bytes returns the string that should be written to disk when
// the line array is saved
func (la *LineArray) Bytes() []byte {
b := new(bytes.Buffer)
// initsize should provide a good estimate
b.Grow(int(la.initsize + 4096))
for i, l := range la.lines {
b.Write(l.data)
if i != len(la.lines)-1 {
if la.Endings == FFDos {
b.WriteByte('\r')
}
b.WriteByte('\n')
}
}
return b.Bytes()
}
// newlineBelow adds a newline below the given line number
func (la *LineArray) newlineBelow(y int) {
la.lines = append(la.lines, Line{
data: []byte{' '},
state: nil,
match: nil,
})
copy(la.lines[y+2:], la.lines[y+1:])
la.lines[y+1] = Line{
data: []byte{},
state: la.lines[y].state,
match: nil,
}
}
// Inserts a byte array at a given location
func (la *LineArray) insert(pos Loc, value []byte) {
la.lock.Lock()
defer la.lock.Unlock()
x, y := runeToByteIndex(pos.X, la.lines[pos.Y].data), pos.Y
for i := 0; i < len(value); i++ {
if value[i] == '\n' || (value[i] == '\r' && i < len(value)-1 && value[i+1] == '\n') {
la.split(Loc{x, y})
x = 0
y++
if value[i] == '\r' {
i++
}
continue
}
la.insertByte(Loc{x, y}, value[i])
x++
}
}
// InsertByte inserts a byte at a given location
func (la *LineArray) insertByte(pos Loc, value byte) {
la.lines[pos.Y].data = append(la.lines[pos.Y].data, 0)
copy(la.lines[pos.Y].data[pos.X+1:], la.lines[pos.Y].data[pos.X:])
la.lines[pos.Y].data[pos.X] = value
}
// joinLines joins the two lines a and b
func (la *LineArray) joinLines(a, b int) {
la.lines[a].data = append(la.lines[a].data, la.lines[b].data...)
la.deleteLine(b)
}
// split splits a line at a given position
func (la *LineArray) split(pos Loc) {
la.newlineBelow(pos.Y)
la.lines[pos.Y+1].data = append(la.lines[pos.Y+1].data, la.lines[pos.Y].data[pos.X:]...)
la.lines[pos.Y+1].state = la.lines[pos.Y].state
la.lines[pos.Y].state = nil
la.lines[pos.Y].match = nil
la.lines[pos.Y+1].match = nil
la.deleteToEnd(Loc{pos.X, pos.Y})
}
// removes from start to end
func (la *LineArray) remove(start, end Loc) []byte {
la.lock.Lock()
defer la.lock.Unlock()
sub := la.Substr(start, end)
startX := runeToByteIndex(start.X, la.lines[start.Y].data)
endX := runeToByteIndex(end.X, la.lines[end.Y].data)
if start.Y == end.Y {
la.lines[start.Y].data = append(la.lines[start.Y].data[:startX], la.lines[start.Y].data[endX:]...)
} else {
la.deleteLines(start.Y+1, end.Y-1)
la.deleteToEnd(Loc{startX, start.Y})
la.deleteFromStart(Loc{endX - 1, start.Y + 1})
la.joinLines(start.Y, start.Y+1)
}
return sub
}
// deleteToEnd deletes from the end of a line to the position
func (la *LineArray) deleteToEnd(pos Loc) {
la.lines[pos.Y].data = la.lines[pos.Y].data[:pos.X]
}
// deleteFromStart deletes from the start of a line to the position
func (la *LineArray) deleteFromStart(pos Loc) {
la.lines[pos.Y].data = la.lines[pos.Y].data[pos.X+1:]
}
// deleteLine deletes the line number
func (la *LineArray) deleteLine(y int) {
la.lines = la.lines[:y+copy(la.lines[y:], la.lines[y+1:])]
}
func (la *LineArray) deleteLines(y1, y2 int) {
la.lines = la.lines[:y1+copy(la.lines[y1:], la.lines[y2+1:])]
}
// DeleteByte deletes the byte at a position
func (la *LineArray) deleteByte(pos Loc) {
la.lines[pos.Y].data = la.lines[pos.Y].data[:pos.X+copy(la.lines[pos.Y].data[pos.X:], la.lines[pos.Y].data[pos.X+1:])]
}
// Substr returns the string representation between two locations
func (la *LineArray) Substr(start, end Loc) []byte {
startX := runeToByteIndex(start.X, la.lines[start.Y].data)
endX := runeToByteIndex(end.X, la.lines[end.Y].data)
if start.Y == end.Y {
src := la.lines[start.Y].data[startX:endX]
dest := make([]byte, len(src))
copy(dest, src)
return dest
}
str := make([]byte, 0, len(la.lines[start.Y+1].data)*(end.Y-start.Y))
str = append(str, la.lines[start.Y].data[startX:]...)
str = append(str, '\n')
for i := start.Y + 1; i <= end.Y-1; i++ {
str = append(str, la.lines[i].data...)
str = append(str, '\n')
}
str = append(str, la.lines[end.Y].data[:endX]...)
return str
}
// LinesNum returns the number of lines in the buffer
func (la *LineArray) LinesNum() int {
return len(la.lines)
}
// Start returns the start of the buffer
func (la *LineArray) Start() Loc {
return Loc{0, 0}
}
// End returns the location of the last character in the buffer
func (la *LineArray) End() Loc {
numlines := len(la.lines)
return Loc{util.CharacterCount(la.lines[numlines-1].data), numlines - 1}
}
// LineBytes returns line n as an array of bytes
func (la *LineArray) LineBytes(lineN int) []byte {
if lineN >= len(la.lines) || lineN < 0 {
return []byte{}
}
return la.lines[lineN].data
}
// State gets the highlight state for the given line number
func (la *LineArray) State(lineN int) highlight.State {
la.lines[lineN].lock.Lock()
defer la.lines[lineN].lock.Unlock()
return la.lines[lineN].state
}
// SetState sets the highlight state at the given line number
func (la *LineArray) SetState(lineN int, s highlight.State) {
la.lines[lineN].lock.Lock()
defer la.lines[lineN].lock.Unlock()
la.lines[lineN].state = s
}
// SetMatch sets the match at the given line number
func (la *LineArray) SetMatch(lineN int, m highlight.LineMatch) {
la.lines[lineN].lock.Lock()
defer la.lines[lineN].lock.Unlock()
la.lines[lineN].match = m
}
// Match retrieves the match for the given line number
func (la *LineArray) Match(lineN int) highlight.LineMatch {
la.lines[lineN].lock.Lock()
defer la.lines[lineN].lock.Unlock()
return la.lines[lineN].match
}
// Locks the whole LineArray
func (la *LineArray) Lock() {
la.lock.Lock()
}
// Unlocks the whole LineArray
func (la *LineArray) Unlock() {
la.lock.Unlock()
}
// SearchMatch returns true if the location `pos` is within a match
// of the last search for the buffer `b`.
// It is used for efficient highlighting of search matches (separately
// from the syntax highlighting).
// SearchMatch searches for the matches if it is called first time
// for the given line or if the line was modified. Otherwise the
// previously found matches are used.
//
// The buffer `b` needs to be passed because the line array may be shared
// between multiple buffers (multiple instances of the same file opened
// in different edit panes) which have distinct searches, so SearchMatch
// needs to know which search to match against.
func (la *LineArray) SearchMatch(b *Buffer, pos Loc) bool {
if b.LastSearch == "" {
return false
}
lineN := pos.Y
if la.lines[lineN].search == nil {
la.lines[lineN].search = make(map[*Buffer]*searchState)
}
s, ok := la.lines[lineN].search[b]
if !ok {
// Note: here is a small harmless leak: when the buffer `b` is closed,
// `s` is not deleted from the map. It means that the buffer
// will not be garbage-collected until the line array is garbage-collected,
// i.e. until all the buffers sharing this file are closed.
s = new(searchState)
la.lines[lineN].search[b] = s
}
if !ok || s.search != b.LastSearch || s.useRegex != b.LastSearchRegex ||
s.ignorecase != b.Settings["ignorecase"].(bool) {
s.search = b.LastSearch
s.useRegex = b.LastSearchRegex
s.ignorecase = b.Settings["ignorecase"].(bool)
s.done = false
}
if !s.done {
s.match = nil
start := Loc{0, lineN}
end := Loc{util.CharacterCount(la.lines[lineN].data), lineN}
for start.X < end.X {
m, found, _ := b.FindNext(b.LastSearch, start, end, start, true, b.LastSearchRegex)
if !found {
break
}
s.match = append(s.match, [2]int{m[0].X, m[1].X})
start.X = m[1].X
if m[1].X == m[0].X {
start.X = m[1].X + 1
}
}
s.done = true
}
for _, m := range s.match {
if pos.X >= m[0] && pos.X < m[1] {
return true
}
}
return false
}
// invalidateSearchMatches marks search matches for the given line as outdated.
// It is called when the line is modified.
func (la *LineArray) invalidateSearchMatches(lineN int) {
if la.lines[lineN].search != nil {
for _, s := range la.lines[lineN].search {
s.done = false
}
}
}
```
|
/content/code_sandbox/internal/buffer/line_array.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 3,589
|
```go
package buffer
import (
"fmt"
"io"
"os"
"path/filepath"
"sync/atomic"
"time"
"github.com/zyedidia/micro/v2/internal/config"
"github.com/zyedidia/micro/v2/internal/screen"
"github.com/zyedidia/micro/v2/internal/util"
"golang.org/x/text/encoding"
)
const backupMsg = `A backup was detected for this file. This likely means that micro
crashed while editing this file, or another instance of micro is currently
editing this file.
The backup was created on %s, and the file is
%s
* 'recover' will apply the backup as unsaved changes to the current buffer.
When the buffer is closed, the backup will be removed.
* 'ignore' will ignore the backup, discarding its changes. The backup file
will be removed.
* 'abort' will abort the open operation, and instead open an empty buffer.
Options: [r]ecover, [i]gnore, [a]bort: `
var backupRequestChan chan *Buffer
func backupThread() {
for {
time.Sleep(time.Second * 8)
for len(backupRequestChan) > 0 {
b := <-backupRequestChan
bfini := atomic.LoadInt32(&(b.fini)) != 0
if !bfini {
b.Backup()
}
}
}
}
func init() {
backupRequestChan = make(chan *Buffer, 10)
go backupThread()
}
func (b *Buffer) RequestBackup() {
if !b.requestedBackup {
select {
case backupRequestChan <- b:
default:
// channel is full
}
b.requestedBackup = true
}
}
// Backup saves the current buffer to ConfigDir/backups
func (b *Buffer) Backup() error {
if !b.Settings["backup"].(bool) || b.Path == "" || b.Type != BTDefault {
return nil
}
backupdir, err := util.ReplaceHome(b.Settings["backupdir"].(string))
if backupdir == "" || err != nil {
backupdir = filepath.Join(config.ConfigDir, "backups")
}
if _, err := os.Stat(backupdir); os.IsNotExist(err) {
os.Mkdir(backupdir, os.ModePerm)
}
name := filepath.Join(backupdir, util.EscapePath(b.AbsPath))
err = overwriteFile(name, encoding.Nop, func(file io.Writer) (e error) {
if len(b.lines) == 0 {
return
}
// end of line
eol := []byte{'\n'}
// write lines
if _, e = file.Write(b.lines[0].data); e != nil {
return
}
for _, l := range b.lines[1:] {
if _, e = file.Write(eol); e != nil {
return
}
if _, e = file.Write(l.data); e != nil {
return
}
}
return
}, false)
b.requestedBackup = false
return err
}
// RemoveBackup removes any backup file associated with this buffer
func (b *Buffer) RemoveBackup() {
if !b.Settings["backup"].(bool) || b.Settings["permbackup"].(bool) || b.Path == "" || b.Type != BTDefault {
return
}
f := filepath.Join(config.ConfigDir, "backups", util.EscapePath(b.AbsPath))
os.Remove(f)
}
// ApplyBackup applies the corresponding backup file to this buffer (if one exists)
// Returns true if a backup was applied
func (b *Buffer) ApplyBackup(fsize int64) (bool, bool) {
if b.Settings["backup"].(bool) && !b.Settings["permbackup"].(bool) && len(b.Path) > 0 && b.Type == BTDefault {
backupfile := filepath.Join(config.ConfigDir, "backups", util.EscapePath(b.AbsPath))
if info, err := os.Stat(backupfile); err == nil {
backup, err := os.Open(backupfile)
if err == nil {
defer backup.Close()
t := info.ModTime()
msg := fmt.Sprintf(backupMsg, t.Format("Mon Jan _2 at 15:04, 2006"), util.EscapePath(b.AbsPath))
choice := screen.TermPrompt(msg, []string{"r", "i", "a", "recover", "ignore", "abort"}, true)
if choice%3 == 0 {
// recover
b.LineArray = NewLineArray(uint64(fsize), FFAuto, backup)
b.isModified = true
return true, true
} else if choice%3 == 1 {
// delete
os.Remove(backupfile)
} else if choice%3 == 2 {
return false, false
}
}
}
}
return false, true
}
```
|
/content/code_sandbox/internal/buffer/backup.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 1,069
|
```go
package buffer
import (
"bytes"
"time"
dmp "github.com/sergi/go-diff/diffmatchpatch"
"github.com/zyedidia/micro/v2/internal/config"
ulua "github.com/zyedidia/micro/v2/internal/lua"
"github.com/zyedidia/micro/v2/internal/screen"
"github.com/zyedidia/micro/v2/internal/util"
luar "layeh.com/gopher-luar"
)
const (
// Opposite and undoing events must have opposite values
// TextEventInsert represents an insertion event
TextEventInsert = 1
// TextEventRemove represents a deletion event
TextEventRemove = -1
// TextEventReplace represents a replace event
TextEventReplace = 0
undoThreshold = 1000 // If two events are less than n milliseconds apart, undo both of them
)
// TextEvent holds data for a manipulation on some text that can be undone
type TextEvent struct {
C Cursor
EventType int
Deltas []Delta
Time time.Time
}
// A Delta is a change to the buffer
type Delta struct {
Text []byte
Start Loc
End Loc
}
// DoTextEvent runs a text event
func (eh *EventHandler) DoTextEvent(t *TextEvent, useUndo bool) {
oldl := eh.buf.LinesNum()
if useUndo {
eh.Execute(t)
} else {
ExecuteTextEvent(t, eh.buf)
}
if len(t.Deltas) != 1 {
return
}
text := t.Deltas[0].Text
start := t.Deltas[0].Start
lastnl := -1
var endX int
var textX int
if t.EventType == TextEventInsert {
linecount := eh.buf.LinesNum() - oldl
textcount := util.CharacterCount(text)
lastnl = bytes.LastIndex(text, []byte{'\n'})
if lastnl >= 0 {
endX = util.CharacterCount(text[lastnl+1:])
textX = endX
} else {
endX = start.X + textcount
textX = textcount
}
t.Deltas[0].End = clamp(Loc{endX, start.Y + linecount}, eh.buf.LineArray)
}
end := t.Deltas[0].End
for _, c := range eh.cursors {
move := func(loc Loc) Loc {
if t.EventType == TextEventInsert {
if start.Y != loc.Y && loc.GreaterThan(start) {
loc.Y += end.Y - start.Y
} else if loc.Y == start.Y && loc.GreaterEqual(start) {
loc.Y += end.Y - start.Y
if lastnl >= 0 {
loc.X += textX - start.X
} else {
loc.X += textX
}
}
return loc
} else {
if loc.Y != end.Y && loc.GreaterThan(end) {
loc.Y -= end.Y - start.Y
} else if loc.Y == end.Y && loc.GreaterEqual(end) {
loc = loc.MoveLA(-DiffLA(start, end, eh.buf.LineArray), eh.buf.LineArray)
}
return loc
}
}
c.Loc = move(c.Loc)
c.CurSelection[0] = move(c.CurSelection[0])
c.CurSelection[1] = move(c.CurSelection[1])
c.OrigSelection[0] = move(c.OrigSelection[0])
c.OrigSelection[1] = move(c.OrigSelection[1])
c.Relocate()
c.LastVisualX = c.GetVisualX()
}
if useUndo {
eh.updateTrailingWs(t)
}
}
// ExecuteTextEvent runs a text event
func ExecuteTextEvent(t *TextEvent, buf *SharedBuffer) {
if t.EventType == TextEventInsert {
for _, d := range t.Deltas {
buf.insert(d.Start, d.Text)
}
} else if t.EventType == TextEventRemove {
for i, d := range t.Deltas {
t.Deltas[i].Text = buf.remove(d.Start, d.End)
}
} else if t.EventType == TextEventReplace {
for i, d := range t.Deltas {
t.Deltas[i].Text = buf.remove(d.Start, d.End)
buf.insert(d.Start, d.Text)
t.Deltas[i].Start = d.Start
t.Deltas[i].End = Loc{d.Start.X + util.CharacterCount(d.Text), d.Start.Y}
}
for i, j := 0, len(t.Deltas)-1; i < j; i, j = i+1, j-1 {
t.Deltas[i], t.Deltas[j] = t.Deltas[j], t.Deltas[i]
}
}
}
// UndoTextEvent undoes a text event
func (eh *EventHandler) UndoTextEvent(t *TextEvent) {
t.EventType = -t.EventType
eh.DoTextEvent(t, false)
}
// EventHandler executes text manipulations and allows undoing and redoing
type EventHandler struct {
buf *SharedBuffer
cursors []*Cursor
active int
UndoStack *TEStack
RedoStack *TEStack
}
// NewEventHandler returns a new EventHandler
func NewEventHandler(buf *SharedBuffer, cursors []*Cursor) *EventHandler {
eh := new(EventHandler)
eh.UndoStack = new(TEStack)
eh.RedoStack = new(TEStack)
eh.buf = buf
eh.cursors = cursors
return eh
}
// ApplyDiff takes a string and runs the necessary insertion and deletion events to make
// the buffer equal to that string
// This means that we can transform the buffer into any string and still preserve undo/redo
// through insert and delete events
func (eh *EventHandler) ApplyDiff(new string) {
differ := dmp.New()
diff := differ.DiffMain(string(eh.buf.Bytes()), new, false)
loc := eh.buf.Start()
for _, d := range diff {
if d.Type == dmp.DiffDelete {
eh.Remove(loc, loc.MoveLA(util.CharacterCountInString(d.Text), eh.buf.LineArray))
} else {
if d.Type == dmp.DiffInsert {
eh.Insert(loc, d.Text)
}
loc = loc.MoveLA(util.CharacterCountInString(d.Text), eh.buf.LineArray)
}
}
}
// Insert creates an insert text event and executes it
func (eh *EventHandler) Insert(start Loc, textStr string) {
text := []byte(textStr)
eh.InsertBytes(start, text)
}
// InsertBytes creates an insert text event and executes it
func (eh *EventHandler) InsertBytes(start Loc, text []byte) {
if len(text) == 0 {
return
}
start = clamp(start, eh.buf.LineArray)
e := &TextEvent{
C: *eh.cursors[eh.active],
EventType: TextEventInsert,
Deltas: []Delta{{text, start, Loc{0, 0}}},
Time: time.Now(),
}
eh.DoTextEvent(e, true)
}
// Remove creates a remove text event and executes it
func (eh *EventHandler) Remove(start, end Loc) {
if start == end {
return
}
start = clamp(start, eh.buf.LineArray)
end = clamp(end, eh.buf.LineArray)
e := &TextEvent{
C: *eh.cursors[eh.active],
EventType: TextEventRemove,
Deltas: []Delta{{[]byte{}, start, end}},
Time: time.Now(),
}
eh.DoTextEvent(e, true)
}
// MultipleReplace creates an multiple insertions executes them
func (eh *EventHandler) MultipleReplace(deltas []Delta) {
e := &TextEvent{
C: *eh.cursors[eh.active],
EventType: TextEventReplace,
Deltas: deltas,
Time: time.Now(),
}
eh.Execute(e)
}
// Replace deletes from start to end and replaces it with the given string
func (eh *EventHandler) Replace(start, end Loc, replace string) {
eh.Remove(start, end)
eh.Insert(start, replace)
}
// Execute a textevent and add it to the undo stack
func (eh *EventHandler) Execute(t *TextEvent) {
if eh.RedoStack.Len() > 0 {
eh.RedoStack = new(TEStack)
}
eh.UndoStack.Push(t)
b, err := config.RunPluginFnBool(nil, "onBeforeTextEvent", luar.New(ulua.L, eh.buf), luar.New(ulua.L, t))
if err != nil {
screen.TermMessage(err)
}
if !b {
return
}
ExecuteTextEvent(t, eh.buf)
}
// Undo the first event in the undo stack. Returns false if the stack is empty.
func (eh *EventHandler) Undo() bool {
t := eh.UndoStack.Peek()
if t == nil {
return false
}
startTime := t.Time.UnixNano() / int64(time.Millisecond)
endTime := startTime - (startTime % undoThreshold)
for {
t = eh.UndoStack.Peek()
if t == nil {
break
}
if t.Time.UnixNano()/int64(time.Millisecond) < endTime {
break
}
eh.UndoOneEvent()
}
return true
}
// UndoOneEvent undoes one event
func (eh *EventHandler) UndoOneEvent() {
// This event should be undone
// Pop it off the stack
t := eh.UndoStack.Pop()
if t == nil {
return
}
// Undo it
// Modifies the text event
eh.UndoTextEvent(t)
// Set the cursor in the right place
if t.C.Num >= 0 && t.C.Num < len(eh.cursors) {
eh.cursors[t.C.Num].Goto(t.C)
eh.cursors[t.C.Num].NewTrailingWsY = t.C.NewTrailingWsY
}
// Push it to the redo stack
eh.RedoStack.Push(t)
}
// Redo the first event in the redo stack. Returns false if the stack is empty.
func (eh *EventHandler) Redo() bool {
t := eh.RedoStack.Peek()
if t == nil {
return false
}
startTime := t.Time.UnixNano() / int64(time.Millisecond)
endTime := startTime - (startTime % undoThreshold) + undoThreshold
for {
t = eh.RedoStack.Peek()
if t == nil {
break
}
if t.Time.UnixNano()/int64(time.Millisecond) > endTime {
break
}
eh.RedoOneEvent()
}
return true
}
// RedoOneEvent redoes one event
func (eh *EventHandler) RedoOneEvent() {
t := eh.RedoStack.Pop()
if t == nil {
return
}
if t.C.Num >= 0 && t.C.Num < len(eh.cursors) {
eh.cursors[t.C.Num].Goto(t.C)
eh.cursors[t.C.Num].NewTrailingWsY = t.C.NewTrailingWsY
}
// Modifies the text event
eh.UndoTextEvent(t)
eh.UndoStack.Push(t)
}
// updateTrailingWs updates the cursor's trailing whitespace status after a text event
func (eh *EventHandler) updateTrailingWs(t *TextEvent) {
if len(t.Deltas) != 1 {
return
}
text := t.Deltas[0].Text
start := t.Deltas[0].Start
end := t.Deltas[0].End
c := eh.cursors[eh.active]
isEol := func(loc Loc) bool {
return loc.X == util.CharacterCount(eh.buf.LineBytes(loc.Y))
}
if t.EventType == TextEventInsert && c.Loc == end && isEol(end) {
var addedTrailingWs bool
addedAfterWs := false
addedWsOnly := false
if start.Y == end.Y {
addedTrailingWs = util.HasTrailingWhitespace(text)
addedWsOnly = util.IsBytesWhitespace(text)
addedAfterWs = start.X > 0 && util.IsWhitespace(c.buf.RuneAt(Loc{start.X - 1, start.Y}))
} else {
lastnl := bytes.LastIndex(text, []byte{'\n'})
addedTrailingWs = util.HasTrailingWhitespace(text[lastnl+1:])
}
if addedTrailingWs && !(addedAfterWs && addedWsOnly) {
c.NewTrailingWsY = c.Y
} else if !addedTrailingWs {
c.NewTrailingWsY = -1
}
} else if t.EventType == TextEventRemove && c.Loc == start && isEol(start) {
removedAfterWs := util.HasTrailingWhitespace(eh.buf.LineBytes(start.Y))
var removedWsOnly bool
if start.Y == end.Y {
removedWsOnly = util.IsBytesWhitespace(text)
} else {
firstnl := bytes.Index(text, []byte{'\n'})
removedWsOnly = util.IsBytesWhitespace(text[:firstnl])
}
if removedAfterWs && !removedWsOnly {
c.NewTrailingWsY = c.Y
} else if !removedAfterWs {
c.NewTrailingWsY = -1
}
} else if c.NewTrailingWsY != -1 && start.Y != end.Y && c.Loc.GreaterThan(start) &&
((t.EventType == TextEventInsert && c.Y == c.NewTrailingWsY+(end.Y-start.Y)) ||
(t.EventType == TextEventRemove && c.Y == c.NewTrailingWsY-(end.Y-start.Y))) {
// The cursor still has its new trailingws
// but its line number was shifted by insert or remove of lines above
c.NewTrailingWsY = c.Y
}
}
```
|
/content/code_sandbox/internal/buffer/eventhandler.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 3,075
|
```go
package buffer
import (
"crypto/md5"
"reflect"
"github.com/zyedidia/micro/v2/internal/config"
"github.com/zyedidia/micro/v2/internal/screen"
)
func (b *Buffer) ReloadSettings(reloadFiletype bool) {
settings := config.ParsedSettings()
if _, ok := b.LocalSettings["filetype"]; !ok && reloadFiletype {
// need to update filetype before updating other settings based on it
b.Settings["filetype"] = "unknown"
if v, ok := settings["filetype"]; ok {
b.Settings["filetype"] = v
}
}
// update syntax rules, which will also update filetype if needed
b.UpdateRules()
settings["filetype"] = b.Settings["filetype"]
config.InitLocalSettings(settings, b.Path)
for k, v := range config.DefaultCommonSettings() {
if k == "filetype" {
// prevent recursion
continue
}
if _, ok := config.VolatileSettings[k]; ok {
// reload should not override volatile settings
continue
}
if _, ok := b.LocalSettings[k]; ok {
// reload should not override local settings
continue
}
if _, ok := settings[k]; ok {
b.DoSetOptionNative(k, settings[k])
} else {
b.DoSetOptionNative(k, v)
}
}
}
func (b *Buffer) DoSetOptionNative(option string, nativeValue interface{}) {
if reflect.DeepEqual(b.Settings[option], nativeValue) {
return
}
b.Settings[option] = nativeValue
if option == "fastdirty" {
if !nativeValue.(bool) {
if b.Size() > LargeFileThreshold {
b.Settings["fastdirty"] = true
} else {
if !b.isModified {
calcHash(b, &b.origHash)
} else {
// prevent using an old stale origHash value
b.origHash = [md5.Size]byte{}
}
}
}
} else if option == "statusline" {
screen.Redraw()
} else if option == "filetype" {
b.ReloadSettings(false)
} else if option == "fileformat" {
switch b.Settings["fileformat"].(string) {
case "unix":
b.Endings = FFUnix
case "dos":
b.Endings = FFDos
}
b.isModified = true
} else if option == "syntax" {
if !nativeValue.(bool) {
b.ClearMatches()
} else {
b.UpdateRules()
}
} else if option == "encoding" {
b.isModified = true
} else if option == "readonly" && b.Type.Kind == BTDefault.Kind {
b.Type.Readonly = nativeValue.(bool)
} else if option == "hlsearch" {
for _, buf := range OpenBuffers {
if b.SharedBuffer == buf.SharedBuffer {
buf.HighlightSearch = nativeValue.(bool)
}
}
} else {
for _, pl := range config.Plugins {
if option == pl.Name {
if nativeValue.(bool) {
if !pl.Loaded {
pl.Load()
}
_, err := pl.Call("init")
if err != nil && err != config.ErrNoSuchFunction {
screen.TermMessage(err)
}
} else if !nativeValue.(bool) && pl.Loaded {
_, err := pl.Call("deinit")
if err != nil && err != config.ErrNoSuchFunction {
screen.TermMessage(err)
}
}
}
}
}
if b.OptionCallback != nil {
b.OptionCallback(option, nativeValue)
}
}
func (b *Buffer) SetOptionNative(option string, nativeValue interface{}) error {
if err := config.OptionIsValid(option, nativeValue); err != nil {
return err
}
b.DoSetOptionNative(option, nativeValue)
b.LocalSettings[option] = true
return nil
}
// SetOption sets a given option to a value just for this buffer
func (b *Buffer) SetOption(option, value string) error {
if _, ok := b.Settings[option]; !ok {
return config.ErrInvalidOption
}
nativeValue, err := config.GetNativeValue(option, b.Settings[option], value)
if err != nil {
return err
}
return b.SetOptionNative(option, nativeValue)
}
```
|
/content/code_sandbox/internal/buffer/settings.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 980
|
```go
package buffer
import (
"github.com/zyedidia/micro/v2/internal/config"
"github.com/zyedidia/tcell/v2"
)
type MsgType int
const (
MTInfo = iota
MTWarning
MTError
)
// Message represents the information for a gutter message
type Message struct {
// The Msg iteslf
Msg string
// Start and End locations for the message
Start, End Loc
// The Kind stores the message type
Kind MsgType
// The Owner of the message
Owner string
}
// NewMessage creates a new gutter message
func NewMessage(owner string, msg string, start, end Loc, kind MsgType) *Message {
return &Message{
Msg: msg,
Start: start,
End: end,
Kind: kind,
Owner: owner,
}
}
// NewMessageAtLine creates a new gutter message at a given line
func NewMessageAtLine(owner string, msg string, line int, kind MsgType) *Message {
start := Loc{-1, line - 1}
end := start
return NewMessage(owner, msg, start, end, kind)
}
func (m *Message) Style() tcell.Style {
switch m.Kind {
case MTInfo:
if style, ok := config.Colorscheme["gutter-info"]; ok {
return style
}
case MTWarning:
if style, ok := config.Colorscheme["gutter-warning"]; ok {
return style
}
case MTError:
if style, ok := config.Colorscheme["gutter-error"]; ok {
return style
}
}
return config.DefStyle
}
func (b *Buffer) AddMessage(m *Message) {
b.Messages = append(b.Messages, m)
}
func (b *Buffer) removeMsg(i int) {
copy(b.Messages[i:], b.Messages[i+1:])
b.Messages[len(b.Messages)-1] = nil
b.Messages = b.Messages[:len(b.Messages)-1]
}
func (b *Buffer) ClearMessages(owner string) {
for i := len(b.Messages) - 1; i >= 0; i-- {
if b.Messages[i].Owner == owner {
b.removeMsg(i)
}
}
}
func (b *Buffer) ClearAllMessages() {
b.Messages = make([]*Message, 0)
}
type Messager interface {
Message(msg ...interface{})
}
var prompt Messager
func SetMessager(m Messager) {
prompt = m
}
```
|
/content/code_sandbox/internal/buffer/message.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 537
|
```go
package buffer
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestStack(t *testing.T) {
s := new(TEStack)
e1 := &TextEvent{
EventType: TextEventReplace,
Time: time.Now(),
}
e2 := &TextEvent{
EventType: TextEventInsert,
Time: time.Now(),
}
s.Push(e1)
s.Push(e2)
p := s.Peek()
assert.Equal(t, p.EventType, TextEventInsert)
p = s.Pop()
assert.Equal(t, p.EventType, TextEventInsert)
p = s.Peek()
assert.Equal(t, p.EventType, TextEventReplace)
p = s.Pop()
assert.Equal(t, p.EventType, TextEventReplace)
p = s.Pop()
assert.Nil(t, p)
p = s.Peek()
assert.Nil(t, p)
}
```
|
/content/code_sandbox/internal/buffer/stack_test.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 181
|
```go
package buffer
import (
"bytes"
"io/ioutil"
"os"
"sort"
"strings"
"github.com/zyedidia/micro/v2/internal/util"
)
// A Completer is a function that takes a buffer and returns info
// describing what autocompletions should be inserted at the current
// cursor location
// It returns a list of string suggestions which will be inserted at
// the current cursor location if selected as well as a list of
// suggestion names which can be displayed in an autocomplete box or
// other UI element
type Completer func(*Buffer) ([]string, []string)
func (b *Buffer) GetSuggestions() {
}
// Autocomplete starts the autocomplete process
func (b *Buffer) Autocomplete(c Completer) bool {
b.Completions, b.Suggestions = c(b)
if len(b.Completions) != len(b.Suggestions) || len(b.Completions) == 0 {
return false
}
b.CurSuggestion = -1
b.CycleAutocomplete(true)
return true
}
// CycleAutocomplete moves to the next suggestion
func (b *Buffer) CycleAutocomplete(forward bool) {
prevSuggestion := b.CurSuggestion
if forward {
b.CurSuggestion++
} else {
b.CurSuggestion--
}
if b.CurSuggestion >= len(b.Suggestions) {
b.CurSuggestion = 0
} else if b.CurSuggestion < 0 {
b.CurSuggestion = len(b.Suggestions) - 1
}
c := b.GetActiveCursor()
start := c.Loc
end := c.Loc
if prevSuggestion < len(b.Suggestions) && prevSuggestion >= 0 {
start = end.Move(-util.CharacterCountInString(b.Completions[prevSuggestion]), b)
}
b.Replace(start, end, b.Completions[b.CurSuggestion])
if len(b.Suggestions) > 1 {
b.HasSuggestions = true
}
}
// GetWord gets the most recent word separated by any separator
// (whitespace, punctuation, any non alphanumeric character)
func (b *Buffer) GetWord() ([]byte, int) {
c := b.GetActiveCursor()
l := b.LineBytes(c.Y)
l = util.SliceStart(l, c.X)
if c.X == 0 || util.IsWhitespace(b.RuneAt(c.Loc.Move(-1, b))) {
return []byte{}, -1
}
if util.IsNonWordChar(b.RuneAt(c.Loc.Move(-1, b))) {
return []byte{}, c.X
}
args := bytes.FieldsFunc(l, util.IsNonWordChar)
input := args[len(args)-1]
return input, c.X - util.CharacterCount(input)
}
// GetArg gets the most recent word (separated by ' ' only)
func (b *Buffer) GetArg() (string, int) {
c := b.GetActiveCursor()
l := b.LineBytes(c.Y)
l = util.SliceStart(l, c.X)
args := bytes.Split(l, []byte{' '})
input := string(args[len(args)-1])
argstart := 0
for i, a := range args {
if i == len(args)-1 {
break
}
argstart += util.CharacterCount(a) + 1
}
return input, argstart
}
// FileComplete autocompletes filenames
func FileComplete(b *Buffer) ([]string, []string) {
c := b.GetActiveCursor()
input, argstart := b.GetArg()
sep := string(os.PathSeparator)
dirs := strings.Split(input, sep)
var files []os.FileInfo
var err error
if len(dirs) > 1 {
directories := strings.Join(dirs[:len(dirs)-1], sep) + sep
directories, _ = util.ReplaceHome(directories)
files, err = ioutil.ReadDir(directories)
} else {
files, err = ioutil.ReadDir(".")
}
if err != nil {
return nil, nil
}
var suggestions []string
for _, f := range files {
name := f.Name()
if f.IsDir() {
name += sep
}
if strings.HasPrefix(name, dirs[len(dirs)-1]) {
suggestions = append(suggestions, name)
}
}
sort.Strings(suggestions)
completions := make([]string, len(suggestions))
for i := range suggestions {
var complete string
if len(dirs) > 1 {
complete = strings.Join(dirs[:len(dirs)-1], sep) + sep + suggestions[i]
} else {
complete = suggestions[i]
}
completions[i] = util.SliceEndStr(complete, c.X-argstart)
}
return completions, suggestions
}
// BufferComplete autocompletes based on previous words in the buffer
func BufferComplete(b *Buffer) ([]string, []string) {
c := b.GetActiveCursor()
input, argstart := b.GetWord()
if argstart == -1 {
return []string{}, []string{}
}
inputLen := util.CharacterCount(input)
suggestionsSet := make(map[string]struct{})
var suggestions []string
for i := c.Y; i >= 0; i-- {
l := b.LineBytes(i)
words := bytes.FieldsFunc(l, util.IsNonWordChar)
for _, w := range words {
if bytes.HasPrefix(w, input) && util.CharacterCount(w) > inputLen {
strw := string(w)
if _, ok := suggestionsSet[strw]; !ok {
suggestionsSet[strw] = struct{}{}
suggestions = append(suggestions, strw)
}
}
}
}
for i := c.Y + 1; i < b.LinesNum(); i++ {
l := b.LineBytes(i)
words := bytes.FieldsFunc(l, util.IsNonWordChar)
for _, w := range words {
if bytes.HasPrefix(w, input) && util.CharacterCount(w) > inputLen {
strw := string(w)
if _, ok := suggestionsSet[strw]; !ok {
suggestionsSet[strw] = struct{}{}
suggestions = append(suggestions, strw)
}
}
}
}
if len(suggestions) > 1 {
suggestions = append(suggestions, string(input))
}
completions := make([]string, len(suggestions))
for i := range suggestions {
completions[i] = util.SliceEndStr(suggestions[i], c.X-argstart)
}
return completions, suggestions
}
```
|
/content/code_sandbox/internal/buffer/autocomplete.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 1,433
|
```go
package buffer
import (
"encoding/gob"
"errors"
"io"
"os"
"path/filepath"
"time"
"golang.org/x/text/encoding"
"github.com/zyedidia/micro/v2/internal/config"
"github.com/zyedidia/micro/v2/internal/util"
)
// The SerializedBuffer holds the types that get serialized when a buffer is saved
// These are used for the savecursor and saveundo options
type SerializedBuffer struct {
EventHandler *EventHandler
Cursor Loc
ModTime time.Time
}
// Serialize serializes the buffer to config.ConfigDir/buffers
func (b *Buffer) Serialize() error {
if !b.Settings["savecursor"].(bool) && !b.Settings["saveundo"].(bool) {
return nil
}
if b.Path == "" {
return nil
}
name := filepath.Join(config.ConfigDir, "buffers", util.EscapePath(b.AbsPath))
return overwriteFile(name, encoding.Nop, func(file io.Writer) error {
err := gob.NewEncoder(file).Encode(SerializedBuffer{
b.EventHandler,
b.GetActiveCursor().Loc,
b.ModTime,
})
return err
}, false)
}
// Unserialize loads the buffer info from config.ConfigDir/buffers
func (b *Buffer) Unserialize() error {
// If either savecursor or saveundo is turned on, we need to load the serialized information
// from ~/.config/micro/buffers
if b.Path == "" {
return nil
}
file, err := os.Open(filepath.Join(config.ConfigDir, "buffers", util.EscapePath(b.AbsPath)))
if err == nil {
defer file.Close()
var buffer SerializedBuffer
decoder := gob.NewDecoder(file)
err = decoder.Decode(&buffer)
if err != nil {
return errors.New(err.Error() + "\nYou may want to remove the files in ~/.config/micro/buffers (these files\nstore the information for the 'saveundo' and 'savecursor' options) if\nthis problem persists.\nThis may be caused by upgrading to version 2.0, and removing the 'buffers'\ndirectory will reset the cursor and undo history and solve the problem.")
}
if b.Settings["savecursor"].(bool) {
b.StartCursor = buffer.Cursor
}
if b.Settings["saveundo"].(bool) {
// We should only use last time's eventhandler if the file wasn't modified by someone else in the meantime
if b.ModTime == buffer.ModTime {
b.EventHandler = buffer.EventHandler
b.EventHandler.cursors = b.cursors
b.EventHandler.buf = b.SharedBuffer
}
}
}
return nil
}
```
|
/content/code_sandbox/internal/buffer/serialize.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 577
|
```go
package buffer
import (
"math/rand"
"strings"
"testing"
"github.com/stretchr/testify/assert"
lua "github.com/yuin/gopher-lua"
"github.com/zyedidia/micro/v2/internal/config"
ulua "github.com/zyedidia/micro/v2/internal/lua"
"github.com/zyedidia/micro/v2/internal/util"
)
type operation struct {
start Loc
end Loc
text []string
}
func init() {
ulua.L = lua.NewState()
config.InitRuntimeFiles(false)
config.InitGlobalSettings()
config.GlobalSettings["backup"] = false
config.GlobalSettings["fastdirty"] = true
}
func check(t *testing.T, before []string, operations []operation, after []string) {
assert := assert.New(t)
b := NewBufferFromString(strings.Join(before, "\n"), "", BTDefault)
assert.NotEqual("", b.GetName())
assert.Equal(false, b.ExternallyModified())
assert.Equal(false, b.Modified())
assert.Equal(1, b.NumCursors())
checkText := func(lines []string) {
assert.Equal([]byte(strings.Join(lines, "\n")), b.Bytes())
assert.Equal(len(lines), b.LinesNum())
for i, s := range lines {
assert.Equal(s, b.Line(i))
assert.Equal([]byte(s), b.LineBytes(i))
}
}
checkText(before)
var cursors []*Cursor
for _, op := range operations {
cursor := NewCursor(b, op.start)
cursor.SetSelectionStart(op.start)
cursor.SetSelectionEnd(op.end)
b.AddCursor(cursor)
cursors = append(cursors, cursor)
}
assert.Equal(1+len(operations), b.NumCursors())
for i, op := range operations {
cursor := cursors[i]
b.SetCurCursor(cursor.Num)
cursor.DeleteSelection()
b.Insert(cursor.Loc, strings.Join(op.text, "\n"))
}
checkText(after)
// must have exactly two events per operation (delete and insert)
for range operations {
b.UndoOneEvent()
b.UndoOneEvent()
}
checkText(before)
for i, op := range operations {
cursor := cursors[i]
if op.start == op.end {
assert.Equal(op.start, cursor.Loc)
} else {
assert.Equal(op.start, cursor.CurSelection[0])
assert.Equal(op.end, cursor.CurSelection[1])
}
}
for range operations {
b.RedoOneEvent()
b.RedoOneEvent()
}
checkText(after)
b.Close()
}
const maxLineLength = 200
var alphabet = []rune(" abcde")
func randomString(length int) string {
runes := make([]rune, length)
for i := range runes {
runes[i] = alphabet[rand.Intn(len(alphabet))]
}
return string(runes)
}
func randomText(nLines int) string {
lines := make([]string, nLines)
for i := range lines {
lines[i] = randomString(rand.Intn(maxLineLength + 1))
}
return strings.Join(lines, "\n")
}
func benchCreateAndClose(testingB *testing.B, nLines int) {
rand.Seed(int64(nLines))
text := randomText(nLines)
testingB.ResetTimer()
for i := 0; i < testingB.N; i++ {
b := NewBufferFromString(text, "", BTDefault)
b.Close()
}
}
func benchRead(testingB *testing.B, nLines int) {
rand.Seed(int64(nLines))
b := NewBufferFromString(randomText(nLines), "", BTDefault)
testingB.ResetTimer()
for i := 0; i < testingB.N; i++ {
b.Bytes()
for j := 0; j < b.LinesNum(); j++ {
b.Line(j)
b.LineBytes(j)
}
}
testingB.StopTimer()
b.Close()
}
func benchEdit(testingB *testing.B, nLines, nCursors int) {
rand.Seed(int64(nLines + nCursors))
b := NewBufferFromString(randomText(nLines), "", BTDefault)
regionSize := nLines / nCursors
operations := make([]operation, nCursors)
for i := range operations {
startLine := (i * regionSize) + rand.Intn(regionSize-5)
startColumn := rand.Intn(util.CharacterCountInString(b.Line(startLine)) + 1)
endLine := startLine + 1 + rand.Intn(5)
endColumn := rand.Intn(util.CharacterCountInString(b.Line(endLine)) + 1)
operations[i] = operation{
start: Loc{startColumn, startLine},
end: Loc{endColumn, endLine},
text: []string{randomText(2 + rand.Intn(4))},
}
}
testingB.ResetTimer()
for i := 0; i < testingB.N; i++ {
b.SetCursors([]*Cursor{})
var cursors []*Cursor
for _, op := range operations {
cursor := NewCursor(b, op.start)
cursor.SetSelectionStart(op.start)
cursor.SetSelectionEnd(op.end)
b.AddCursor(cursor)
cursors = append(cursors, cursor)
}
for j, op := range operations {
cursor := cursors[j]
b.SetCurCursor(cursor.Num)
cursor.DeleteSelection()
b.Insert(cursor.Loc, op.text[0])
}
for b.UndoStack.Peek() != nil {
b.UndoOneEvent()
}
}
testingB.StopTimer()
b.Close()
}
func BenchmarkCreateAndClose10Lines(b *testing.B) {
benchCreateAndClose(b, 10)
}
func BenchmarkCreateAndClose100Lines(b *testing.B) {
benchCreateAndClose(b, 100)
}
func BenchmarkCreateAndClose1000Lines(b *testing.B) {
benchCreateAndClose(b, 1000)
}
func BenchmarkCreateAndClose10000Lines(b *testing.B) {
benchCreateAndClose(b, 10000)
}
func BenchmarkCreateAndClose100000Lines(b *testing.B) {
benchCreateAndClose(b, 100000)
}
func BenchmarkCreateAndClose1000000Lines(b *testing.B) {
benchCreateAndClose(b, 1000000)
}
func BenchmarkRead10Lines(b *testing.B) {
benchRead(b, 10)
}
func BenchmarkRead100Lines(b *testing.B) {
benchRead(b, 100)
}
func BenchmarkRead1000Lines(b *testing.B) {
benchRead(b, 1000)
}
func BenchmarkRead10000Lines(b *testing.B) {
benchRead(b, 10000)
}
func BenchmarkRead100000Lines(b *testing.B) {
benchRead(b, 100000)
}
func BenchmarkRead1000000Lines(b *testing.B) {
benchRead(b, 1000000)
}
func BenchmarkEdit10Lines1Cursor(b *testing.B) {
benchEdit(b, 10, 1)
}
func BenchmarkEdit100Lines1Cursor(b *testing.B) {
benchEdit(b, 100, 1)
}
func BenchmarkEdit100Lines10Cursors(b *testing.B) {
benchEdit(b, 100, 10)
}
func BenchmarkEdit1000Lines1Cursor(b *testing.B) {
benchEdit(b, 1000, 1)
}
func BenchmarkEdit1000Lines10Cursors(b *testing.B) {
benchEdit(b, 1000, 10)
}
func BenchmarkEdit1000Lines100Cursors(b *testing.B) {
benchEdit(b, 1000, 100)
}
func BenchmarkEdit10000Lines1Cursor(b *testing.B) {
benchEdit(b, 10000, 1)
}
func BenchmarkEdit10000Lines10Cursors(b *testing.B) {
benchEdit(b, 10000, 10)
}
func BenchmarkEdit10000Lines100Cursors(b *testing.B) {
benchEdit(b, 10000, 100)
}
func BenchmarkEdit10000Lines1000Cursors(b *testing.B) {
benchEdit(b, 10000, 1000)
}
func BenchmarkEdit100000Lines1Cursor(b *testing.B) {
benchEdit(b, 100000, 1)
}
func BenchmarkEdit100000Lines10Cursors(b *testing.B) {
benchEdit(b, 100000, 10)
}
func BenchmarkEdit100000Lines100Cursors(b *testing.B) {
benchEdit(b, 100000, 100)
}
func BenchmarkEdit100000Lines1000Cursors(b *testing.B) {
benchEdit(b, 100000, 1000)
}
func BenchmarkEdit1000000Lines1Cursor(b *testing.B) {
benchEdit(b, 1000000, 1)
}
func BenchmarkEdit1000000Lines10Cursors(b *testing.B) {
benchEdit(b, 1000000, 10)
}
func BenchmarkEdit1000000Lines100Cursors(b *testing.B) {
benchEdit(b, 1000000, 100)
}
func BenchmarkEdit1000000Lines1000Cursors(b *testing.B) {
benchEdit(b, 1000000, 1000)
}
```
|
/content/code_sandbox/internal/buffer/buffer_test.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 2,002
|
```go
package buffer
import (
"strings"
"testing"
"github.com/stretchr/testify/assert"
)
var unicode_txt = `An preost wes on leoden, Laamon was ihoten
He wes Leovenaes sone -- lie him be Drihten.
He wonede at Ernlee at elen are chirechen,
Uppen Sevarne stae, sel ar him uhte,
Onfest Radestone, er he bock radde.`
var la *LineArray
func init() {
reader := strings.NewReader(unicode_txt)
la = NewLineArray(uint64(len(unicode_txt)), FFAuto, reader)
}
func TestSplit(t *testing.T) {
la.insert(Loc{17, 1}, []byte{'\n'})
assert.Equal(t, len(la.lines), 6)
sub1 := la.Substr(Loc{0, 1}, Loc{17, 1})
sub2 := la.Substr(Loc{0, 2}, Loc{30, 2})
assert.Equal(t, []byte("He wes Leovenaes"), sub1)
assert.Equal(t, []byte(" sone -- lie him be Drihten."), sub2)
}
func TestJoin(t *testing.T) {
la.remove(Loc{47, 1}, Loc{0, 2})
assert.Equal(t, len(la.lines), 5)
sub := la.Substr(Loc{0, 1}, Loc{47, 1})
bytes := la.Bytes()
assert.Equal(t, []byte("He wes Leovenaes sone -- lie him be Drihten."), sub)
assert.Equal(t, unicode_txt, string(bytes))
}
func TestInsert(t *testing.T) {
la.insert(Loc{20, 3}, []byte(" foobar"))
sub1 := la.Substr(Loc{0, 3}, Loc{50, 3})
assert.Equal(t, []byte("Uppen Sevarne stae, foobar sel ar him uhte,"), sub1)
la.insert(Loc{25, 2}, []byte("Helo"))
sub2 := la.Substr(Loc{0, 2}, Loc{60, 2})
assert.Equal(t, []byte("He wonede at Ernlee at Heloelen are chirechen,"), sub2)
}
func TestRemove(t *testing.T) {
la.remove(Loc{20, 3}, Loc{27, 3})
la.remove(Loc{25, 2}, Loc{30, 2})
bytes := la.Bytes()
assert.Equal(t, unicode_txt, string(bytes))
}
```
|
/content/code_sandbox/internal/buffer/line_array_test.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 560
|
```go
package buffer
import (
"github.com/zyedidia/micro/v2/internal/util"
)
// Loc stores a location
type Loc struct {
X, Y int
}
// LessThan returns true if b is smaller
func (l Loc) LessThan(b Loc) bool {
if l.Y < b.Y {
return true
}
return l.Y == b.Y && l.X < b.X
}
// GreaterThan returns true if b is bigger
func (l Loc) GreaterThan(b Loc) bool {
if l.Y > b.Y {
return true
}
return l.Y == b.Y && l.X > b.X
}
// GreaterEqual returns true if b is greater than or equal to b
func (l Loc) GreaterEqual(b Loc) bool {
if l.Y > b.Y {
return true
}
if l.Y == b.Y && l.X > b.X {
return true
}
return l == b
}
// LessEqual returns true if b is less than or equal to b
func (l Loc) LessEqual(b Loc) bool {
if l.Y < b.Y {
return true
}
if l.Y == b.Y && l.X < b.X {
return true
}
return l == b
}
// The following functions require a buffer to know where newlines are
// Diff returns the distance between two locations
func DiffLA(a, b Loc, buf *LineArray) int {
if a.Y == b.Y {
if a.X > b.X {
return a.X - b.X
}
return b.X - a.X
}
// Make sure a is guaranteed to be less than b
if b.LessThan(a) {
a, b = b, a
}
loc := 0
for i := a.Y + 1; i < b.Y; i++ {
// + 1 for the newline
loc += util.CharacterCount(buf.LineBytes(i)) + 1
}
loc += util.CharacterCount(buf.LineBytes(a.Y)) - a.X + b.X + 1
return loc
}
// This moves the location one character to the right
func (l Loc) right(buf *LineArray) Loc {
if l == buf.End() {
return Loc{l.X + 1, l.Y}
}
var res Loc
if l.X < util.CharacterCount(buf.LineBytes(l.Y)) {
res = Loc{l.X + 1, l.Y}
} else {
res = Loc{0, l.Y + 1}
}
return res
}
// This moves the given location one character to the left
func (l Loc) left(buf *LineArray) Loc {
if l == buf.Start() {
return Loc{l.X - 1, l.Y}
}
var res Loc
if l.X > 0 {
res = Loc{l.X - 1, l.Y}
} else {
res = Loc{util.CharacterCount(buf.LineBytes(l.Y - 1)), l.Y - 1}
}
return res
}
// MoveLA moves the cursor n characters to the left or right
// It moves the cursor left if n is negative
func (l Loc) MoveLA(n int, buf *LineArray) Loc {
if n > 0 {
for i := 0; i < n; i++ {
l = l.right(buf)
}
return l
}
for i := 0; i < util.Abs(n); i++ {
l = l.left(buf)
}
return l
}
// Diff returns the difference between two locs
func (l Loc) Diff(b Loc, buf *Buffer) int {
return DiffLA(l, b, buf.LineArray)
}
// Move moves a loc n characters
func (l Loc) Move(n int, buf *Buffer) Loc {
return l.MoveLA(n, buf.LineArray)
}
// ByteOffset is just like ToCharPos except it counts bytes instead of runes
func ByteOffset(pos Loc, buf *Buffer) int {
x, y := pos.X, pos.Y
loc := 0
for i := 0; i < y; i++ {
// + 1 for the newline
loc += len(buf.Line(i)) + 1
}
loc += len(buf.Line(y)[:x])
return loc
}
// clamps a loc within a buffer
func clamp(pos Loc, la *LineArray) Loc {
if pos.GreaterEqual(la.End()) {
return la.End()
} else if pos.LessThan(la.Start()) {
return la.Start()
}
return pos
}
```
|
/content/code_sandbox/internal/buffer/loc.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 978
|
```go
package buffer
// TEStack is a simple implementation of a LIFO stack for text events
type TEStack struct {
Top *Element
Size int
}
// An Element which is stored in the Stack
type Element struct {
Value *TextEvent
Next *Element
}
// Len returns the stack's length
func (s *TEStack) Len() int {
return s.Size
}
// Push a new element onto the stack
func (s *TEStack) Push(value *TextEvent) {
s.Top = &Element{value, s.Top}
s.Size++
}
// Pop removes the top element from the stack and returns its value
// If the stack is empty, return nil
func (s *TEStack) Pop() (value *TextEvent) {
if s.Size > 0 {
value, s.Top = s.Top.Value, s.Top.Next
s.Size--
return
}
return nil
}
// Peek returns the top element of the stack without removing it
func (s *TEStack) Peek() *TextEvent {
if s.Size > 0 {
return s.Top.Value
}
return nil
}
```
|
/content/code_sandbox/internal/buffer/stack.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 242
|
```go
package buffer
import (
"github.com/zyedidia/micro/v2/internal/clipboard"
"github.com/zyedidia/micro/v2/internal/util"
)
// InBounds returns whether the given location is a valid character position in the given buffer
func InBounds(pos Loc, buf *Buffer) bool {
if pos.Y < 0 || pos.Y >= len(buf.lines) || pos.X < 0 || pos.X > util.CharacterCount(buf.LineBytes(pos.Y)) {
return false
}
return true
}
// The Cursor struct stores the location of the cursor in the buffer
// as well as the selection
type Cursor struct {
buf *Buffer
Loc
// Last cursor x position
LastVisualX int
// The current selection as a range of character numbers (inclusive)
CurSelection [2]Loc
// The original selection as a range of character numbers
// This is used for line and word selection where it is necessary
// to know what the original selection was
OrigSelection [2]Loc
// The line number where a new trailing whitespace has been added
// or -1 if there is no new trailing whitespace at this cursor.
// This is used for checking if a trailing whitespace should be highlighted
NewTrailingWsY int
// Which cursor index is this (for multiple cursors)
Num int
}
func NewCursor(b *Buffer, l Loc) *Cursor {
c := &Cursor{
buf: b,
Loc: l,
NewTrailingWsY: -1,
}
c.StoreVisualX()
return c
}
func (c *Cursor) SetBuf(b *Buffer) {
c.buf = b
}
func (c *Cursor) Buf() *Buffer {
return c.buf
}
// Goto puts the cursor at the given cursor's location and gives
// the current cursor its selection too
func (c *Cursor) Goto(b Cursor) {
c.X, c.Y, c.LastVisualX = b.X, b.Y, b.LastVisualX
c.OrigSelection, c.CurSelection = b.OrigSelection, b.CurSelection
}
// GotoLoc puts the cursor at the given cursor's location and gives
// the current cursor its selection too
func (c *Cursor) GotoLoc(l Loc) {
c.X, c.Y = l.X, l.Y
c.StoreVisualX()
}
// GetVisualX returns the x value of the cursor in visual spaces
func (c *Cursor) GetVisualX() int {
if c.buf.GetVisualX != nil {
return c.buf.GetVisualX(c.Loc)
}
if c.X <= 0 {
c.X = 0
return 0
}
bytes := c.buf.LineBytes(c.Y)
tabsize := int(c.buf.Settings["tabsize"].(float64))
return util.StringWidth(bytes, c.X, tabsize)
}
// 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(b []byte, visualPos int) int {
tabsize := int(c.buf.Settings["tabsize"].(float64))
return util.GetCharPosInLine(b, visualPos, tabsize)
}
// Start moves the cursor to the start of the line it is on
func (c *Cursor) Start() {
c.X = 0
c.LastVisualX = c.GetVisualX()
}
// StartOfText moves the cursor to the first non-whitespace rune of
// the line it is on
func (c *Cursor) StartOfText() {
c.Start()
for util.IsWhitespace(c.RuneUnder(c.X)) {
if c.X == util.CharacterCount(c.buf.LineBytes(c.Y)) {
break
}
c.Right()
}
}
// IsStartOfText returns whether the cursor is at the first
// non-whitespace rune of the line it is on
func (c *Cursor) IsStartOfText() bool {
x := 0
for util.IsWhitespace(c.RuneUnder(x)) {
if x == util.CharacterCount(c.buf.LineBytes(c.Y)) {
break
}
x++
}
return c.X == x
}
// End moves the cursor to the end of the line it is on
func (c *Cursor) End() {
c.X = util.CharacterCount(c.buf.LineBytes(c.Y))
c.LastVisualX = c.GetVisualX()
}
// CopySelection copies the user's selection to either "primary"
// or "clipboard"
func (c *Cursor) CopySelection(target clipboard.Register) {
if c.HasSelection() {
if target != clipboard.PrimaryReg || c.buf.Settings["useprimary"].(bool) {
clipboard.WriteMulti(string(c.GetSelection()), target, c.Num, c.buf.NumCursors())
}
}
}
// ResetSelection resets the user's selection
func (c *Cursor) ResetSelection() {
c.CurSelection[0] = c.buf.Start()
c.CurSelection[1] = c.buf.Start()
}
// SetSelectionStart sets the start of the selection
func (c *Cursor) SetSelectionStart(pos Loc) {
c.CurSelection[0] = pos
}
// SetSelectionEnd sets the end of the selection
func (c *Cursor) SetSelectionEnd(pos Loc) {
c.CurSelection[1] = pos
}
// HasSelection returns whether or not the user has selected anything
func (c *Cursor) HasSelection() bool {
return c.CurSelection[0] != c.CurSelection[1]
}
// DeleteSelection deletes the currently selected text
func (c *Cursor) DeleteSelection() {
if c.CurSelection[0].GreaterThan(c.CurSelection[1]) {
c.buf.Remove(c.CurSelection[1], c.CurSelection[0])
c.Loc = c.CurSelection[1]
} else if !c.HasSelection() {
return
} else {
c.buf.Remove(c.CurSelection[0], c.CurSelection[1])
c.Loc = c.CurSelection[0]
}
}
// Deselect closes the cursor's current selection
// Start indicates whether the cursor should be placed
// at the start or end of the selection
func (c *Cursor) Deselect(start bool) {
if c.HasSelection() {
if start {
c.Loc = c.CurSelection[0]
} else {
c.Loc = c.CurSelection[1].Move(-1, c.buf)
}
c.ResetSelection()
c.StoreVisualX()
}
}
// GetSelection returns the cursor's selection
func (c *Cursor) GetSelection() []byte {
if InBounds(c.CurSelection[0], c.buf) && InBounds(c.CurSelection[1], c.buf) {
if c.CurSelection[0].GreaterThan(c.CurSelection[1]) {
return c.buf.Substr(c.CurSelection[1], c.CurSelection[0])
}
return c.buf.Substr(c.CurSelection[0], c.CurSelection[1])
}
return []byte{}
}
// SelectLine selects the current line
func (c *Cursor) SelectLine() {
c.Start()
c.SetSelectionStart(c.Loc)
c.End()
if len(c.buf.lines)-1 > c.Y {
c.SetSelectionEnd(c.Loc.Move(1, c.buf))
} else {
c.SetSelectionEnd(c.Loc)
}
c.OrigSelection = c.CurSelection
}
// AddLineToSelection adds the current line to the selection
func (c *Cursor) AddLineToSelection() {
if c.Loc.LessThan(c.OrigSelection[0]) {
c.Start()
c.SetSelectionStart(c.Loc)
c.SetSelectionEnd(c.OrigSelection[1])
}
if c.Loc.GreaterThan(c.OrigSelection[1]) {
c.End()
c.SetSelectionEnd(c.Loc.Move(1, c.buf))
c.SetSelectionStart(c.OrigSelection[0])
}
if c.Loc.LessThan(c.OrigSelection[1]) && c.Loc.GreaterThan(c.OrigSelection[0]) {
c.CurSelection = c.OrigSelection
}
}
// UpN moves the cursor up N lines (if possible)
func (c *Cursor) UpN(amount int) {
proposedY := c.Y - amount
if proposedY < 0 {
proposedY = 0
} else if proposedY >= len(c.buf.lines) {
proposedY = len(c.buf.lines) - 1
}
bytes := c.buf.LineBytes(proposedY)
c.X = c.GetCharPosInLine(bytes, c.LastVisualX)
if c.X > util.CharacterCount(bytes) || (amount < 0 && proposedY == c.Y) {
c.X = util.CharacterCount(bytes)
c.StoreVisualX()
}
if c.X < 0 || (amount > 0 && proposedY == c.Y) {
c.X = 0
c.StoreVisualX()
}
c.Y = proposedY
}
// DownN moves the cursor down N lines (if possible)
func (c *Cursor) DownN(amount int) {
c.UpN(-amount)
}
// Up moves the cursor up one line (if possible)
func (c *Cursor) Up() {
c.UpN(1)
}
// Down moves the cursor down one line (if possible)
func (c *Cursor) Down() {
c.DownN(1)
}
// Left moves the cursor left one cell (if possible) or to
// the previous line if it is at the beginning
func (c *Cursor) Left() {
if c.Loc == c.buf.Start() {
return
}
if c.X > 0 {
c.X--
} else {
c.Up()
c.End()
}
c.StoreVisualX()
}
// Right moves the cursor right one cell (if possible) or
// to the next line if it is at the end
func (c *Cursor) Right() {
if c.Loc == c.buf.End() {
return
}
if c.X < util.CharacterCount(c.buf.LineBytes(c.Y)) {
c.X++
} else {
c.Down()
c.Start()
}
c.StoreVisualX()
}
// Relocate makes sure that the cursor is inside the bounds
// of the buffer If it isn't, it moves it to be within the
// buffer's lines
func (c *Cursor) Relocate() {
if c.Y < 0 {
c.Y = 0
} else if c.Y >= len(c.buf.lines) {
c.Y = len(c.buf.lines) - 1
}
if c.X < 0 {
c.X = 0
} else if c.X > util.CharacterCount(c.buf.LineBytes(c.Y)) {
c.X = util.CharacterCount(c.buf.LineBytes(c.Y))
}
}
// SelectWord selects the word the cursor is currently on
func (c *Cursor) SelectWord() {
if len(c.buf.LineBytes(c.Y)) == 0 {
return
}
if !util.IsWordChar(c.RuneUnder(c.X)) {
c.SetSelectionStart(c.Loc)
c.SetSelectionEnd(c.Loc.Move(1, c.buf))
c.OrigSelection = c.CurSelection
return
}
forward, backward := c.X, c.X
for backward > 0 && util.IsWordChar(c.RuneUnder(backward-1)) {
backward--
}
c.SetSelectionStart(Loc{backward, c.Y})
c.OrigSelection[0] = c.CurSelection[0]
lineLen := util.CharacterCount(c.buf.LineBytes(c.Y)) - 1
for forward < lineLen && util.IsWordChar(c.RuneUnder(forward+1)) {
forward++
}
c.SetSelectionEnd(Loc{forward, c.Y}.Move(1, c.buf))
c.OrigSelection[1] = c.CurSelection[1]
c.Loc = c.CurSelection[1]
}
// AddWordToSelection adds the word the cursor is currently on
// to the selection
func (c *Cursor) AddWordToSelection() {
if c.Loc.GreaterThan(c.OrigSelection[0]) && c.Loc.LessThan(c.OrigSelection[1]) {
c.CurSelection = c.OrigSelection
return
}
if c.Loc.LessThan(c.OrigSelection[0]) {
backward := c.X
for backward > 0 && util.IsWordChar(c.RuneUnder(backward-1)) {
backward--
}
c.SetSelectionStart(Loc{backward, c.Y})
c.SetSelectionEnd(c.OrigSelection[1])
}
if c.Loc.GreaterThan(c.OrigSelection[1]) {
forward := c.X
lineLen := util.CharacterCount(c.buf.LineBytes(c.Y)) - 1
for forward < lineLen && util.IsWordChar(c.RuneUnder(forward+1)) {
forward++
}
c.SetSelectionEnd(Loc{forward, c.Y}.Move(1, c.buf))
c.SetSelectionStart(c.OrigSelection[0])
}
c.Loc = c.CurSelection[1]
}
// SelectTo selects from the current cursor location to the given
// location
func (c *Cursor) SelectTo(loc Loc) {
if loc.GreaterThan(c.OrigSelection[0]) {
c.SetSelectionStart(c.OrigSelection[0])
c.SetSelectionEnd(loc)
} else {
c.SetSelectionStart(loc)
c.SetSelectionEnd(c.OrigSelection[0])
}
}
// WordRight moves the cursor one word to the right
func (c *Cursor) WordRight() {
if c.X == util.CharacterCount(c.buf.LineBytes(c.Y)) {
c.Right()
return
}
for util.IsWhitespace(c.RuneUnder(c.X)) {
if c.X == util.CharacterCount(c.buf.LineBytes(c.Y)) {
return
}
c.Right()
}
if util.IsNonWordChar(c.RuneUnder(c.X)) && !util.IsWhitespace(c.RuneUnder(c.X)) &&
util.IsNonWordChar(c.RuneUnder(c.X+1)) {
for util.IsNonWordChar(c.RuneUnder(c.X)) && !util.IsWhitespace(c.RuneUnder(c.X)) {
if c.X == util.CharacterCount(c.buf.LineBytes(c.Y)) {
return
}
c.Right()
}
return
}
c.Right()
for util.IsWordChar(c.RuneUnder(c.X)) {
if c.X == util.CharacterCount(c.buf.LineBytes(c.Y)) {
return
}
c.Right()
}
}
// WordLeft moves the cursor one word to the left
func (c *Cursor) WordLeft() {
if c.X == 0 {
c.Left()
return
}
c.Left()
for util.IsWhitespace(c.RuneUnder(c.X)) {
if c.X == 0 {
return
}
c.Left()
}
if util.IsNonWordChar(c.RuneUnder(c.X)) && !util.IsWhitespace(c.RuneUnder(c.X)) &&
util.IsNonWordChar(c.RuneUnder(c.X-1)) {
for util.IsNonWordChar(c.RuneUnder(c.X)) && !util.IsWhitespace(c.RuneUnder(c.X)) {
if c.X == 0 {
return
}
c.Left()
}
c.Right()
return
}
c.Left()
for util.IsWordChar(c.RuneUnder(c.X)) {
if c.X == 0 {
return
}
c.Left()
}
c.Right()
}
// SubWordRight moves the cursor one sub-word to the right
func (c *Cursor) SubWordRight() {
if c.X == util.CharacterCount(c.buf.LineBytes(c.Y)) {
c.Right()
return
}
if util.IsWhitespace(c.RuneUnder(c.X)) {
for util.IsWhitespace(c.RuneUnder(c.X)) {
if c.X == util.CharacterCount(c.buf.LineBytes(c.Y)) {
return
}
c.Right()
}
return
}
if util.IsNonWordChar(c.RuneUnder(c.X)) && !util.IsWhitespace(c.RuneUnder(c.X)) {
for util.IsNonWordChar(c.RuneUnder(c.X)) && !util.IsWhitespace(c.RuneUnder(c.X)) {
if c.X == util.CharacterCount(c.buf.LineBytes(c.Y)) {
return
}
c.Right()
}
return
}
if util.IsSubwordDelimiter(c.RuneUnder(c.X)) {
for util.IsSubwordDelimiter(c.RuneUnder(c.X)) {
if c.X == util.CharacterCount(c.buf.LineBytes(c.Y)) {
return
}
c.Right()
}
if util.IsWhitespace(c.RuneUnder(c.X)) {
return
}
}
if c.X == util.CharacterCount(c.buf.LineBytes(c.Y)) {
return
}
if util.IsUpperLetter(c.RuneUnder(c.X)) &&
util.IsUpperLetter(c.RuneUnder(c.X+1)) {
for util.IsUpperAlphanumeric(c.RuneUnder(c.X)) {
if c.X == util.CharacterCount(c.buf.LineBytes(c.Y)) {
return
}
c.Right()
}
if util.IsLowerAlphanumeric(c.RuneUnder(c.X)) {
c.Left()
}
} else {
c.Right()
for util.IsLowerAlphanumeric(c.RuneUnder(c.X)) {
if c.X == util.CharacterCount(c.buf.LineBytes(c.Y)) {
return
}
c.Right()
}
}
}
// SubWordLeft moves the cursor one sub-word to the left
func (c *Cursor) SubWordLeft() {
if c.X == 0 {
c.Left()
return
}
c.Left()
if util.IsWhitespace(c.RuneUnder(c.X)) {
for util.IsWhitespace(c.RuneUnder(c.X)) {
if c.X == 0 {
return
}
c.Left()
}
c.Right()
return
}
if util.IsNonWordChar(c.RuneUnder(c.X)) && !util.IsWhitespace(c.RuneUnder(c.X)) {
for util.IsNonWordChar(c.RuneUnder(c.X)) && !util.IsWhitespace(c.RuneUnder(c.X)) {
if c.X == 0 {
return
}
c.Left()
}
c.Right()
return
}
if util.IsSubwordDelimiter(c.RuneUnder(c.X)) {
for util.IsSubwordDelimiter(c.RuneUnder(c.X)) {
if c.X == 0 {
return
}
c.Left()
}
if util.IsWhitespace(c.RuneUnder(c.X)) {
c.Right()
return
}
}
if c.X == 0 {
return
}
if util.IsUpperLetter(c.RuneUnder(c.X)) &&
util.IsUpperLetter(c.RuneUnder(c.X-1)) {
for util.IsUpperAlphanumeric(c.RuneUnder(c.X)) {
if c.X == 0 {
return
}
c.Left()
}
if !util.IsUpperAlphanumeric(c.RuneUnder(c.X)) {
c.Right()
}
} else {
for util.IsLowerAlphanumeric(c.RuneUnder(c.X)) {
if c.X == 0 {
return
}
c.Left()
}
if !util.IsAlphanumeric(c.RuneUnder(c.X)) {
c.Right()
}
}
}
// RuneUnder returns the rune under the given x position
func (c *Cursor) RuneUnder(x int) rune {
line := c.buf.LineBytes(c.Y)
if len(line) == 0 || x >= util.CharacterCount(line) {
return '\n'
} else if x < 0 {
x = 0
}
i := 0
for len(line) > 0 {
r, _, size := util.DecodeCharacter(line)
line = line[size:]
if i == x {
return r
}
i++
}
return '\n'
}
func (c *Cursor) StoreVisualX() {
c.LastVisualX = c.GetVisualX()
}
```
|
/content/code_sandbox/internal/buffer/cursor.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 4,416
|
```go
package buffer
import (
"bufio"
"bytes"
"errors"
"io"
"os"
"os/exec"
"os/signal"
"path/filepath"
"runtime"
"unicode"
"github.com/zyedidia/micro/v2/internal/config"
"github.com/zyedidia/micro/v2/internal/screen"
"github.com/zyedidia/micro/v2/internal/util"
"golang.org/x/text/encoding"
"golang.org/x/text/encoding/htmlindex"
"golang.org/x/text/transform"
)
// LargeFileThreshold is the number of bytes when fastdirty is forced
// because hashing is too slow
const LargeFileThreshold = 50000
// overwriteFile opens the given file for writing, truncating if one exists, and then calls
// the supplied function with the file as io.Writer object, also making sure the file is
// closed afterwards.
func overwriteFile(name string, enc encoding.Encoding, fn func(io.Writer) error, withSudo bool) (err error) {
var writeCloser io.WriteCloser
var screenb bool
var cmd *exec.Cmd
if withSudo {
cmd = exec.Command(config.GlobalSettings["sucmd"].(string), "dd", "bs=4k", "of="+name)
if writeCloser, err = cmd.StdinPipe(); err != nil {
return
}
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func() {
<-c
cmd.Process.Kill()
}()
screenb = screen.TempFini()
// need to start the process now, otherwise when we flush the file
// contents to its stdin it might hang because the kernel's pipe size
// is too small to handle the full file contents all at once
if e := cmd.Start(); e != nil && err == nil {
screen.TempStart(screenb)
return err
}
} else if writeCloser, err = os.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666); err != nil {
return
}
w := bufio.NewWriter(transform.NewWriter(writeCloser, enc.NewEncoder()))
err = fn(w)
if err2 := w.Flush(); err2 != nil && err == nil {
err = err2
}
// Call Sync() on the file to make sure the content is safely on disk.
// Does not work with sudo as we don't have direct access to the file.
if !withSudo {
f := writeCloser.(*os.File)
if err2 := f.Sync(); err2 != nil && err == nil {
err = err2
}
}
if err2 := writeCloser.Close(); err2 != nil && err == nil {
err = err2
}
if withSudo {
// wait for dd to finish and restart the screen if we used sudo
err := cmd.Wait()
screen.TempStart(screenb)
if err != nil {
return err
}
}
return
}
// Save saves the buffer to its default path
func (b *Buffer) Save() error {
return b.SaveAs(b.Path)
}
// AutoSave saves the buffer to its default path
func (b *Buffer) AutoSave() error {
// Doing full b.Modified() check every time would be costly, due to the hash
// calculation. So use just isModified even if fastdirty is not set.
if !b.isModified {
return nil
}
return b.saveToFile(b.Path, false, true)
}
// SaveAs saves the buffer to a specified path (filename), creating the file if it does not exist
func (b *Buffer) SaveAs(filename string) error {
return b.saveToFile(filename, false, false)
}
func (b *Buffer) SaveWithSudo() error {
return b.SaveAsWithSudo(b.Path)
}
func (b *Buffer) SaveAsWithSudo(filename string) error {
return b.saveToFile(filename, true, false)
}
func (b *Buffer) saveToFile(filename string, withSudo bool, autoSave bool) error {
var err error
if b.Type.Readonly {
return errors.New("Cannot save readonly buffer")
}
if b.Type.Scratch {
return errors.New("Cannot save scratch buffer")
}
if withSudo && runtime.GOOS == "windows" {
return errors.New("Save with sudo not supported on Windows")
}
if !autoSave && b.Settings["rmtrailingws"].(bool) {
for i, l := range b.lines {
leftover := util.CharacterCount(bytes.TrimRightFunc(l.data, unicode.IsSpace))
linelen := util.CharacterCount(l.data)
b.Remove(Loc{leftover, i}, Loc{linelen, i})
}
b.RelocateCursors()
}
if b.Settings["eofnewline"].(bool) {
end := b.End()
if b.RuneAt(Loc{end.X - 1, end.Y}) != '\n' {
b.insert(end, []byte{'\n'})
}
}
// Update the last time this file was updated after saving
defer func() {
b.ModTime, _ = util.GetModTime(filename)
err = b.Serialize()
}()
// Removes any tilde and replaces with the absolute path to home
absFilename, _ := util.ReplaceHome(filename)
// Get the leading path to the file | "." is returned if there's no leading path provided
if dirname := filepath.Dir(absFilename); dirname != "." {
// Check if the parent dirs don't exist
if _, statErr := os.Stat(dirname); os.IsNotExist(statErr) {
// Prompt to make sure they want to create the dirs that are missing
if b.Settings["mkparents"].(bool) {
// Create all leading dir(s) since they don't exist
if mkdirallErr := os.MkdirAll(dirname, os.ModePerm); mkdirallErr != nil {
// If there was an error creating the dirs
return mkdirallErr
}
} else {
return errors.New("Parent dirs don't exist, enable 'mkparents' for auto creation")
}
}
}
var fileSize int
enc, err := htmlindex.Get(b.Settings["encoding"].(string))
if err != nil {
return err
}
fwriter := func(file io.Writer) (e error) {
if len(b.lines) == 0 {
return
}
// end of line
var eol []byte
if b.Endings == FFDos {
eol = []byte{'\r', '\n'}
} else {
eol = []byte{'\n'}
}
// write lines
if fileSize, e = file.Write(b.lines[0].data); e != nil {
return
}
for _, l := range b.lines[1:] {
if _, e = file.Write(eol); e != nil {
return
}
if _, e = file.Write(l.data); e != nil {
return
}
fileSize += len(eol) + len(l.data)
}
return
}
if err = overwriteFile(absFilename, enc, fwriter, withSudo); err != nil {
return err
}
if !b.Settings["fastdirty"].(bool) {
if fileSize > LargeFileThreshold {
// For large files 'fastdirty' needs to be on
b.Settings["fastdirty"] = true
} else {
calcHash(b, &b.origHash)
}
}
b.Path = filename
absPath, _ := filepath.Abs(filename)
b.AbsPath = absPath
b.isModified = false
b.UpdateRules()
return err
}
```
|
/content/code_sandbox/internal/buffer/save.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 1,692
|
```go
// This file is generated from VSCode model tests by the testgen tool.
// DO NOT EDIT THIS FILE BY HAND; your changes will be overwritten!
package buffer
import "testing"
func TestAuto1(t *testing.T) {
check(
t,
[]string{
"ioe",
"",
"yjct",
"",
"",
},
[]operation{
{
start: Loc{1, 0},
end: Loc{1, 0},
text: []string{
"b",
"r",
"fq",
},
},
{
start: Loc{3, 0},
end: Loc{0, 1},
text: []string{
"",
"",
},
},
},
[]string{
"ib",
"r",
"fqoe",
"",
"yjct",
"",
"",
},
)
}
func TestAuto2(t *testing.T) {
check(
t,
[]string{
"f",
"littnhskrq",
"utxvsizqnk",
"lslqz",
"jxn",
"gmm",
},
[]operation{
{
start: Loc{1, 0},
end: Loc{1, 0},
text: []string{
"",
"o",
},
},
{
start: Loc{3, 1},
end: Loc{3, 1},
text: []string{
"zaq",
"avb",
},
},
{
start: Loc{4, 1},
end: Loc{1, 5},
text: []string{
"jlr",
"zl",
"j",
},
},
},
[]string{
"f",
"o",
"litzaq",
"avbtjlr",
"zl",
"jmm",
},
)
}
func TestAuto3(t *testing.T) {
check(
t,
[]string{
"ofw",
"qsxmziuvzw",
"rp",
"qsnymek",
"elth",
"wmgzbwudxz",
"iwsdkndh",
"bujlbwb",
"asuouxfv",
"xuccnb",
},
[]operation{
{
start: Loc{2, 3},
end: Loc{2, 3},
text: []string{
"",
},
},
},
[]string{
"ofw",
"qsxmziuvzw",
"rp",
"qsnymek",
"elth",
"wmgzbwudxz",
"iwsdkndh",
"bujlbwb",
"asuouxfv",
"xuccnb",
},
)
}
func TestAuto4(t *testing.T) {
check(
t,
[]string{
"fefymj",
"qum",
"vmiwxxaiqq",
"dz",
"lnqdgorosf",
},
[]operation{
{
start: Loc{2, 0},
end: Loc{4, 0},
text: []string{
"hp",
},
},
{
start: Loc{6, 0},
end: Loc{0, 1},
text: []string{
"kcg",
"",
"mpx",
},
},
{
start: Loc{1, 1},
end: Loc{1, 1},
text: []string{
"",
"aw",
"",
},
},
{
start: Loc{1, 1},
end: Loc{1, 1},
text: []string{
"vqr",
"mo",
},
},
{
start: Loc{1, 3},
end: Loc{2, 4},
text: []string{
"xyc",
},
},
},
[]string{
"fehpmjkcg",
"",
"mpxq",
"aw",
"vqr",
"moum",
"vmiwxxaiqq",
"dxycqdgorosf",
},
)
}
func TestBug19872UndoIsFunky(t *testing.T) {
check(
t,
[]string{
"something",
" A",
"",
" B",
"something else",
},
[]operation{
{
start: Loc{0, 1},
end: Loc{1, 1},
text: []string{
"",
},
},
{
start: Loc{0, 2},
end: Loc{1, 3},
text: []string{
"",
},
},
},
[]string{
"something",
"A",
"B",
"something else",
},
)
}
func TestBug19872UndoIsFunky_2(t *testing.T) {
check(
t,
[]string{
"something",
"A",
"B",
"something else",
},
[]operation{
{
start: Loc{0, 1},
end: Loc{0, 1},
text: []string{
" ",
},
},
{
start: Loc{0, 2},
end: Loc{0, 2},
text: []string{
"",
" ",
},
},
},
[]string{
"something",
" A",
"",
" B",
"something else",
},
)
}
func TestInsertEmptyText(t *testing.T) {
check(
t,
[]string{
"My First Line",
"\t\tMy Second Line",
" Third Line",
"",
"1",
},
[]operation{
{
start: Loc{0, 0},
end: Loc{0, 0},
text: []string{
"",
},
},
},
[]string{
"My First Line",
"\t\tMy Second Line",
" Third Line",
"",
"1",
},
)
}
func TestLastOpIsNoOp(t *testing.T) {
check(
t,
[]string{
"My First Line",
"\t\tMy Second Line",
" Third Line",
"",
"1",
},
[]operation{
{
start: Loc{0, 0},
end: Loc{1, 0},
text: []string{
"",
},
},
{
start: Loc{0, 3},
end: Loc{0, 3},
text: []string{
"",
},
},
},
[]string{
"y First Line",
"\t\tMy Second Line",
" Third Line",
"",
"1",
},
)
}
func TestInsertTextWithoutNewline1(t *testing.T) {
check(
t,
[]string{
"My First Line",
"\t\tMy Second Line",
" Third Line",
"",
"1",
},
[]operation{
{
start: Loc{0, 0},
end: Loc{0, 0},
text: []string{
"foo ",
},
},
},
[]string{
"foo My First Line",
"\t\tMy Second Line",
" Third Line",
"",
"1",
},
)
}
func TestInsertTextWithoutNewline2(t *testing.T) {
check(
t,
[]string{
"My First Line",
"\t\tMy Second Line",
" Third Line",
"",
"1",
},
[]operation{
{
start: Loc{2, 0},
end: Loc{2, 0},
text: []string{
" foo",
},
},
},
[]string{
"My foo First Line",
"\t\tMy Second Line",
" Third Line",
"",
"1",
},
)
}
func TestInsertOneNewline(t *testing.T) {
check(
t,
[]string{
"My First Line",
"\t\tMy Second Line",
" Third Line",
"",
"1",
},
[]operation{
{
start: Loc{3, 0},
end: Loc{3, 0},
text: []string{
"",
"",
},
},
},
[]string{
"My ",
"First Line",
"\t\tMy Second Line",
" Third Line",
"",
"1",
},
)
}
func TestInsertTextWithOneNewline(t *testing.T) {
check(
t,
[]string{
"My First Line",
"\t\tMy Second Line",
" Third Line",
"",
"1",
},
[]operation{
{
start: Loc{2, 0},
end: Loc{2, 0},
text: []string{
" new line",
"No longer",
},
},
},
[]string{
"My new line",
"No longer First Line",
"\t\tMy Second Line",
" Third Line",
"",
"1",
},
)
}
func TestInsertTextWithTwoNewlines(t *testing.T) {
check(
t,
[]string{
"My First Line",
"\t\tMy Second Line",
" Third Line",
"",
"1",
},
[]operation{
{
start: Loc{2, 0},
end: Loc{2, 0},
text: []string{
" new line",
"One more line in the middle",
"No longer",
},
},
},
[]string{
"My new line",
"One more line in the middle",
"No longer First Line",
"\t\tMy Second Line",
" Third Line",
"",
"1",
},
)
}
func TestInsertTextWithManyNewlines(t *testing.T) {
check(
t,
[]string{
"My First Line",
"\t\tMy Second Line",
" Third Line",
"",
"1",
},
[]operation{
{
start: Loc{2, 0},
end: Loc{2, 0},
text: []string{
"",
"",
"",
"",
"",
},
},
},
[]string{
"My",
"",
"",
"",
" First Line",
"\t\tMy Second Line",
" Third Line",
"",
"1",
},
)
}
func TestInsertMultipleNewlines(t *testing.T) {
check(
t,
[]string{
"My First Line",
"\t\tMy Second Line",
" Third Line",
"",
"1",
},
[]operation{
{
start: Loc{2, 0},
end: Loc{2, 0},
text: []string{
"",
"",
"",
"",
"",
},
},
{
start: Loc{14, 2},
end: Loc{14, 2},
text: []string{
"a",
"b",
},
},
},
[]string{
"My",
"",
"",
"",
" First Line",
"\t\tMy Second Line",
" Third Linea",
"b",
"",
"1",
},
)
}
func TestDeleteEmptyText(t *testing.T) {
check(
t,
[]string{
"My First Line",
"\t\tMy Second Line",
" Third Line",
"",
"1",
},
[]operation{
{
start: Loc{0, 0},
end: Loc{0, 0},
text: []string{
"",
},
},
},
[]string{
"My First Line",
"\t\tMy Second Line",
" Third Line",
"",
"1",
},
)
}
func TestDeleteTextFromOneLine(t *testing.T) {
check(
t,
[]string{
"My First Line",
"\t\tMy Second Line",
" Third Line",
"",
"1",
},
[]operation{
{
start: Loc{0, 0},
end: Loc{1, 0},
text: []string{
"",
},
},
},
[]string{
"y First Line",
"\t\tMy Second Line",
" Third Line",
"",
"1",
},
)
}
func TestDeleteTextFromOneLine2(t *testing.T) {
check(
t,
[]string{
"My First Line",
"\t\tMy Second Line",
" Third Line",
"",
"1",
},
[]operation{
{
start: Loc{0, 0},
end: Loc{2, 0},
text: []string{
"a",
},
},
},
[]string{
"a First Line",
"\t\tMy Second Line",
" Third Line",
"",
"1",
},
)
}
func TestDeleteAllTextFromALine(t *testing.T) {
check(
t,
[]string{
"My First Line",
"\t\tMy Second Line",
" Third Line",
"",
"1",
},
[]operation{
{
start: Loc{0, 0},
end: Loc{13, 0},
text: []string{
"",
},
},
},
[]string{
"",
"\t\tMy Second Line",
" Third Line",
"",
"1",
},
)
}
func TestDeleteTextFromTwoLines(t *testing.T) {
check(
t,
[]string{
"My First Line",
"\t\tMy Second Line",
" Third Line",
"",
"1",
},
[]operation{
{
start: Loc{3, 0},
end: Loc{5, 1},
text: []string{
"",
},
},
},
[]string{
"My Second Line",
" Third Line",
"",
"1",
},
)
}
func TestDeleteTextFromManyLines(t *testing.T) {
check(
t,
[]string{
"My First Line",
"\t\tMy Second Line",
" Third Line",
"",
"1",
},
[]operation{
{
start: Loc{3, 0},
end: Loc{4, 2},
text: []string{
"",
},
},
},
[]string{
"My Third Line",
"",
"1",
},
)
}
func TestDeleteEverything(t *testing.T) {
check(
t,
[]string{
"My First Line",
"\t\tMy Second Line",
" Third Line",
"",
"1",
},
[]operation{
{
start: Loc{0, 0},
end: Loc{1, 4},
text: []string{
"",
},
},
},
[]string{
"",
},
)
}
func TestTwoUnrelatedEdits(t *testing.T) {
check(
t,
[]string{
"My First Line",
"\t\tMy Second Line",
" Third Line",
"",
"123",
},
[]operation{
{
start: Loc{0, 1},
end: Loc{2, 1},
text: []string{
"\t",
},
},
{
start: Loc{0, 2},
end: Loc{4, 2},
text: []string{
"",
},
},
},
[]string{
"My First Line",
"\tMy Second Line",
"Third Line",
"",
"123",
},
)
}
func TestTwoEditsOnOneLine(t *testing.T) {
check(
t,
[]string{
"\t\tfirst\t ",
"\t\tsecond line",
"\tthird line",
"fourth line",
"\t\t<!@#fifth#@!>\t\t",
},
[]operation{
{
start: Loc{2, 4},
end: Loc{6, 4},
text: []string{
"",
},
},
{
start: Loc{11, 4},
end: Loc{15, 4},
text: []string{
"",
},
},
},
[]string{
"\t\tfirst\t ",
"\t\tsecond line",
"\tthird line",
"fourth line",
"\t\tfifth\t\t",
},
)
}
func TestManyEdits(t *testing.T) {
check(
t,
[]string{
"{\"x\" : 1}",
},
[]operation{
{
start: Loc{1, 0},
end: Loc{1, 0},
text: []string{
"\n ",
},
},
{
start: Loc{4, 0},
end: Loc{5, 0},
text: []string{
"",
},
},
{
start: Loc{8, 0},
end: Loc{8, 0},
text: []string{
"\n",
},
},
},
[]string{
"{",
" \"x\": 1",
"}",
},
)
}
func TestManyEditsReversed(t *testing.T) {
check(
t,
[]string{
"{",
" \"x\": 1",
"}",
},
[]operation{
{
start: Loc{1, 0},
end: Loc{2, 1},
text: []string{
"",
},
},
{
start: Loc{5, 1},
end: Loc{5, 1},
text: []string{
" ",
},
},
{
start: Loc{8, 1},
end: Loc{0, 2},
text: []string{
"",
},
},
},
[]string{
"{\"x\" : 1}",
},
)
}
func TestReplacingNewlines1(t *testing.T) {
check(
t,
[]string{
"{",
"\"a\": true,",
"",
"\"b\": true",
"}",
},
[]operation{
{
start: Loc{1, 0},
end: Loc{0, 1},
text: []string{
"",
"\t",
},
},
{
start: Loc{10, 1},
end: Loc{0, 3},
text: []string{
"",
"\t",
},
},
},
[]string{
"{",
"\t\"a\": true,",
"\t\"b\": true",
"}",
},
)
}
func TestReplacingNewlines2(t *testing.T) {
check(
t,
[]string{
"some text",
"some more text",
"now comes an empty line",
"",
"after empty line",
"and the last line",
},
[]operation{
{
start: Loc{4, 0},
end: Loc{0, 2},
text: []string{
" text",
"some more text",
"some more text",
},
},
{
start: Loc{1, 2},
end: Loc{0, 3},
text: []string{
"o more lines",
"asd",
"asd",
"asd",
},
},
{
start: Loc{0, 4},
end: Loc{5, 4},
text: []string{
"zzzzzzzz",
},
},
{
start: Loc{10, 4},
end: Loc{15, 5},
text: []string{
"1",
"2",
"3",
"4",
},
},
},
[]string{
"some text",
"some more text",
"some more textno more lines",
"asd",
"asd",
"asd",
"zzzzzzzz empt1",
"2",
"3",
"4ne",
},
)
}
func TestAdvanced1(t *testing.T) {
check(
t,
[]string{
" { \"d\": [",
" null",
" ] /*comment*/",
" ,\"e\": /*comment*/ [null] }",
},
[]operation{
{
start: Loc{0, 0},
end: Loc{1, 0},
text: []string{
"",
},
},
{
start: Loc{2, 0},
end: Loc{9, 0},
text: []string{
"",
" ",
},
},
{
start: Loc{15, 0},
end: Loc{13, 1},
text: []string{
"",
" ",
},
},
{
start: Loc{17, 1},
end: Loc{8, 2},
text: []string{
"",
" ",
},
},
{
start: Loc{21, 2},
end: Loc{8, 3},
text: []string{
"",
},
},
{
start: Loc{9, 3},
end: Loc{9, 3},
text: []string{
"",
" ",
},
},
{
start: Loc{27, 3},
end: Loc{27, 3},
text: []string{
"",
" ",
},
},
{
start: Loc{31, 3},
end: Loc{31, 3},
text: []string{
"",
" ",
},
},
{
start: Loc{32, 3},
end: Loc{33, 3},
text: []string{
"",
"",
},
},
},
[]string{
"{",
" \"d\": [",
" null",
" ] /*comment*/,",
" \"e\": /*comment*/ [",
" null",
" ]",
"}",
},
)
}
func TestAdvancedSimplified(t *testing.T) {
check(
t,
[]string{
" abc",
" ,def",
},
[]operation{
{
start: Loc{0, 0},
end: Loc{3, 0},
text: []string{
"",
},
},
{
start: Loc{6, 0},
end: Loc{1, 1},
text: []string{
"",
},
},
{
start: Loc{2, 1},
end: Loc{2, 1},
text: []string{
"",
"",
},
},
},
[]string{
"abc,",
"def",
},
)
}
func TestIssue144(t *testing.T) {
check(
t,
[]string{
"package caddy",
"",
"func main() {",
"\tfmt.Println(\"Hello World! :)\")",
"}",
"",
},
[]operation{
{
start: Loc{0, 0},
end: Loc{0, 5},
text: []string{
"package caddy",
"",
"import \"fmt\"",
"",
"func main() {",
"\tfmt.Println(\"Hello World! :)\")",
"}",
"",
},
},
},
[]string{
"package caddy",
"",
"import \"fmt\"",
"",
"func main() {",
"\tfmt.Println(\"Hello World! :)\")",
"}",
"",
},
)
}
func your_sha256_hashment(t *testing.T) {
check(
t,
[]string{
"something",
"interesting",
},
[]operation{
{
start: Loc{9, 0},
end: Loc{0, 1},
text: []string{
"",
"",
},
},
},
[]string{
"something",
"interesting",
},
)
}
func TestIssue3980(t *testing.T) {
check(
t,
[]string{
"class A {",
" someProperty = false;",
" someMethod() {",
" this.someMethod();",
" }",
"}",
},
[]operation{
{
start: Loc{7, 0},
end: Loc{8, 0},
text: []string{
"",
"",
},
},
{
start: Loc{16, 2},
end: Loc{17, 2},
text: []string{
"",
"",
},
},
{
start: Loc{17, 2},
end: Loc{17, 2},
text: []string{
" ",
},
},
{
start: Loc{4, 3},
end: Loc{4, 3},
text: []string{
" ",
},
},
},
[]string{
"class A",
"{",
" someProperty = false;",
" someMethod()",
" {",
" this.someMethod();",
" }",
"}",
},
)
}
func TestTouchingEditsTwoInsertsAtTheSamePosition(t *testing.T) {
check(
t,
[]string{
"hello world",
},
[]operation{
{
start: Loc{0, 0},
end: Loc{0, 0},
text: []string{
"a",
},
},
{
start: Loc{0, 0},
end: Loc{0, 0},
text: []string{
"b",
},
},
},
[]string{
"abhello world",
},
)
}
func TestTouchingEditsInsertAndReplaceTouching(t *testing.T) {
check(
t,
[]string{
"hello world",
},
[]operation{
{
start: Loc{0, 0},
end: Loc{0, 0},
text: []string{
"b",
},
},
{
start: Loc{0, 0},
end: Loc{2, 0},
text: []string{
"ab",
},
},
},
[]string{
"babllo world",
},
)
}
func TestTouchingEditsTwoTouchingReplaces(t *testing.T) {
check(
t,
[]string{
"hello world",
},
[]operation{
{
start: Loc{0, 0},
end: Loc{1, 0},
text: []string{
"H",
},
},
{
start: Loc{1, 0},
end: Loc{2, 0},
text: []string{
"E",
},
},
},
[]string{
"HEllo world",
},
)
}
func TestTouchingEditsTwoTouchingDeletes(t *testing.T) {
check(
t,
[]string{
"hello world",
},
[]operation{
{
start: Loc{0, 0},
end: Loc{1, 0},
text: []string{
"",
},
},
{
start: Loc{1, 0},
end: Loc{2, 0},
text: []string{
"",
},
},
},
[]string{
"llo world",
},
)
}
func TestTouchingEditsInsertAndReplace(t *testing.T) {
check(
t,
[]string{
"hello world",
},
[]operation{
{
start: Loc{0, 0},
end: Loc{0, 0},
text: []string{
"H",
},
},
{
start: Loc{0, 0},
end: Loc{2, 0},
text: []string{
"e",
},
},
},
[]string{
"Hello world",
},
)
}
func TestTouchingEditsReplaceAndInsert(t *testing.T) {
check(
t,
[]string{
"hello world",
},
[]operation{
{
start: Loc{0, 0},
end: Loc{2, 0},
text: []string{
"H",
},
},
{
start: Loc{2, 0},
end: Loc{2, 0},
text: []string{
"e",
},
},
},
[]string{
"Hello world",
},
)
}
func TestSingleDelete1(t *testing.T) {
check(
t,
[]string{
"hello world",
},
[]operation{
{
start: Loc{0, 0},
end: Loc{1, 0},
text: []string{
"",
},
},
},
[]string{
"ello world",
},
)
}
func TestSingleDelete2(t *testing.T) {
check(
t,
[]string{
"helloworld",
},
[]operation{
{
start: Loc{2, 0},
end: Loc{7, 0},
text: []string{
"",
},
},
},
[]string{
"herld",
},
)
}
func TestSingleDelete3(t *testing.T) {
check(
t,
[]string{
"hello world",
},
[]operation{
{
start: Loc{0, 0},
end: Loc{5, 0},
text: []string{
"",
},
},
},
[]string{
" world",
},
)
}
func TestSingleDelete4(t *testing.T) {
check(
t,
[]string{
"hello world",
},
[]operation{
{
start: Loc{1, 0},
end: Loc{6, 0},
text: []string{
"",
},
},
},
[]string{
"hworld",
},
)
}
func TestSingleDelete5(t *testing.T) {
check(
t,
[]string{
"hello world",
},
[]operation{
{
start: Loc{0, 0},
end: Loc{11, 0},
text: []string{
"",
},
},
},
[]string{
"",
},
)
}
func TestMultiDelete6(t *testing.T) {
check(
t,
[]string{
"hello world",
"hello world",
"hello world",
},
[]operation{
{
start: Loc{5, 0},
end: Loc{5, 2},
text: []string{
"",
},
},
},
[]string{
"hello world",
},
)
}
func TestMultiDelete7(t *testing.T) {
check(
t,
[]string{
"hello world",
"hello world",
"hello world",
},
[]operation{
{
start: Loc{11, 0},
end: Loc{11, 2},
text: []string{
"",
},
},
},
[]string{
"hello world",
},
)
}
func TestMultiDelete8(t *testing.T) {
check(
t,
[]string{
"hello world",
"hello world",
"hello world",
},
[]operation{
{
start: Loc{0, 0},
end: Loc{0, 2},
text: []string{
"",
},
},
},
[]string{
"hello world",
},
)
}
func TestMultiDelete9(t *testing.T) {
check(
t,
[]string{
"hello world",
"hello world",
"hello world",
},
[]operation{
{
start: Loc{11, 0},
end: Loc{0, 2},
text: []string{
"",
},
},
},
[]string{
"hello worldhello world",
},
)
}
func TestSingleInsert1(t *testing.T) {
check(
t,
[]string{
"hello world",
},
[]operation{
{
start: Loc{0, 0},
end: Loc{0, 0},
text: []string{
"xx",
},
},
},
[]string{
"xxhello world",
},
)
}
func TestSingleInsert2(t *testing.T) {
check(
t,
[]string{
"hello world",
},
[]operation{
{
start: Loc{1, 0},
end: Loc{1, 0},
text: []string{
"xx",
},
},
},
[]string{
"hxxello world",
},
)
}
func TestSingleInsert3(t *testing.T) {
check(
t,
[]string{
"hello world",
},
[]operation{
{
start: Loc{5, 0},
end: Loc{5, 0},
text: []string{
"xx",
},
},
},
[]string{
"helloxx world",
},
)
}
func TestSingleInsert4(t *testing.T) {
check(
t,
[]string{
"hello world",
},
[]operation{
{
start: Loc{6, 0},
end: Loc{6, 0},
text: []string{
"xx",
},
},
},
[]string{
"hello xxworld",
},
)
}
func TestSingleInsert5(t *testing.T) {
check(
t,
[]string{
"hello world",
},
[]operation{
{
start: Loc{11, 0},
end: Loc{11, 0},
text: []string{
"xx",
},
},
},
[]string{
"hello worldxx",
},
)
}
func TestMultiInsert6(t *testing.T) {
check(
t,
[]string{
"hello world",
},
[]operation{
{
start: Loc{0, 0},
end: Loc{0, 0},
text: []string{
"\n",
},
},
},
[]string{
"",
"hello world",
},
)
}
func TestMultiInsert7(t *testing.T) {
check(
t,
[]string{
"hello world",
},
[]operation{
{
start: Loc{11, 0},
end: Loc{11, 0},
text: []string{
"\n",
},
},
},
[]string{
"hello world",
"",
},
)
}
func TestMultiInsert8(t *testing.T) {
check(
t,
[]string{
"hello world",
},
[]operation{
{
start: Loc{6, 0},
end: Loc{6, 0},
text: []string{
"\n",
},
},
},
[]string{
"hello ",
"world",
},
)
}
func TestMultiInsert9(t *testing.T) {
check(
t,
[]string{
"hello world",
"hello world",
},
[]operation{
{
start: Loc{6, 0},
end: Loc{6, 0},
text: []string{
"xx\nyy",
},
},
},
[]string{
"hello xx",
"yyworld",
"hello world",
},
)
}
```
|
/content/code_sandbox/internal/buffer/buffer_generated_test.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 9,174
|
```go
package views
import (
"fmt"
"strings"
)
type SplitType uint8
const (
STVert = 0
STHoriz = 1
STUndef = 2
)
var idcounter uint64
// NewID returns a new unique id
func NewID() uint64 {
idcounter++
return idcounter
}
// A View is a size and location of a split
type View struct {
X, Y int
W, H int
}
// A Node describes a split in the tree
// If a node is a leaf node then it corresponds to a buffer that is being
// displayed otherwise it has a number of children of the opposite type
// (vertical splits have horizontal children and vice versa)
type Node struct {
View
Kind SplitType
parent *Node
children []*Node
// Nodes can be marked as non resizable if they shouldn't be rescaled
// when the terminal window is resized or when a new split is added
// Only the splits on the edges of the screen can be marked as non resizable
canResize bool
// A node may also be marked with proportional scaling. This means that when
// the window is resized the split maintains its proportions
propScale bool
// Defines the proportion of the screen this node should take up if propScale is
// on
propW, propH float64
// The id is unique for each leaf node and provides a way to keep track of a split
// The id cannot be 0
id uint64
}
// NewNode returns a new node with the given specifications
func NewNode(Kind SplitType, x, y, w, h int, parent *Node, id uint64) *Node {
n := new(Node)
n.Kind = Kind
n.canResize = true
n.propScale = true
n.X, n.Y, n.W, n.H = x, y, w, h
n.children = make([]*Node, 0)
n.parent = parent
n.id = id
if parent != nil {
n.propW, n.propH = float64(w)/float64(parent.W), float64(h)/float64(parent.H)
} else {
n.propW, n.propH = 1, 1
}
return n
}
// NewRoot returns an empty Node with a size and location
// The type of the node will be determined by the first action on the node
// In other words, a lone split is neither horizontal nor vertical, it only
// becomes one or the other after a vsplit or hsplit is made
func NewRoot(x, y, w, h int) *Node {
n1 := NewNode(STUndef, x, y, w, h, nil, NewID())
return n1
}
// IsLeaf returns if this node is a leaf node
func (n *Node) IsLeaf() bool {
return len(n.children) == 0
}
// ID returns this node's id or 0 if it is not viewable
func (n *Node) ID() uint64 {
if n.IsLeaf() {
return n.id
}
return 0
}
// CanResize returns if this node can be resized
func (n *Node) CanResize() bool {
return n.canResize
}
// PropScale returns if this node is proportionally scaled
func (n *Node) PropScale() bool {
return n.propScale
}
// SetResize sets the resize flag
func (n *Node) SetResize(b bool) {
n.canResize = b
}
// SetPropScale sets the propScale flag
func (n *Node) SetPropScale(b bool) {
n.propScale = b
}
// Children returns this node's children
func (n *Node) Children() []*Node {
return n.children
}
// GetNode returns the node with the given id in the tree of children
// that this node has access to or nil if the node with that id cannot be found
func (n *Node) GetNode(id uint64) *Node {
if n.id == id && n.IsLeaf() {
return n
}
for _, c := range n.children {
if c.id == id && c.IsLeaf() {
return c
}
gc := c.GetNode(id)
if gc != nil {
return gc
}
}
return nil
}
func (n *Node) vResizeSplit(i int, size int) bool {
if i < 0 || i >= len(n.children) {
return false
}
var c1, c2 *Node
if i == len(n.children)-1 {
c1, c2 = n.children[i-1], n.children[i]
} else {
c1, c2 = n.children[i], n.children[i+1]
}
toth := c1.H + c2.H
if size >= toth {
return false
}
c2.Y = c1.Y + size
c1.Resize(c1.W, size)
c2.Resize(c2.W, toth-size)
n.markSizes()
n.alignSizes(n.W, n.H)
return true
}
func (n *Node) hResizeSplit(i int, size int) bool {
if i < 0 || i >= len(n.children) {
return false
}
var c1, c2 *Node
if i == len(n.children)-1 {
c1, c2 = n.children[i-1], n.children[i]
} else {
c1, c2 = n.children[i], n.children[i+1]
}
totw := c1.W + c2.W
if size >= totw {
return false
}
c2.X = c1.X + size
c1.Resize(size, c1.H)
c2.Resize(totw-size, c2.H)
n.markSizes()
n.alignSizes(n.W, n.H)
return true
}
// ResizeSplit resizes a certain split to a given size
func (n *Node) ResizeSplit(size int) bool {
// TODO: `size < 0` does not work for some reason
if size <= 0 {
return false
}
if len(n.parent.children) <= 1 {
// cannot resize a lone node
return false
}
ind := 0
for i, c := range n.parent.children {
if c.id == n.id {
ind = i
}
}
if n.parent.Kind == STVert {
return n.parent.vResizeSplit(ind, size)
}
return n.parent.hResizeSplit(ind, size)
}
// Resize sets this node's size and resizes all children accordingly
func (n *Node) Resize(w, h int) {
n.W, n.H = w, h
if n.IsLeaf() {
return
}
x, y := n.X, n.Y
totw, toth := 0, 0
for _, c := range n.children {
cW := int(float64(w) * c.propW)
cH := int(float64(h) * c.propH)
c.X, c.Y = x, y
c.Resize(cW, cH)
if n.Kind == STHoriz {
x += cW
totw += cW
} else {
y += cH
toth += cH
}
}
n.alignSizes(totw, toth)
}
func (n *Node) alignSizes(totw, toth int) {
// Make sure that there are no off-by-one problems with the rounding
// of the sizes by making the final split fill the screen
if n.Kind == STVert && toth != n.H {
last := n.children[len(n.children)-1]
last.Resize(last.W, last.H+n.H-toth)
} else if n.Kind == STHoriz && totw != n.W {
last := n.children[len(n.children)-1]
last.Resize(last.W+n.W-totw, last.H)
}
}
// Resets all proportions for children
func (n *Node) markSizes() {
for _, c := range n.children {
c.propW = float64(c.W) / float64(n.W)
c.propH = float64(c.H) / float64(n.H)
c.markSizes()
}
}
func (n *Node) markResize() {
n.markSizes()
n.Resize(n.W, n.H)
}
// vsplits a vertical split and returns the id of the new split
func (n *Node) vVSplit(right bool) uint64 {
ind := 0
for i, c := range n.parent.children {
if c.id == n.id {
ind = i
}
}
return n.parent.hVSplit(ind, right)
}
// hsplits a horizontal split
func (n *Node) hHSplit(bottom bool) uint64 {
ind := 0
for i, c := range n.parent.children {
if c.id == n.id {
ind = i
}
}
return n.parent.vHSplit(ind, bottom)
}
// Returns the size of the non-resizable area and the number of resizable
// splits
func (n *Node) getResizeInfo(h bool) (int, int) {
numr := 0
numnr := 0
nonr := 0
for _, c := range n.children {
if !c.CanResize() {
if h {
nonr += c.H
} else {
nonr += c.W
}
numnr++
} else {
numr++
}
}
// if there are no resizable splits make them all resizable
if numr == 0 {
numr = numnr
}
return nonr, numr
}
func (n *Node) applyNewSize(size int, h bool) {
a := n.X
if h {
a = n.Y
}
for _, c := range n.children {
if h {
c.Y = a
} else {
c.X = a
}
if c.CanResize() {
if h {
c.Resize(c.W, size)
} else {
c.Resize(size, c.H)
}
}
if h {
a += c.H
} else {
a += c.H
}
}
n.markResize()
}
// hsplits a vertical split
func (n *Node) vHSplit(i int, right bool) uint64 {
if n.IsLeaf() {
newid := NewID()
hn1 := NewNode(STHoriz, n.X, n.Y, n.W, n.H/2, n, n.id)
hn2 := NewNode(STHoriz, n.X, n.Y+hn1.H, n.W, n.H/2, n, newid)
if !right {
hn1.id, hn2.id = hn2.id, hn1.id
}
n.children = append(n.children, hn1, hn2)
n.markResize()
return newid
} else {
nonrh, numr := n.getResizeInfo(true)
// size of resizable area
height := (n.H - nonrh) / (numr + 1)
newid := NewID()
hn := NewNode(STHoriz, n.X, 0, n.W, height, n, newid)
// insert the node into the correct slot
n.children = append(n.children, nil)
inspos := i
if right {
inspos++
}
copy(n.children[inspos+1:], n.children[inspos:])
n.children[inspos] = hn
n.applyNewSize(height, true)
return newid
}
}
// vsplits a horizontal split
func (n *Node) hVSplit(i int, right bool) uint64 {
if n.IsLeaf() {
newid := NewID()
vn1 := NewNode(STVert, n.X, n.Y, n.W/2, n.H, n, n.id)
vn2 := NewNode(STVert, n.X+vn1.W, n.Y, n.W/2, n.H, n, newid)
if !right {
vn1.id, vn2.id = vn2.id, vn1.id
}
n.children = append(n.children, vn1, vn2)
n.markResize()
return newid
} else {
nonrw, numr := n.getResizeInfo(false)
width := (n.W - nonrw) / (numr + 1)
newid := NewID()
vn := NewNode(STVert, 0, n.Y, width, n.H, n, newid)
// Inser the node into the correct slot
n.children = append(n.children, nil)
inspos := i
if right {
inspos++
}
copy(n.children[inspos+1:], n.children[inspos:])
n.children[inspos] = vn
n.applyNewSize(width, false)
return newid
}
}
// HSplit creates a horizontal split and returns the id of the new split
// bottom specifies if the new split should be created on the top or bottom
// of the current split
func (n *Node) HSplit(bottom bool) uint64 {
if !n.IsLeaf() {
return 0
}
if n.Kind == STUndef {
n.Kind = STVert
}
if n.Kind == STVert {
return n.vHSplit(0, bottom)
}
return n.hHSplit(bottom)
}
// VSplit creates a vertical split and returns the id of the new split
// right specifies if the new split should be created on the right or left
// of the current split
func (n *Node) VSplit(right bool) uint64 {
if !n.IsLeaf() {
return 0
}
if n.Kind == STUndef {
n.Kind = STHoriz
}
if n.Kind == STVert {
return n.vVSplit(right)
}
return n.hVSplit(0, right)
}
// unsplits the child of a split
func (n *Node) unsplit(i int, h bool) {
copy(n.children[i:], n.children[i+1:])
n.children[len(n.children)-1] = nil
n.children = n.children[:len(n.children)-1]
nonrs, numr := n.getResizeInfo(h)
if numr == 0 {
// This means that this was the last child
// The parent will get cleaned up in the next iteration and
// will resolve all sizing issues with its parent
return
}
size := (n.W - nonrs) / numr
if h {
size = (n.H - nonrs) / numr
}
n.applyNewSize(size, h)
}
// Unsplit deletes this split and resizes everything
// else accordingly
func (n *Node) Unsplit() bool {
if !n.IsLeaf() || n.parent == nil {
return false
}
ind := 0
for i, c := range n.parent.children {
if c.id == n.id {
ind = i
}
}
if n.parent.Kind == STVert {
n.parent.unsplit(ind, true)
} else {
n.parent.unsplit(ind, false)
}
if n.parent.IsLeaf() {
return n.parent.Unsplit()
}
return true
}
// String returns the string form of the node and all children (used for debugging)
func (n *Node) String() string {
var strf func(n *Node, ident int) string
strf = func(n *Node, ident int) string {
marker := "|"
if n.Kind == STHoriz {
marker = "-"
}
str := fmt.Sprint(strings.Repeat("\t", ident), marker, n.View, n.id)
if n.IsLeaf() {
str += ""
}
str += "\n"
for _, c := range n.children {
str += strf(c, ident+1)
}
return str
}
return strf(n, 0)
}
```
|
/content/code_sandbox/internal/views/splits.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 3,530
|
```go
package views
import (
"fmt"
"testing"
)
func TestHSplit(t *testing.T) {
root := NewRoot(0, 0, 80, 80)
n1 := root.VSplit(true)
root.GetNode(n1).VSplit(true)
root.GetNode(root.id).ResizeSplit(7)
root.Resize(120, 120)
fmt.Println(root.String())
}
```
|
/content/code_sandbox/internal/views/splits_test.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 82
|
```go
package util
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestStringWidth(t *testing.T) {
bytes := []byte("\tPot s \tmnnc sticl i ea nu m rnete.")
n := StringWidth(bytes, 23, 4)
assert.Equal(t, 26, n)
}
func TestSliceVisualEnd(t *testing.T) {
s := []byte("\thello")
slc, n, _ := SliceVisualEnd(s, 2, 4)
assert.Equal(t, []byte("\thello"), slc)
assert.Equal(t, 2, n)
slc, n, _ = SliceVisualEnd(s, 1, 4)
assert.Equal(t, []byte("\thello"), slc)
assert.Equal(t, 1, n)
slc, n, _ = SliceVisualEnd(s, 4, 4)
assert.Equal(t, []byte("hello"), slc)
assert.Equal(t, 0, n)
slc, n, _ = SliceVisualEnd(s, 5, 4)
assert.Equal(t, []byte("ello"), slc)
assert.Equal(t, 0, n)
}
```
|
/content/code_sandbox/internal/util/util_test.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 248
|
```go
package buffer
import (
"bufio"
"bytes"
"crypto/md5"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"path"
"path/filepath"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
luar "layeh.com/gopher-luar"
dmp "github.com/sergi/go-diff/diffmatchpatch"
"github.com/zyedidia/micro/v2/internal/config"
ulua "github.com/zyedidia/micro/v2/internal/lua"
"github.com/zyedidia/micro/v2/internal/screen"
"github.com/zyedidia/micro/v2/internal/util"
"github.com/zyedidia/micro/v2/pkg/highlight"
"golang.org/x/text/encoding/htmlindex"
"golang.org/x/text/encoding/unicode"
"golang.org/x/text/transform"
)
const backupTime = 8000
var (
// OpenBuffers is a list of the currently open buffers
OpenBuffers []*Buffer
// LogBuf is a reference to the log buffer which can be opened with the
// `> log` command
LogBuf *Buffer
)
// The BufType defines what kind of buffer this is
type BufType struct {
Kind int
Readonly bool // The buffer cannot be edited
Scratch bool // The buffer cannot be saved
Syntax bool // Syntax highlighting is enabled
}
var (
// BTDefault is a default buffer
BTDefault = BufType{0, false, false, true}
// BTHelp is a help buffer
BTHelp = BufType{1, true, true, true}
// BTLog is a log buffer
BTLog = BufType{2, true, true, false}
// BTScratch is a buffer that cannot be saved (for scratch work)
BTScratch = BufType{3, false, true, false}
// BTRaw is a buffer that shows raw terminal events
BTRaw = BufType{4, false, true, false}
// BTInfo is a buffer for inputting information
BTInfo = BufType{5, false, true, false}
// BTStdout is a buffer that only writes to stdout
// when closed
BTStdout = BufType{6, false, true, true}
)
// SharedBuffer is a struct containing info that is shared among buffers
// that have the same file open
type SharedBuffer struct {
*LineArray
// Stores the last modification time of the file the buffer is pointing to
ModTime time.Time
// Type of the buffer (e.g. help, raw, scratch etc..)
Type BufType
// Path to the file on disk
Path string
// Absolute path to the file on disk
AbsPath string
// Name of the buffer on the status line
name string
toStdout bool
// Settings customized by the user
Settings map[string]interface{}
// LocalSettings customized by the user for this buffer only
LocalSettings map[string]bool
Suggestions []string
Completions []string
CurSuggestion int
Messages []*Message
updateDiffTimer *time.Timer
diffBase []byte
diffBaseLineCount int
diffLock sync.RWMutex
diff map[int]DiffStatus
requestedBackup bool
// ReloadDisabled allows the user to disable reloads if they
// are viewing a file that is constantly changing
ReloadDisabled bool
isModified bool
// Whether or not suggestions can be autocompleted must be shared because
// it changes based on how the buffer has changed
HasSuggestions bool
// The Highlighter struct actually performs the highlighting
Highlighter *highlight.Highlighter
// SyntaxDef represents the syntax highlighting definition being used
// This stores the highlighting rules and filetype detection info
SyntaxDef *highlight.Def
ModifiedThisFrame bool
// Hash of the original buffer -- empty if fastdirty is on
origHash [md5.Size]byte
}
func (b *SharedBuffer) insert(pos Loc, value []byte) {
b.isModified = true
b.HasSuggestions = false
b.LineArray.insert(pos, value)
inslines := bytes.Count(value, []byte{'\n'})
b.MarkModified(pos.Y, pos.Y+inslines)
}
func (b *SharedBuffer) remove(start, end Loc) []byte {
b.isModified = true
b.HasSuggestions = false
defer b.MarkModified(start.Y, end.Y)
return b.LineArray.remove(start, end)
}
// MarkModified marks the buffer as modified for this frame
// and performs rehighlighting if syntax highlighting is enabled
func (b *SharedBuffer) MarkModified(start, end int) {
b.ModifiedThisFrame = true
start = util.Clamp(start, 0, len(b.lines)-1)
end = util.Clamp(end, 0, len(b.lines)-1)
if b.Settings["syntax"].(bool) && b.SyntaxDef != nil {
l := -1
for i := start; i <= end; i++ {
l = util.Max(b.Highlighter.ReHighlightStates(b, i), l)
}
b.Highlighter.HighlightMatches(b, start, l)
}
for i := start; i <= end; i++ {
b.LineArray.invalidateSearchMatches(i)
}
}
// DisableReload disables future reloads of this sharedbuffer
func (b *SharedBuffer) DisableReload() {
b.ReloadDisabled = true
}
const (
DSUnchanged = 0
DSAdded = 1
DSModified = 2
DSDeletedAbove = 3
)
type DiffStatus byte
// Buffer stores the main information about a currently open file including
// the actual text (in a LineArray), the undo/redo stack (in an EventHandler)
// all the cursors, the syntax highlighting info, the settings for the buffer
// and some misc info about modification time and path location.
// The syntax highlighting info must be stored with the buffer because the syntax
// highlighter attaches information to each line of the buffer for optimization
// purposes so it doesn't have to rehighlight everything on every update.
// Likewise for the search highlighting.
type Buffer struct {
*EventHandler
*SharedBuffer
fini int32
cursors []*Cursor
curCursor int
StartCursor Loc
// OptionCallback is called after a buffer option value is changed.
// The display module registers its OptionCallback to ensure the buffer window
// is properly updated when needed. This is a workaround for the fact that
// the buffer module cannot directly call the display's API (it would mean
// a circular dependency between packages).
OptionCallback func(option string, nativeValue interface{})
// The display module registers its own GetVisualX function for getting
// the correct visual x location of a cursor when softwrap is used.
// This is hacky. Maybe it would be better to move all the visual x logic
// from buffer to display, but it would require rewriting a lot of code.
GetVisualX func(loc Loc) int
// Last search stores the last successful search
LastSearch string
LastSearchRegex bool
// HighlightSearch enables highlighting all instances of the last successful search
HighlightSearch bool
}
// NewBufferFromFileAtLoc opens a new buffer with a given cursor location
// If cursorLoc is {-1, -1} the location does not overwrite what the cursor location
// would otherwise be (start of file, or saved cursor position if `savecursor` is
// enabled)
func NewBufferFromFileAtLoc(path string, btype BufType, cursorLoc Loc) (*Buffer, error) {
var err error
filename := path
if config.GetGlobalOption("parsecursor").(bool) && cursorLoc.X == -1 && cursorLoc.Y == -1 {
var cursorPos []string
filename, cursorPos = util.GetPathAndCursorPosition(filename)
cursorLoc, err = ParseCursorLocation(cursorPos)
if err != nil {
cursorLoc = Loc{-1, -1}
}
}
filename, err = util.ReplaceHome(filename)
if err != nil {
return nil, err
}
f, err := os.OpenFile(filename, os.O_WRONLY, 0)
readonly := os.IsPermission(err)
f.Close()
fileInfo, serr := os.Stat(filename)
if serr != nil && !os.IsNotExist(serr) {
return nil, serr
}
if serr == nil && fileInfo.IsDir() {
return nil, errors.New("Error: " + filename + " is a directory and cannot be opened")
}
file, err := os.Open(filename)
if err == nil {
defer file.Close()
}
var buf *Buffer
if os.IsNotExist(err) {
// File does not exist -- create an empty buffer with that name
buf = NewBufferFromString("", filename, btype)
} else if err != nil {
return nil, err
} else {
buf = NewBuffer(file, util.FSize(file), filename, cursorLoc, btype)
if buf == nil {
return nil, errors.New("could not open file")
}
}
if readonly && prompt != nil {
prompt.Message(fmt.Sprintf("Warning: file is readonly - %s will be attempted when saving", config.GlobalSettings["sucmd"].(string)))
// buf.SetOptionNative("readonly", true)
}
return buf, nil
}
// NewBufferFromFile opens a new buffer using the given path
// It will also automatically handle `~`, and line/column with filename:l:c
// It will return an empty buffer if the path does not exist
// and an error if the file is a directory
func NewBufferFromFile(path string, btype BufType) (*Buffer, error) {
return NewBufferFromFileAtLoc(path, btype, Loc{-1, -1})
}
// NewBufferFromStringAtLoc creates a new buffer containing the given string with a cursor loc
func NewBufferFromStringAtLoc(text, path string, btype BufType, cursorLoc Loc) *Buffer {
return NewBuffer(strings.NewReader(text), int64(len(text)), path, cursorLoc, btype)
}
// NewBufferFromString creates a new buffer containing the given string
func NewBufferFromString(text, path string, btype BufType) *Buffer {
return NewBuffer(strings.NewReader(text), int64(len(text)), path, Loc{-1, -1}, btype)
}
// NewBuffer creates a new buffer from a given reader with a given path
// Ensure that ReadSettings and InitGlobalSettings have been called before creating
// a new buffer
// Places the cursor at startcursor. If startcursor is -1, -1 places the
// cursor at an autodetected location (based on savecursor or :LINE:COL)
func NewBuffer(r io.Reader, size int64, path string, startcursor Loc, btype BufType) *Buffer {
absPath, err := filepath.Abs(path)
if err != nil {
absPath = path
}
b := new(Buffer)
found := false
if len(path) > 0 {
for _, buf := range OpenBuffers {
if buf.AbsPath == absPath && buf.Type != BTInfo {
found = true
b.SharedBuffer = buf.SharedBuffer
b.EventHandler = buf.EventHandler
}
}
}
hasBackup := false
if !found {
b.SharedBuffer = new(SharedBuffer)
b.Type = btype
b.AbsPath = absPath
b.Path = path
// this is a little messy since we need to know some settings to read
// the file properly, but some settings depend on the filetype, which
// we don't know until reading the file. We first read the settings
// into a local variable and then use that to determine the encoding,
// readonly, and fileformat necessary for reading the file and
// assigning the filetype.
settings := config.DefaultCommonSettings()
b.Settings = config.DefaultCommonSettings()
b.LocalSettings = make(map[string]bool)
for k, v := range config.GlobalSettings {
if _, ok := config.DefaultGlobalOnlySettings[k]; !ok {
// make sure setting is not global-only
settings[k] = v
b.Settings[k] = v
}
}
config.InitLocalSettings(settings, absPath)
b.Settings["readonly"] = settings["readonly"]
b.Settings["filetype"] = settings["filetype"]
b.Settings["syntax"] = settings["syntax"]
enc, err := htmlindex.Get(settings["encoding"].(string))
if err != nil {
enc = unicode.UTF8
b.Settings["encoding"] = "utf-8"
}
var ok bool
hasBackup, ok = b.ApplyBackup(size)
if !ok {
return NewBufferFromString("", "", btype)
}
if !hasBackup {
reader := bufio.NewReader(transform.NewReader(r, enc.NewDecoder()))
var ff FileFormat = FFAuto
if size == 0 {
// for empty files, use the fileformat setting instead of
// autodetection
switch settings["fileformat"] {
case "unix":
ff = FFUnix
case "dos":
ff = FFDos
}
} else {
// in case of autodetection treat as locally set
b.LocalSettings["fileformat"] = true
}
b.LineArray = NewLineArray(uint64(size), ff, reader)
}
b.EventHandler = NewEventHandler(b.SharedBuffer, b.cursors)
// The last time this file was modified
b.UpdateModTime()
}
if b.Settings["readonly"].(bool) && b.Type == BTDefault {
b.Type.Readonly = true
}
switch b.Endings {
case FFUnix:
b.Settings["fileformat"] = "unix"
case FFDos:
b.Settings["fileformat"] = "dos"
}
b.UpdateRules()
// init local settings again now that we know the filetype
config.InitLocalSettings(b.Settings, b.Path)
if _, err := os.Stat(filepath.Join(config.ConfigDir, "buffers")); os.IsNotExist(err) {
os.Mkdir(filepath.Join(config.ConfigDir, "buffers"), os.ModePerm)
}
if startcursor.X != -1 && startcursor.Y != -1 {
b.StartCursor = startcursor
} else if b.Settings["savecursor"].(bool) || b.Settings["saveundo"].(bool) {
err := b.Unserialize()
if err != nil {
screen.TermMessage(err)
}
}
b.AddCursor(NewCursor(b, b.StartCursor))
b.GetActiveCursor().Relocate()
if !b.Settings["fastdirty"].(bool) && !found {
if size > LargeFileThreshold {
// If the file is larger than LargeFileThreshold fastdirty needs to be on
b.Settings["fastdirty"] = true
} else if !hasBackup {
// since applying a backup does not save the applied backup to disk, we should
// not calculate the original hash based on the backup data
calcHash(b, &b.origHash)
}
}
err = config.RunPluginFn("onBufferOpen", luar.New(ulua.L, b))
if err != nil {
screen.TermMessage(err)
}
OpenBuffers = append(OpenBuffers, b)
return b
}
// CloseOpenBuffers removes all open buffers
func CloseOpenBuffers() {
for i, buf := range OpenBuffers {
buf.Fini()
OpenBuffers[i] = nil
}
OpenBuffers = OpenBuffers[:0]
}
// Close removes this buffer from the list of open buffers
func (b *Buffer) Close() {
for i, buf := range OpenBuffers {
if b == buf {
b.Fini()
copy(OpenBuffers[i:], OpenBuffers[i+1:])
OpenBuffers[len(OpenBuffers)-1] = nil
OpenBuffers = OpenBuffers[:len(OpenBuffers)-1]
return
}
}
}
// Fini should be called when a buffer is closed and performs
// some cleanup
func (b *Buffer) Fini() {
if !b.Modified() {
b.Serialize()
}
b.RemoveBackup()
if b.Type == BTStdout {
fmt.Fprint(util.Stdout, string(b.Bytes()))
}
atomic.StoreInt32(&(b.fini), int32(1))
}
// GetName returns the name that should be displayed in the statusline
// for this buffer
func (b *Buffer) GetName() string {
name := b.name
if name == "" {
if b.Path == "" {
return "No name"
}
name = b.Path
}
if b.Settings["basename"].(bool) {
return path.Base(name)
}
return name
}
// SetName changes the name for this buffer
func (b *Buffer) SetName(s string) {
b.name = s
}
// Insert inserts the given string of text at the start location
func (b *Buffer) Insert(start Loc, text string) {
if !b.Type.Readonly {
b.EventHandler.cursors = b.cursors
b.EventHandler.active = b.curCursor
b.EventHandler.Insert(start, text)
b.RequestBackup()
}
}
// Remove removes the characters between the start and end locations
func (b *Buffer) Remove(start, end Loc) {
if !b.Type.Readonly {
b.EventHandler.cursors = b.cursors
b.EventHandler.active = b.curCursor
b.EventHandler.Remove(start, end)
b.RequestBackup()
}
}
// FileType returns the buffer's filetype
func (b *Buffer) FileType() string {
return b.Settings["filetype"].(string)
}
// ExternallyModified returns whether the file being edited has
// been modified by some external process
func (b *Buffer) ExternallyModified() bool {
modTime, err := util.GetModTime(b.Path)
if err == nil {
return modTime != b.ModTime
}
return false
}
// UpdateModTime updates the modtime of this file
func (b *Buffer) UpdateModTime() (err error) {
b.ModTime, err = util.GetModTime(b.Path)
return
}
// ReOpen reloads the current buffer from disk
func (b *Buffer) ReOpen() error {
file, err := os.Open(b.Path)
if err != nil {
return err
}
enc, err := htmlindex.Get(b.Settings["encoding"].(string))
if err != nil {
return err
}
reader := bufio.NewReader(transform.NewReader(file, enc.NewDecoder()))
data, err := ioutil.ReadAll(reader)
txt := string(data)
if err != nil {
return err
}
b.EventHandler.ApplyDiff(txt)
err = b.UpdateModTime()
if !b.Settings["fastdirty"].(bool) {
if len(data) > LargeFileThreshold {
b.Settings["fastdirty"] = true
} else {
calcHash(b, &b.origHash)
}
}
b.isModified = false
b.RelocateCursors()
return err
}
// RelocateCursors relocates all cursors (makes sure they are in the buffer)
func (b *Buffer) RelocateCursors() {
for _, c := range b.cursors {
c.Relocate()
}
}
// DeselectCursors removes selection from all cursors
func (b *Buffer) DeselectCursors() {
for _, c := range b.cursors {
c.Deselect(true)
}
}
// RuneAt returns the rune at a given location in the buffer
func (b *Buffer) RuneAt(loc Loc) rune {
line := b.LineBytes(loc.Y)
if len(line) > 0 {
i := 0
for len(line) > 0 {
r, _, size := util.DecodeCharacter(line)
line = line[size:]
if i == loc.X {
return r
}
i++
}
}
return '\n'
}
// WordAt returns the word around a given location in the buffer
func (b *Buffer) WordAt(loc Loc) []byte {
if len(b.LineBytes(loc.Y)) == 0 || !util.IsWordChar(b.RuneAt(loc)) {
return []byte{}
}
start := loc
end := loc.Move(1, b)
for start.X > 0 && util.IsWordChar(b.RuneAt(start.Move(-1, b))) {
start.X--
}
lineLen := util.CharacterCount(b.LineBytes(loc.Y))
for end.X < lineLen && util.IsWordChar(b.RuneAt(end)) {
end.X++
}
return b.Substr(start, end)
}
// Modified returns if this buffer has been modified since
// being opened
func (b *Buffer) Modified() bool {
if b.Type.Scratch {
return false
}
if b.Settings["fastdirty"].(bool) {
return b.isModified
}
var buff [md5.Size]byte
calcHash(b, &buff)
return buff != b.origHash
}
// Size returns the number of bytes in the current buffer
func (b *Buffer) Size() int {
nb := 0
for i := 0; i < b.LinesNum(); i++ {
nb += len(b.LineBytes(i))
if i != b.LinesNum()-1 {
if b.Endings == FFDos {
nb++ // carriage return
}
nb++ // newline
}
}
return nb
}
// calcHash calculates md5 hash of all lines in the buffer
func calcHash(b *Buffer, out *[md5.Size]byte) {
h := md5.New()
if len(b.lines) > 0 {
h.Write(b.lines[0].data)
for _, l := range b.lines[1:] {
if b.Endings == FFDos {
h.Write([]byte{'\r', '\n'})
} else {
h.Write([]byte{'\n'})
}
h.Write(l.data)
}
}
h.Sum((*out)[:0])
}
func parseDefFromFile(f config.RuntimeFile, header *highlight.Header) *highlight.Def {
data, err := f.Data()
if err != nil {
screen.TermMessage("Error loading syntax file " + f.Name() + ": " + err.Error())
return nil
}
if header == nil {
header, err = highlight.MakeHeaderYaml(data)
if err != nil {
screen.TermMessage("Error parsing header for syntax file " + f.Name() + ": " + err.Error())
return nil
}
}
file, err := highlight.ParseFile(data)
if err != nil {
screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
return nil
}
syndef, err := highlight.ParseDef(file, header)
if err != nil {
screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
return nil
}
return syndef
}
// findRealRuntimeSyntaxDef finds a specific syntax definition
// in the user's custom syntax files
func findRealRuntimeSyntaxDef(name string, header *highlight.Header) *highlight.Def {
for _, f := range config.ListRealRuntimeFiles(config.RTSyntax) {
if f.Name() == name {
syndef := parseDefFromFile(f, header)
if syndef != nil {
return syndef
}
}
}
return nil
}
// findRuntimeSyntaxDef finds a specific syntax definition
// in the built-in syntax files
func findRuntimeSyntaxDef(name string, header *highlight.Header) *highlight.Def {
for _, f := range config.ListRuntimeFiles(config.RTSyntax) {
if f.Name() == name {
syndef := parseDefFromFile(f, header)
if syndef != nil {
return syndef
}
}
}
return nil
}
func resolveIncludes(syndef *highlight.Def) {
includes := highlight.GetIncludes(syndef)
if len(includes) == 0 {
return
}
var files []*highlight.File
for _, f := range config.ListRuntimeFiles(config.RTSyntax) {
data, err := f.Data()
if err != nil {
screen.TermMessage("Error loading syntax file " + f.Name() + ": " + err.Error())
continue
}
header, err := highlight.MakeHeaderYaml(data)
if err != nil {
screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
continue
}
for _, i := range includes {
if header.FileType == i {
file, err := highlight.ParseFile(data)
if err != nil {
screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
continue
}
files = append(files, file)
break
}
}
if len(files) >= len(includes) {
break
}
}
highlight.ResolveIncludes(syndef, files)
}
// UpdateRules updates the syntax rules and filetype for this buffer
// This is called when the colorscheme changes
func (b *Buffer) UpdateRules() {
if !b.Type.Syntax {
return
}
ft := b.Settings["filetype"].(string)
if ft == "off" {
b.ClearMatches()
b.SyntaxDef = nil
return
}
b.SyntaxDef = nil
// syntaxFileInfo is an internal helper structure
// to store properties of one single syntax file
type syntaxFileInfo struct {
header *highlight.Header
fileName string
syntaxDef *highlight.Def
}
fnameMatches := []syntaxFileInfo{}
headerMatches := []syntaxFileInfo{}
syntaxFile := ""
foundDef := false
var header *highlight.Header
// search for the syntax file in the user's custom syntax files
for _, f := range config.ListRealRuntimeFiles(config.RTSyntax) {
if f.Name() == "default" {
continue
}
data, err := f.Data()
if err != nil {
screen.TermMessage("Error loading syntax file " + f.Name() + ": " + err.Error())
continue
}
header, err = highlight.MakeHeaderYaml(data)
if err != nil {
screen.TermMessage("Error parsing header for syntax file " + f.Name() + ": " + err.Error())
continue
}
matchedFileType := false
matchedFileName := false
matchedFileHeader := false
if ft == "unknown" || ft == "" {
if header.MatchFileName(b.Path) {
matchedFileName = true
}
if len(fnameMatches) == 0 && header.MatchFileHeader(b.lines[0].data) {
matchedFileHeader = true
}
} else if header.FileType == ft {
matchedFileType = true
}
if matchedFileType || matchedFileName || matchedFileHeader {
file, err := highlight.ParseFile(data)
if err != nil {
screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
continue
}
syndef, err := highlight.ParseDef(file, header)
if err != nil {
screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
continue
}
if matchedFileType {
b.SyntaxDef = syndef
syntaxFile = f.Name()
foundDef = true
break
}
if matchedFileName {
fnameMatches = append(fnameMatches, syntaxFileInfo{header, f.Name(), syndef})
} else if matchedFileHeader {
headerMatches = append(headerMatches, syntaxFileInfo{header, f.Name(), syndef})
}
}
}
if !foundDef {
// search for the syntax file in the built-in syntax files
for _, f := range config.ListRuntimeFiles(config.RTSyntaxHeader) {
data, err := f.Data()
if err != nil {
screen.TermMessage("Error loading syntax header file " + f.Name() + ": " + err.Error())
continue
}
header, err = highlight.MakeHeader(data)
if err != nil {
screen.TermMessage("Error reading syntax header file", f.Name(), err)
continue
}
if ft == "unknown" || ft == "" {
if header.MatchFileName(b.Path) {
fnameMatches = append(fnameMatches, syntaxFileInfo{header, f.Name(), nil})
}
if len(fnameMatches) == 0 && header.MatchFileHeader(b.lines[0].data) {
headerMatches = append(headerMatches, syntaxFileInfo{header, f.Name(), nil})
}
} else if header.FileType == ft {
syntaxFile = f.Name()
break
}
}
}
if syntaxFile == "" {
matches := fnameMatches
if len(matches) == 0 {
matches = headerMatches
}
length := len(matches)
if length > 0 {
signatureMatch := false
if length > 1 {
// multiple matching syntax files found, try to resolve the ambiguity
// using signatures
detectlimit := util.IntOpt(b.Settings["detectlimit"])
lineCount := len(b.lines)
limit := lineCount
if detectlimit > 0 && lineCount > detectlimit {
limit = detectlimit
}
matchLoop:
for _, m := range matches {
if m.header.HasFileSignature() {
for i := 0; i < limit; i++ {
if m.header.MatchFileSignature(b.lines[i].data) {
syntaxFile = m.fileName
if m.syntaxDef != nil {
b.SyntaxDef = m.syntaxDef
foundDef = true
}
header = m.header
signatureMatch = true
break matchLoop
}
}
}
}
}
if length == 1 || !signatureMatch {
syntaxFile = matches[0].fileName
if matches[0].syntaxDef != nil {
b.SyntaxDef = matches[0].syntaxDef
foundDef = true
}
header = matches[0].header
}
}
}
if syntaxFile != "" && !foundDef {
// we found a syntax file using a syntax header file
b.SyntaxDef = findRuntimeSyntaxDef(syntaxFile, header)
}
if b.SyntaxDef != nil {
b.Settings["filetype"] = b.SyntaxDef.FileType
} else {
// search for the default file in the user's custom syntax files
b.SyntaxDef = findRealRuntimeSyntaxDef("default", nil)
if b.SyntaxDef == nil {
// search for the default file in the built-in syntax files
b.SyntaxDef = findRuntimeSyntaxDef("default", nil)
}
}
if b.SyntaxDef != nil {
resolveIncludes(b.SyntaxDef)
}
if b.SyntaxDef != nil {
b.Highlighter = highlight.NewHighlighter(b.SyntaxDef)
if b.Settings["syntax"].(bool) {
go func() {
b.Highlighter.HighlightStates(b)
b.Highlighter.HighlightMatches(b, 0, b.End().Y)
screen.Redraw()
}()
}
}
}
// ClearMatches clears all of the syntax highlighting for the buffer
func (b *Buffer) ClearMatches() {
for i := range b.lines {
b.SetMatch(i, nil)
b.SetState(i, nil)
}
}
// IndentString returns this buffer's indent method (a tabstop or n spaces
// depending on the settings)
func (b *Buffer) IndentString(tabsize int) string {
if b.Settings["tabstospaces"].(bool) {
return util.Spaces(tabsize)
}
return "\t"
}
// SetCursors resets this buffer's cursors to a new list
func (b *Buffer) SetCursors(c []*Cursor) {
b.cursors = c
b.EventHandler.cursors = b.cursors
b.EventHandler.active = b.curCursor
}
// AddCursor adds a new cursor to the list
func (b *Buffer) AddCursor(c *Cursor) {
b.cursors = append(b.cursors, c)
b.EventHandler.cursors = b.cursors
b.EventHandler.active = b.curCursor
b.UpdateCursors()
}
// SetCurCursor sets the current cursor
func (b *Buffer) SetCurCursor(n int) {
b.curCursor = n
}
// GetActiveCursor returns the main cursor in this buffer
func (b *Buffer) GetActiveCursor() *Cursor {
return b.cursors[b.curCursor]
}
// GetCursor returns the nth cursor
func (b *Buffer) GetCursor(n int) *Cursor {
return b.cursors[n]
}
// GetCursors returns the list of cursors in this buffer
func (b *Buffer) GetCursors() []*Cursor {
return b.cursors
}
// NumCursors returns the number of cursors
func (b *Buffer) NumCursors() int {
return len(b.cursors)
}
// MergeCursors merges any cursors that are at the same position
// into one cursor
func (b *Buffer) MergeCursors() {
var cursors []*Cursor
for i := 0; i < len(b.cursors); i++ {
c1 := b.cursors[i]
if c1 != nil {
for j := 0; j < len(b.cursors); j++ {
c2 := b.cursors[j]
if c2 != nil && i != j && c1.Loc == c2.Loc {
b.cursors[j] = nil
}
}
cursors = append(cursors, c1)
}
}
b.cursors = cursors
for i := range b.cursors {
b.cursors[i].Num = i
}
if b.curCursor >= len(b.cursors) {
b.curCursor = len(b.cursors) - 1
}
b.EventHandler.cursors = b.cursors
b.EventHandler.active = b.curCursor
}
// UpdateCursors updates all the cursors indices
func (b *Buffer) UpdateCursors() {
b.EventHandler.cursors = b.cursors
b.EventHandler.active = b.curCursor
for i, c := range b.cursors {
c.Num = i
}
}
func (b *Buffer) RemoveCursor(i int) {
copy(b.cursors[i:], b.cursors[i+1:])
b.cursors[len(b.cursors)-1] = nil
b.cursors = b.cursors[:len(b.cursors)-1]
b.curCursor = util.Clamp(b.curCursor, 0, len(b.cursors)-1)
b.UpdateCursors()
}
// ClearCursors removes all extra cursors
func (b *Buffer) ClearCursors() {
for i := 1; i < len(b.cursors); i++ {
b.cursors[i] = nil
}
b.cursors = b.cursors[:1]
b.UpdateCursors()
b.curCursor = 0
b.GetActiveCursor().Deselect(true)
}
// MoveLinesUp moves the range of lines up one row
func (b *Buffer) MoveLinesUp(start int, end int) {
if start < 1 || start >= end || end > len(b.lines) {
return
}
l := string(b.LineBytes(start - 1))
if end == len(b.lines) {
b.insert(
Loc{
util.CharacterCount(b.lines[end-1].data),
end - 1,
},
[]byte{'\n'},
)
}
b.Insert(
Loc{0, end},
l+"\n",
)
b.Remove(
Loc{0, start - 1},
Loc{0, start},
)
}
// MoveLinesDown moves the range of lines down one row
func (b *Buffer) MoveLinesDown(start int, end int) {
if start < 0 || start >= end || end >= len(b.lines) {
return
}
l := string(b.LineBytes(end))
b.Insert(
Loc{0, start},
l+"\n",
)
end++
b.Remove(
Loc{0, end},
Loc{0, end + 1},
)
}
var BracePairs = [][2]rune{
{'(', ')'},
{'{', '}'},
{'[', ']'},
}
func (b *Buffer) findMatchingBrace(braceType [2]rune, start Loc, char rune) (Loc, bool) {
var i int
if char == braceType[0] {
for y := start.Y; y < b.LinesNum(); y++ {
l := []rune(string(b.LineBytes(y)))
xInit := 0
if y == start.Y {
xInit = start.X
}
for x := xInit; x < len(l); x++ {
r := l[x]
if r == braceType[0] {
i++
} else if r == braceType[1] {
i--
if i == 0 {
return Loc{x, y}, true
}
}
}
}
} else if char == braceType[1] {
for y := start.Y; y >= 0; y-- {
l := []rune(string(b.lines[y].data))
xInit := len(l) - 1
if y == start.Y {
xInit = start.X
}
for x := xInit; x >= 0; x-- {
r := l[x]
if r == braceType[1] {
i++
} else if r == braceType[0] {
i--
if i == 0 {
return Loc{x, y}, true
}
}
}
}
}
return start, false
}
// If there is a brace character (for example '{' or ']') at the given start location,
// FindMatchingBrace returns the location of the matching brace for it (for example '}'
// or '['). The second returned value is true if there was no matching brace found
// for given starting location but it was found for the location one character left
// of it. The third returned value is true if the matching brace was found at all.
func (b *Buffer) FindMatchingBrace(start Loc) (Loc, bool, bool) {
// TODO: maybe can be more efficient with utf8 package
curLine := []rune(string(b.LineBytes(start.Y)))
// first try to find matching brace for the given location (it has higher priority)
if start.X >= 0 && start.X < len(curLine) {
startChar := curLine[start.X]
for _, bp := range BracePairs {
if startChar == bp[0] || startChar == bp[1] {
mb, found := b.findMatchingBrace(bp, start, startChar)
if found {
return mb, false, true
}
}
}
}
if b.Settings["matchbraceleft"].(bool) {
// failed to find matching brace for the given location, so try to find matching
// brace for the location one character left of it
if start.X-1 >= 0 && start.X-1 < len(curLine) {
leftChar := curLine[start.X-1]
left := Loc{start.X - 1, start.Y}
for _, bp := range BracePairs {
if leftChar == bp[0] || leftChar == bp[1] {
mb, found := b.findMatchingBrace(bp, left, leftChar)
if found {
return mb, true, true
}
}
}
}
}
return start, false, false
}
// Retab changes all tabs to spaces or vice versa
func (b *Buffer) Retab() {
toSpaces := b.Settings["tabstospaces"].(bool)
tabsize := util.IntOpt(b.Settings["tabsize"])
dirty := false
for i := 0; i < b.LinesNum(); i++ {
l := b.LineBytes(i)
ws := util.GetLeadingWhitespace(l)
if len(ws) != 0 {
if toSpaces {
ws = bytes.ReplaceAll(ws, []byte{'\t'}, bytes.Repeat([]byte{' '}, tabsize))
} else {
ws = bytes.ReplaceAll(ws, bytes.Repeat([]byte{' '}, tabsize), []byte{'\t'})
}
}
l = bytes.TrimLeft(l, " \t")
b.Lock()
b.lines[i].data = append(ws, l...)
b.Unlock()
b.MarkModified(i, i)
dirty = true
}
b.isModified = dirty
}
// ParseCursorLocation turns a cursor location like 10:5 (LINE:COL)
// into a loc
func ParseCursorLocation(cursorPositions []string) (Loc, error) {
startpos := Loc{0, 0}
var err error
// if no positions are available exit early
if cursorPositions == nil {
return startpos, errors.New("No cursor positions were provided.")
}
startpos.Y, err = strconv.Atoi(cursorPositions[0])
startpos.Y--
if err == nil {
if len(cursorPositions) > 1 {
startpos.X, err = strconv.Atoi(cursorPositions[1])
if startpos.X > 0 {
startpos.X--
}
}
}
return startpos, err
}
// Line returns the string representation of the given line number
func (b *Buffer) Line(i int) string {
return string(b.LineBytes(i))
}
func (b *Buffer) Write(bytes []byte) (n int, err error) {
b.EventHandler.InsertBytes(b.End(), bytes)
return len(bytes), nil
}
func (b *Buffer) updateDiff(synchronous bool) {
b.diffLock.Lock()
defer b.diffLock.Unlock()
b.diff = make(map[int]DiffStatus)
if b.diffBase == nil {
return
}
differ := dmp.New()
if !synchronous {
b.Lock()
}
bytes := b.Bytes()
if !synchronous {
b.Unlock()
}
baseRunes, bufferRunes, _ := differ.DiffLinesToRunes(string(b.diffBase), string(bytes))
diffs := differ.DiffMainRunes(baseRunes, bufferRunes, false)
lineN := 0
for _, diff := range diffs {
lineCount := len([]rune(diff.Text))
switch diff.Type {
case dmp.DiffEqual:
lineN += lineCount
case dmp.DiffInsert:
var status DiffStatus
if b.diff[lineN] == DSDeletedAbove {
status = DSModified
} else {
status = DSAdded
}
for i := 0; i < lineCount; i++ {
b.diff[lineN] = status
lineN++
}
case dmp.DiffDelete:
b.diff[lineN] = DSDeletedAbove
}
}
}
// UpdateDiff computes the diff between the diff base and the buffer content.
// The update may be performed synchronously or asynchronously.
// If an asynchronous update is already pending when UpdateDiff is called,
// UpdateDiff does not schedule another update.
func (b *Buffer) UpdateDiff() {
if b.updateDiffTimer != nil {
return
}
lineCount := b.LinesNum()
if b.diffBaseLineCount > lineCount {
lineCount = b.diffBaseLineCount
}
if lineCount < 1000 {
b.updateDiff(true)
} else if lineCount < 30000 {
b.updateDiffTimer = time.AfterFunc(500*time.Millisecond, func() {
b.updateDiffTimer = nil
b.updateDiff(false)
screen.Redraw()
})
} else {
// Don't compute diffs for very large files
b.diffLock.Lock()
b.diff = make(map[int]DiffStatus)
b.diffLock.Unlock()
}
}
// SetDiffBase sets the text that is used as the base for diffing the buffer content
func (b *Buffer) SetDiffBase(diffBase []byte) {
b.diffBase = diffBase
if diffBase == nil {
b.diffBaseLineCount = 0
} else {
b.diffBaseLineCount = strings.Count(string(diffBase), "\n")
}
b.UpdateDiff()
}
// DiffStatus returns the diff status for a line in the buffer
func (b *Buffer) DiffStatus(lineN int) DiffStatus {
b.diffLock.RLock()
defer b.diffLock.RUnlock()
// Note that the zero value for DiffStatus is equal to DSUnchanged
return b.diff[lineN]
}
// FindNextDiffLine returns the line number of the next block of diffs.
// If `startLine` is already in a block of diffs, lines in that block are skipped.
func (b *Buffer) FindNextDiffLine(startLine int, forward bool) (int, error) {
if b.diff == nil {
return 0, errors.New("no diff data")
}
startStatus, ok := b.diff[startLine]
if !ok {
startStatus = DSUnchanged
}
curLine := startLine
for {
curStatus, ok := b.diff[curLine]
if !ok {
curStatus = DSUnchanged
}
if curLine < 0 || curLine > b.LinesNum() {
return 0, errors.New("no next diff hunk")
}
if curStatus != startStatus {
if startStatus != DSUnchanged && curStatus == DSUnchanged {
// Skip over the block of unchanged text
startStatus = DSUnchanged
} else {
return curLine, nil
}
}
if forward {
curLine++
} else {
curLine--
}
}
}
// SearchMatch returns true if the given location is within a match of the last search.
// It is used for search highlighting
func (b *Buffer) SearchMatch(pos Loc) bool {
return b.LineArray.SearchMatch(b, pos)
}
// WriteLog writes a string to the log buffer
func WriteLog(s string) {
LogBuf.EventHandler.Insert(LogBuf.End(), s)
}
// GetLogBuf returns the log buffer
func GetLogBuf() *Buffer {
return LogBuf
}
```
|
/content/code_sandbox/internal/buffer/buffer.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 10,078
|
```go
package util
import (
"archive/zip"
"bytes"
"errors"
"fmt"
"io"
"net/http"
"os"
"os/user"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"
"time"
"unicode"
"unicode/utf8"
"github.com/blang/semver"
runewidth "github.com/mattn/go-runewidth"
)
var (
// These variables should be set by the linker when compiling
// Version is the version number or commit hash
Version = "0.0.0-unknown"
// SemVersion is the Semantic version
SemVersion semver.Version
// CommitHash is the commit this version was built on
CommitHash = "Unknown"
// CompileDate is the date this binary was compiled on
CompileDate = "Unknown"
// Debug logging
Debug = "OFF"
// FakeCursor is used to disable the terminal cursor and have micro
// draw its own (enabled for windows consoles where the cursor is slow)
FakeCursor = false
// Stdout is a buffer that is written to stdout when micro closes
Stdout *bytes.Buffer
// Sigterm is a channel where micro exits when written
Sigterm chan os.Signal
)
func init() {
var err error
SemVersion, err = semver.Make(Version)
if err != nil {
fmt.Println("Invalid version: ", Version, err)
}
_, wt := os.LookupEnv("WT_SESSION")
if runtime.GOOS == "windows" && !wt {
FakeCursor = true
}
Stdout = new(bytes.Buffer)
}
// SliceEnd returns a byte slice where the index is a rune index
// Slices off the start of the slice
func SliceEnd(slc []byte, index int) []byte {
len := len(slc)
i := 0
totalSize := 0
for totalSize < len {
if i >= index {
return slc[totalSize:]
}
_, _, size := DecodeCharacter(slc[totalSize:])
totalSize += size
i++
}
return slc[totalSize:]
}
// SliceEndStr is the same as SliceEnd but for strings
func SliceEndStr(str string, index int) string {
len := len(str)
i := 0
totalSize := 0
for totalSize < len {
if i >= index {
return str[totalSize:]
}
_, _, size := DecodeCharacterInString(str[totalSize:])
totalSize += size
i++
}
return str[totalSize:]
}
// SliceStart returns a byte slice where the index is a rune index
// Slices off the end of the slice
func SliceStart(slc []byte, index int) []byte {
len := len(slc)
i := 0
totalSize := 0
for totalSize < len {
if i >= index {
return slc[:totalSize]
}
_, _, size := DecodeCharacter(slc[totalSize:])
totalSize += size
i++
}
return slc[:totalSize]
}
// SliceStartStr is the same as SliceStart but for strings
func SliceStartStr(str string, index int) string {
len := len(str)
i := 0
totalSize := 0
for totalSize < len {
if i >= index {
return str[:totalSize]
}
_, _, size := DecodeCharacterInString(str[totalSize:])
totalSize += size
i++
}
return str[:totalSize]
}
// SliceVisualEnd will take a byte slice and slice off the start
// up to a given visual index. If the index is in the middle of a
// rune the number of visual columns into the rune will be returned
// It will also return the char pos of the first character of the slice
func SliceVisualEnd(b []byte, n, tabsize int) ([]byte, int, int) {
width := 0
i := 0
for len(b) > 0 {
r, _, size := DecodeCharacter(b)
w := 0
switch r {
case '\t':
ts := tabsize - (width % tabsize)
w = ts
default:
w = runewidth.RuneWidth(r)
}
if width+w > n {
return b, n - width, i
}
width += w
b = b[size:]
i++
}
return b, n - width, i
}
// Abs is a simple absolute value function for ints
func Abs(n int) int {
if n < 0 {
return -n
}
return n
}
// StringWidth returns the visual width of a byte array indexed from 0 to n (rune index)
// with a given tabsize
func StringWidth(b []byte, n, tabsize int) int {
if n <= 0 {
return 0
}
i := 0
width := 0
for len(b) > 0 {
r, _, size := DecodeCharacter(b)
b = b[size:]
switch r {
case '\t':
ts := tabsize - (width % tabsize)
width += ts
default:
width += runewidth.RuneWidth(r)
}
i++
if i == n {
return width
}
}
return width
}
// 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
}
// FSize gets the size of a file
func FSize(f *os.File) int64 {
fi, _ := f.Stat()
return fi.Size()
}
// IsWordChar returns whether or not a rune is a 'word character'
// Word characters are defined as numbers, letters or sub-word delimiters
func IsWordChar(r rune) bool {
return IsAlphanumeric(r) || IsSubwordDelimiter(r)
}
// IsNonWordChar returns whether or not a rune is not a 'word character'
// Non word characters are defined as all characters not being numbers, letters or sub-word delimiters
// See IsWordChar()
func IsNonWordChar(r rune) bool {
return !IsWordChar(r)
}
// IsUpperWordChar returns whether or not a rune is an 'upper word character'
// Upper word characters are defined as numbers, upper-case letters or sub-word delimiters
func IsUpperWordChar(r rune) bool {
return IsUpperAlphanumeric(r) || IsSubwordDelimiter(r)
}
// IsLowerWordChar returns whether or not a rune is a 'lower word character'
// Lower word characters are defined as numbers, lower-case letters or sub-word delimiters
func IsLowerWordChar(r rune) bool {
return IsLowerAlphanumeric(r) || IsSubwordDelimiter(r)
}
// IsSubwordDelimiter returns whether or not a rune is a 'sub-word delimiter character'
// i.e. is considered a part of the word and is used as a delimiter between sub-words of the word.
// For now the only sub-word delimiter character is '_'.
func IsSubwordDelimiter(r rune) bool {
return r == '_'
}
// IsAlphanumeric returns whether or not a rune is an 'alphanumeric character'
// Alphanumeric characters are defined as numbers or letters
func IsAlphanumeric(r rune) bool {
return unicode.IsLetter(r) || unicode.IsNumber(r)
}
// IsUpperAlphanumeric returns whether or not a rune is an 'upper alphanumeric character'
// Upper alphanumeric characters are defined as numbers or upper-case letters
func IsUpperAlphanumeric(r rune) bool {
return IsUpperLetter(r) || unicode.IsNumber(r)
}
// IsLowerAlphanumeric returns whether or not a rune is a 'lower alphanumeric character'
// Lower alphanumeric characters are defined as numbers or lower-case letters
func IsLowerAlphanumeric(r rune) bool {
return IsLowerLetter(r) || unicode.IsNumber(r)
}
// IsUpperLetter returns whether or not a rune is an 'upper letter character'
// Upper letter characters are defined as upper-case letters
func IsUpperLetter(r rune) bool {
// unicode.IsUpper() returns true for letters only
return unicode.IsUpper(r)
}
// IsLowerLetter returns whether or not a rune is a 'lower letter character'
// Lower letter characters are defined as lower-case letters
func IsLowerLetter(r rune) bool {
// unicode.IsLower() returns true for letters only
return unicode.IsLower(r)
}
// Spaces returns a string with n spaces
func Spaces(n int) string {
return strings.Repeat(" ", n)
}
// IsSpaces checks if a given string is only spaces
func IsSpaces(str []byte) bool {
for _, c := range str {
if c != ' ' {
return false
}
}
return true
}
// IsSpacesOrTabs checks if a given string contains only spaces and tabs
func IsSpacesOrTabs(str []byte) bool {
for _, c := range str {
if c != ' ' && c != '\t' {
return false
}
}
return true
}
// IsWhitespace returns true if the given rune is a space, tab, or newline
func IsWhitespace(c rune) bool {
return unicode.IsSpace(c)
}
// IsBytesWhitespace returns true if the given bytes are all whitespace
func IsBytesWhitespace(b []byte) bool {
for _, c := range b {
if !IsWhitespace(rune(c)) {
return false
}
}
return true
}
// RunePos returns the rune index of a given byte index
// Make sure the byte index is not between code points
func RunePos(b []byte, i int) int {
return CharacterCount(b[:i])
}
// MakeRelative will attempt to make a relative path between path and base
func MakeRelative(path, base string) (string, error) {
if len(path) > 0 {
rel, err := filepath.Rel(base, path)
if err != nil {
return path, err
}
return rel, nil
}
return path, nil
}
// ReplaceHome takes a path as input and replaces ~ at the start of the path with the user's
// home directory. Does nothing if the path does not start with '~'.
func ReplaceHome(path string) (string, error) {
if !strings.HasPrefix(path, "~") {
return path, nil
}
var userData *user.User
var err error
homeString := strings.Split(path, "/")[0]
if homeString == "~" {
userData, err = user.Current()
if err != nil {
return "", errors.New("Could not find user: " + err.Error())
}
} else {
userData, err = user.Lookup(homeString[1:])
if err != nil {
return "", errors.New("Could not find user: " + err.Error())
}
}
home := userData.HomeDir
return strings.Replace(path, homeString, home, 1), nil
}
// GetPathAndCursorPosition returns a filename without everything following a `:`
// This is used for opening files like util.go:10:5 to specify a line and column
// Special cases like Windows Absolute path (C:\myfile.txt:10:5) are handled correctly.
func GetPathAndCursorPosition(path string) (string, []string) {
re := regexp.MustCompile(`([\s\S]+?)(?::(\d+))(?::(\d+))?$`)
match := re.FindStringSubmatch(path)
// no lines/columns were specified in the path, return just the path with no cursor location
if len(match) == 0 {
return path, nil
} else if match[len(match)-1] != "" {
// if the last capture group match isn't empty then both line and column were provided
return match[1], match[2:]
}
// if it was empty, then only a line was provided, so default to column 0
return match[1], []string{match[2], "0"}
}
// GetModTime returns the last modification time for a given file
func GetModTime(path string) (time.Time, error) {
info, err := os.Stat(path)
if err != nil {
return time.Now(), err
}
return info.ModTime(), nil
}
// EscapePath replaces every path separator in a given path with a %
func EscapePath(path string) string {
path = filepath.ToSlash(path)
if runtime.GOOS == "windows" {
// ':' is not valid in a path name on Windows but is ok on Unix
path = strings.ReplaceAll(path, ":", "%")
}
return strings.ReplaceAll(path, "/", "%")
}
// GetLeadingWhitespace returns the leading whitespace of the given byte array
func GetLeadingWhitespace(b []byte) []byte {
ws := []byte{}
for len(b) > 0 {
r, _, size := DecodeCharacter(b)
if r == ' ' || r == '\t' {
ws = append(ws, byte(r))
} else {
break
}
b = b[size:]
}
return ws
}
// GetTrailingWhitespace returns the trailing whitespace of the given byte array
func GetTrailingWhitespace(b []byte) []byte {
ws := []byte{}
for len(b) > 0 {
r, size := utf8.DecodeLastRune(b)
if IsWhitespace(r) {
ws = append([]byte(string(r)), ws...)
} else {
break
}
b = b[:len(b)-size]
}
return ws
}
// HasTrailingWhitespace returns true if the given byte array ends with a whitespace
func HasTrailingWhitespace(b []byte) bool {
r, _ := utf8.DecodeLastRune(b)
return IsWhitespace(r)
}
// IntOpt turns a float64 setting to an int
func IntOpt(opt interface{}) int {
return int(opt.(float64))
}
// GetCharPosInLine gets the char position of a visual x y
// coordinate (this is necessary because tabs are 1 char but
// 4 visual spaces)
func GetCharPosInLine(b []byte, visualPos int, tabsize int) int {
// Scan rune by rune until we exceed the visual width that we are
// looking for. Then we can return the character position we have found
i := 0 // char pos
width := 0 // string visual width
for len(b) > 0 {
r, _, size := DecodeCharacter(b)
b = b[size:]
switch r {
case '\t':
ts := tabsize - (width % tabsize)
width += ts
default:
width += runewidth.RuneWidth(r)
}
if width >= visualPos {
if width == visualPos {
i++
}
break
}
i++
}
return i
}
// ParseBool is almost exactly like strconv.ParseBool, except it also accepts 'on' and 'off'
// as 'true' and 'false' respectively
func ParseBool(str string) (bool, error) {
if str == "on" {
return true, nil
}
if str == "off" {
return false, nil
}
return strconv.ParseBool(str)
}
// Clamp clamps a value between min and max
func Clamp(val, min, max int) int {
if val < min {
val = min
} else if val > max {
val = max
}
return val
}
// IsAutocomplete returns whether a character should begin an autocompletion.
func IsAutocomplete(c rune) bool {
return c == '.' || IsWordChar(c)
}
// ParseSpecial replaces escaped ts with '\t'.
func ParseSpecial(s string) string {
return strings.ReplaceAll(s, "\\t", "\t")
}
// String converts a byte array to a string (for lua plugins)
func String(s []byte) string {
return string(s)
}
// Unzip unzips a file to given folder
func Unzip(src, dest string) error {
r, err := zip.OpenReader(src)
if err != nil {
return err
}
defer r.Close()
os.MkdirAll(dest, 0755)
// Closure to address file descriptors issue with all the deferred .Close() methods
extractAndWriteFile := func(f *zip.File) error {
rc, err := f.Open()
if err != nil {
return err
}
defer rc.Close()
path := filepath.Join(dest, f.Name)
// Check for ZipSlip (Directory traversal)
if !strings.HasPrefix(path, filepath.Clean(dest)+string(os.PathSeparator)) {
return fmt.Errorf("illegal file path: %s", path)
}
if f.FileInfo().IsDir() {
os.MkdirAll(path, f.Mode())
} else {
os.MkdirAll(filepath.Dir(path), f.Mode())
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())
if err != nil {
return err
}
defer f.Close()
_, err = io.Copy(f, rc)
if err != nil {
return err
}
}
return nil
}
for _, f := range r.File {
err := extractAndWriteFile(f)
if err != nil {
return err
}
}
return nil
}
// HttpRequest returns a new http.Client for making custom requests (for lua plugins)
func HttpRequest(method string, url string, headers []string) (resp *http.Response, err error) {
client := http.Client{}
req, err := http.NewRequest(method, url, nil)
if err != nil {
return nil, err
}
for i := 0; i < len(headers); i += 2 {
req.Header.Add(headers[i], headers[i+1])
}
return client.Do(req)
}
```
|
/content/code_sandbox/internal/util/util.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 3,872
|
```go
package util
import (
"fmt"
"log"
"runtime"
"time"
humanize "github.com/dustin/go-humanize"
)
// GetMemStats returns a string describing the memory usage and gc time used so far
func GetMemStats() string {
var memstats runtime.MemStats
runtime.ReadMemStats(&memstats)
return fmt.Sprintf("Alloc: %s, Sys: %s, GC: %d, PauseTotalNs: %dns", humanize.Bytes(memstats.Alloc), humanize.Bytes(memstats.Sys), memstats.NumGC, memstats.PauseTotalNs)
}
func Tic(s string) time.Time {
log.Println("START:", s)
return time.Now()
}
func Toc(start time.Time) {
end := time.Now()
log.Println("END: ElapsedTime in seconds:", end.Sub(start))
}
```
|
/content/code_sandbox/internal/util/profile.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 177
|
```go
package util
// LuaRuneAt is a helper function for lua plugins to return the rune
// at an index within a string
func LuaRuneAt(str string, runeidx int) string {
i := 0
for len(str) > 0 {
r, _, size := DecodeCharacterInString(str)
str = str[size:]
if i == runeidx {
return string(r)
}
i++
}
return ""
}
// LuaGetLeadingWhitespace returns the leading whitespace of a string (used by lua plugins)
func LuaGetLeadingWhitespace(s string) string {
ws := []byte{}
for len(s) > 0 {
r, _, size := DecodeCharacterInString(s)
if r == ' ' || r == '\t' {
ws = append(ws, byte(r))
} else {
break
}
s = s[size:]
}
return string(ws)
}
// LuaIsWordChar returns true if the first rune in a string is a word character
func LuaIsWordChar(s string) bool {
r, _, _ := DecodeCharacterInString(s)
return IsWordChar(r)
}
```
|
/content/code_sandbox/internal/util/lua.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 245
|
```go
package util
import (
"unicode"
"unicode/utf8"
)
// Unicode is annoying. A "code point" (rune in Go-speak) may need up to
// 4 bytes to represent it. In general, a code point will represent a
// complete character, but this is not always the case. A character with
// accents may be made up of multiple code points (the code point for the
// original character, and additional code points for each accent/marking).
// The functions below are meant to help deal with these additional "combining"
// code points. In underlying operations (search, replace, etc...), micro will
// treat a character with combining code points as just the original code point.
// For rendering, micro will display the combining characters. It's not perfect
// but it's pretty good.
var minMark = rune(unicode.Mark.R16[0].Lo)
func isMark(r rune) bool {
// Fast path
if r < minMark {
return false
}
return unicode.In(r, unicode.Mark)
}
// DecodeCharacter returns the next character from an array of bytes
// A character is a rune along with any accompanying combining runes
func DecodeCharacter(b []byte) (rune, []rune, int) {
r, size := utf8.DecodeRune(b)
b = b[size:]
c, s := utf8.DecodeRune(b)
var combc []rune
for isMark(c) {
combc = append(combc, c)
size += s
b = b[s:]
c, s = utf8.DecodeRune(b)
}
return r, combc, size
}
// DecodeCharacterInString returns the next character from a string
// A character is a rune along with any accompanying combining runes
func DecodeCharacterInString(str string) (rune, []rune, int) {
r, size := utf8.DecodeRuneInString(str)
str = str[size:]
c, s := utf8.DecodeRuneInString(str)
var combc []rune
for isMark(c) {
combc = append(combc, c)
size += s
str = str[s:]
c, s = utf8.DecodeRuneInString(str)
}
return r, combc, size
}
// CharacterCount returns the number of characters in a byte array
// Similar to utf8.RuneCount but for unicode characters
func CharacterCount(b []byte) int {
s := 0
for len(b) > 0 {
r, size := utf8.DecodeRune(b)
if !isMark(r) {
s++
}
b = b[size:]
}
return s
}
// CharacterCount returns the number of characters in a string
// Similar to utf8.RuneCountInString but for unicode characters
func CharacterCountInString(str string) int {
s := 0
for _, r := range str {
if !isMark(r) {
s++
}
}
return s
}
```
|
/content/code_sandbox/internal/util/unicode.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 645
|
```go
package display
import (
"github.com/zyedidia/micro/v2/internal/buffer"
)
type View struct {
X, Y int // X,Y location of the view
Width, Height int // Width and height of the view
// Start line of the view (for vertical scroll)
StartLine SLoc
// Start column of the view (for horizontal scroll)
// note that since the starting column of every line is different if the view
// is scrolled, StartCol is a visual index (will be the same for every line)
StartCol int
}
type Window interface {
Display()
Clear()
Relocate() bool
GetView() *View
SetView(v *View)
LocFromVisual(vloc buffer.Loc) buffer.Loc
Resize(w, h int)
SetActive(b bool)
IsActive() bool
}
type BWindow interface {
Window
SoftWrap
SetBuffer(b *buffer.Buffer)
BufView() View
}
```
|
/content/code_sandbox/internal/display/window.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 209
|
```go
package display
import (
"bytes"
"fmt"
"regexp"
"strconv"
"strings"
luar "layeh.com/gopher-luar"
runewidth "github.com/mattn/go-runewidth"
lua "github.com/yuin/gopher-lua"
"github.com/zyedidia/micro/v2/internal/buffer"
"github.com/zyedidia/micro/v2/internal/config"
ulua "github.com/zyedidia/micro/v2/internal/lua"
"github.com/zyedidia/micro/v2/internal/screen"
"github.com/zyedidia/micro/v2/internal/util"
)
// StatusLine represents the information line at the bottom
// of each window
// It gives information such as filename, whether the file has been
// modified, filetype, cursor location
type StatusLine struct {
Info map[string]func(*buffer.Buffer) string
win *BufWindow
}
var statusInfo = map[string]func(*buffer.Buffer) string{
"filename": func(b *buffer.Buffer) string {
return b.GetName()
},
"line": func(b *buffer.Buffer) string {
return strconv.Itoa(b.GetActiveCursor().Y + 1)
},
"col": func(b *buffer.Buffer) string {
return strconv.Itoa(b.GetActiveCursor().X + 1)
},
"modified": func(b *buffer.Buffer) string {
if b.Modified() {
return "+ "
}
if b.Type.Readonly {
return "[ro] "
}
return ""
},
"lines": func(b *buffer.Buffer) string {
return strconv.Itoa(b.LinesNum())
},
"percentage": func(b *buffer.Buffer) string {
return strconv.Itoa((b.GetActiveCursor().Y + 1) * 100 / b.LinesNum())
},
}
func SetStatusInfoFnLua(fn string) {
luaFn := strings.Split(fn, ".")
if len(luaFn) <= 1 {
return
}
plName, plFn := luaFn[0], luaFn[1]
pl := config.FindPlugin(plName)
if pl == nil {
return
}
statusInfo[fn] = func(b *buffer.Buffer) string {
if pl == nil || !pl.IsLoaded() {
return ""
}
val, err := pl.Call(plFn, luar.New(ulua.L, b))
if err == nil {
if v, ok := val.(lua.LString); !ok {
screen.TermMessage(plFn, "should return a string")
return ""
} else {
return string(v)
}
}
return ""
}
}
// NewStatusLine returns a statusline bound to a window
func NewStatusLine(win *BufWindow) *StatusLine {
s := new(StatusLine)
s.win = win
return s
}
// FindOpt finds a given option in the current buffer's settings
func (s *StatusLine) FindOpt(opt string) interface{} {
if val, ok := s.win.Buf.Settings[opt]; ok {
return val
}
return "null"
}
var formatParser = regexp.MustCompile(`\$\(.+?\)`)
// Display draws the statusline to the screen
func (s *StatusLine) Display() {
// We'll draw the line at the lowest line in the window
y := s.win.Height + s.win.Y - 1
winX := s.win.X
b := s.win.Buf
// autocomplete suggestions (for the buffer, not for the infowindow)
if b.HasSuggestions && len(b.Suggestions) > 1 {
statusLineStyle := config.DefStyle.Reverse(true)
if style, ok := config.Colorscheme["statusline.suggestions"]; ok {
statusLineStyle = style
} else if style, ok := config.Colorscheme["statusline"]; ok {
statusLineStyle = style
}
x := 0
for j, sug := range b.Suggestions {
style := statusLineStyle
if b.CurSuggestion == j {
style = style.Reverse(true)
}
for _, r := range sug {
screen.SetContent(winX+x, y, r, nil, style)
x++
if x >= s.win.Width {
return
}
}
screen.SetContent(winX+x, y, ' ', nil, statusLineStyle)
x++
if x >= s.win.Width {
return
}
}
for x < s.win.Width {
screen.SetContent(winX+x, y, ' ', nil, statusLineStyle)
x++
}
return
}
formatter := func(match []byte) []byte {
name := match[2 : len(match)-1]
if bytes.HasPrefix(name, []byte("opt")) {
option := name[4:]
return []byte(fmt.Sprint(s.FindOpt(string(option))))
} else if bytes.HasPrefix(name, []byte("bind")) {
binding := string(name[5:])
for k, v := range config.Bindings["buffer"] {
if v == binding {
return []byte(k)
}
}
return []byte("null")
} else {
if fn, ok := statusInfo[string(name)]; ok {
return []byte(fn(s.win.Buf))
}
return []byte{}
}
}
leftText := []byte(s.win.Buf.Settings["statusformatl"].(string))
leftText = formatParser.ReplaceAllFunc(leftText, formatter)
rightText := []byte(s.win.Buf.Settings["statusformatr"].(string))
rightText = formatParser.ReplaceAllFunc(rightText, formatter)
statusLineStyle := config.DefStyle.Reverse(true)
if s.win.IsActive() {
if style, ok := config.Colorscheme["statusline"]; ok {
statusLineStyle = style
}
} else {
if style, ok := config.Colorscheme["statusline.inactive"]; ok {
statusLineStyle = style
} else if style, ok := config.Colorscheme["statusline"]; ok {
statusLineStyle = style
}
}
leftLen := util.StringWidth(leftText, util.CharacterCount(leftText), 1)
rightLen := util.StringWidth(rightText, util.CharacterCount(rightText), 1)
for x := 0; x < s.win.Width; x++ {
if x < leftLen {
r, combc, size := util.DecodeCharacter(leftText)
leftText = leftText[size:]
rw := runewidth.RuneWidth(r)
for j := 0; j < rw; j++ {
c := r
if j > 0 {
c = ' '
combc = nil
x++
}
screen.SetContent(winX+x, y, c, combc, statusLineStyle)
}
} else if x >= s.win.Width-rightLen && x < rightLen+s.win.Width-rightLen {
r, combc, size := util.DecodeCharacter(rightText)
rightText = rightText[size:]
rw := runewidth.RuneWidth(r)
for j := 0; j < rw; j++ {
c := r
if j > 0 {
c = ' '
combc = nil
x++
}
screen.SetContent(winX+x, y, c, combc, statusLineStyle)
}
} else {
screen.SetContent(winX+x, y, ' ', nil, statusLineStyle)
}
}
}
```
|
/content/code_sandbox/internal/display/statusline.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 1,603
|
```go
package display
import (
"github.com/zyedidia/micro/v2/internal/buffer"
"github.com/zyedidia/micro/v2/internal/config"
"github.com/zyedidia/micro/v2/internal/screen"
"github.com/zyedidia/micro/v2/internal/util"
"github.com/zyedidia/micro/v2/internal/views"
)
type UIWindow struct {
root *views.Node
}
func NewUIWindow(n *views.Node) *UIWindow {
uw := new(UIWindow)
uw.root = n
return uw
}
func (w *UIWindow) drawNode(n *views.Node) {
cs := n.Children()
dividerStyle := config.DefStyle
if style, ok := config.Colorscheme["divider"]; ok {
dividerStyle = style
}
divchars := config.GetGlobalOption("divchars").(string)
if util.CharacterCountInString(divchars) != 2 {
divchars = "|-"
}
divchar, combc, _ := util.DecodeCharacterInString(divchars)
divreverse := config.GetGlobalOption("divreverse").(bool)
if divreverse {
dividerStyle = dividerStyle.Reverse(true)
}
for i, c := range cs {
if c.Kind == views.STVert {
if i != len(cs)-1 {
for h := 0; h < c.H; h++ {
screen.SetContent(c.X+c.W, c.Y+h, divchar, combc, dividerStyle)
}
}
}
w.drawNode(c)
}
}
func (w *UIWindow) Display() {
w.drawNode(w.root)
}
func (w *UIWindow) GetMouseSplitNode(vloc buffer.Loc) *views.Node {
var mouseLoc func(*views.Node) *views.Node
mouseLoc = func(n *views.Node) *views.Node {
cs := n.Children()
for i, c := range cs {
if c.Kind == views.STVert {
if i != len(cs)-1 {
if vloc.X == c.X+c.W && vloc.Y >= c.Y && vloc.Y < c.Y+c.H {
return c
}
}
} else if c.Kind == views.STHoriz {
if i != len(cs)-1 {
if vloc.Y == c.Y+c.H-1 && vloc.X >= c.X && vloc.X < c.X+c.W {
return c
}
}
}
}
for _, c := range cs {
m := mouseLoc(c)
if m != nil {
return m
}
}
return nil
}
return mouseLoc(w.root)
}
func (w *UIWindow) Resize(width, height int) {}
func (w *UIWindow) SetActive(b bool) {}
```
|
/content/code_sandbox/internal/display/uiwindow.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 603
|
```go
package display
import (
"github.com/zyedidia/micro/v2/internal/buffer"
"github.com/zyedidia/micro/v2/internal/config"
"github.com/zyedidia/micro/v2/internal/screen"
"github.com/zyedidia/micro/v2/internal/shell"
"github.com/zyedidia/micro/v2/internal/util"
"github.com/zyedidia/tcell/v2"
"github.com/zyedidia/terminal"
)
type TermWindow struct {
*View
*shell.Terminal
active bool
}
func NewTermWindow(x, y, w, h int, term *shell.Terminal) *TermWindow {
tw := new(TermWindow)
tw.View = new(View)
tw.Terminal = term
tw.X, tw.Y = x, y
tw.Resize(w, h)
return tw
}
// Resize informs the terminal of a resize event
func (w *TermWindow) Resize(width, height int) {
if config.GetGlobalOption("statusline").(bool) {
height--
}
w.Term.Resize(width, height)
w.Width, w.Height = width, height
}
func (w *TermWindow) SetActive(b bool) {
w.active = b
}
func (w *TermWindow) IsActive() bool {
return w.active
}
func (w *TermWindow) LocFromVisual(vloc buffer.Loc) buffer.Loc {
return vloc
}
func (w *TermWindow) Clear() {
for y := 0; y < w.Height; y++ {
for x := 0; x < w.Width; x++ {
screen.SetContent(w.X+x, w.Y+y, ' ', nil, config.DefStyle)
}
}
}
func (w *TermWindow) Relocate() bool { return true }
func (w *TermWindow) GetView() *View {
return w.View
}
func (w *TermWindow) SetView(v *View) {
w.View = v
}
// Display displays this terminal in a view
func (w *TermWindow) Display() {
w.State.Lock()
defer w.State.Unlock()
var l buffer.Loc
for y := 0; y < w.Height; y++ {
for x := 0; x < w.Width; x++ {
l.X, l.Y = x, y
c, f, b := w.State.Cell(x, y)
fg, bg := int(f), int(b)
if f == terminal.DefaultFG {
fg = int(tcell.ColorDefault)
}
if b == terminal.DefaultBG {
bg = int(tcell.ColorDefault)
}
st := tcell.StyleDefault.Foreground(config.GetColor256(fg)).Background(config.GetColor256(bg))
if l.LessThan(w.Selection[1]) && l.GreaterEqual(w.Selection[0]) || l.LessThan(w.Selection[0]) && l.GreaterEqual(w.Selection[1]) {
st = st.Reverse(true)
}
screen.SetContent(w.X+x, w.Y+y, c, nil, st)
}
}
if config.GetGlobalOption("statusline").(bool) {
statusLineStyle := config.DefStyle.Reverse(true)
if style, ok := config.Colorscheme["statusline"]; ok {
statusLineStyle = style
}
text := []byte(w.Name())
textLen := util.CharacterCount(text)
for x := 0; x < w.Width; x++ {
if x < textLen {
r, combc, size := util.DecodeCharacter(text)
text = text[size:]
screen.SetContent(w.X+x, w.Y+w.Height, r, combc, statusLineStyle)
} else {
screen.SetContent(w.X+x, w.Y+w.Height, ' ', nil, statusLineStyle)
}
}
}
if w.State.CursorVisible() && w.active {
curx, cury := w.State.Cursor()
if curx < w.Width && cury < w.Height {
screen.ShowCursor(curx+w.X, cury+w.Y)
}
}
}
```
|
/content/code_sandbox/internal/display/termwindow.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 878
|
```go
package display
import (
runewidth "github.com/mattn/go-runewidth"
"github.com/zyedidia/micro/v2/internal/buffer"
"github.com/zyedidia/micro/v2/internal/config"
"github.com/zyedidia/micro/v2/internal/info"
"github.com/zyedidia/micro/v2/internal/screen"
"github.com/zyedidia/micro/v2/internal/util"
"github.com/zyedidia/tcell/v2"
)
type InfoWindow struct {
*info.InfoBuf
*View
hscroll int
}
func (i *InfoWindow) errStyle() tcell.Style {
errStyle := config.DefStyle.
Foreground(tcell.ColorBlack).
Background(tcell.ColorMaroon)
if _, ok := config.Colorscheme["error-message"]; ok {
errStyle = config.Colorscheme["error-message"]
}
return errStyle
}
func (i *InfoWindow) defStyle() tcell.Style {
defStyle := config.DefStyle
if _, ok := config.Colorscheme["message"]; ok {
defStyle = config.Colorscheme["message"]
}
return defStyle
}
func NewInfoWindow(b *info.InfoBuf) *InfoWindow {
iw := new(InfoWindow)
iw.InfoBuf = b
iw.View = new(View)
iw.Width, iw.Y = screen.Screen.Size()
iw.Y--
return iw
}
func (i *InfoWindow) Resize(w, h int) {
i.Width = w
i.Y = h
}
func (i *InfoWindow) SetBuffer(b *buffer.Buffer) {
i.InfoBuf.Buffer = b
}
func (i *InfoWindow) Relocate() bool { return false }
func (i *InfoWindow) GetView() *View { return i.View }
func (i *InfoWindow) SetView(v *View) {}
func (i *InfoWindow) SetActive(b bool) {}
func (i *InfoWindow) IsActive() bool { return true }
func (i *InfoWindow) LocFromVisual(vloc buffer.Loc) buffer.Loc {
c := i.Buffer.GetActiveCursor()
l := i.Buffer.LineBytes(0)
n := util.CharacterCountInString(i.Msg)
return buffer.Loc{c.GetCharPosInLine(l, vloc.X-n), 0}
}
func (i *InfoWindow) BufView() View {
return View{
X: 0,
Y: i.Y,
Width: i.Width,
Height: 1,
StartLine: SLoc{0, 0},
StartCol: 0,
}
}
func (i *InfoWindow) Scroll(s SLoc, n int) SLoc { return s }
func (i *InfoWindow) Diff(s1, s2 SLoc) int { return 0 }
func (i *InfoWindow) SLocFromLoc(loc buffer.Loc) SLoc { return SLoc{0, 0} }
func (i *InfoWindow) VLocFromLoc(loc buffer.Loc) VLoc { return VLoc{SLoc{0, 0}, loc.X} }
func (i *InfoWindow) LocFromVLoc(vloc VLoc) buffer.Loc { return buffer.Loc{vloc.VisualX, 0} }
func (i *InfoWindow) Clear() {
for x := 0; x < i.Width; x++ {
screen.SetContent(x, i.Y, ' ', nil, i.defStyle())
}
}
func (i *InfoWindow) displayBuffer() {
b := i.Buffer
line := b.LineBytes(0)
activeC := b.GetActiveCursor()
blocX := 0
vlocX := util.CharacterCountInString(i.Msg)
tabsize := 4
line, nColsBeforeStart, bslice := util.SliceVisualEnd(line, blocX, tabsize)
blocX = bslice
draw := func(r rune, combc []rune, style tcell.Style) {
if nColsBeforeStart <= 0 {
bloc := buffer.Loc{X: blocX, Y: 0}
if activeC.HasSelection() &&
(bloc.GreaterEqual(activeC.CurSelection[0]) && bloc.LessThan(activeC.CurSelection[1]) ||
bloc.LessThan(activeC.CurSelection[0]) && bloc.GreaterEqual(activeC.CurSelection[1])) {
// The current character is selected
style = i.defStyle().Reverse(true)
if s, ok := config.Colorscheme["selection"]; ok {
style = s
}
}
rw := runewidth.RuneWidth(r)
for j := 0; j < rw; j++ {
c := r
if j > 0 {
c = ' '
combc = nil
}
screen.SetContent(vlocX, i.Y, c, combc, style)
}
vlocX++
}
nColsBeforeStart--
}
totalwidth := blocX - nColsBeforeStart
for len(line) > 0 {
curVX := vlocX
curBX := blocX
r, combc, size := util.DecodeCharacter(line)
draw(r, combc, i.defStyle())
width := 0
char := ' '
switch r {
case '\t':
ts := tabsize - (totalwidth % tabsize)
width = ts
default:
width = runewidth.RuneWidth(r)
char = '@'
}
blocX++
line = line[size:]
// Draw any extra characters either spaces for tabs or @ for incomplete wide runes
if width > 1 {
for j := 1; j < width; j++ {
draw(char, nil, i.defStyle())
}
}
if activeC.X == curBX {
screen.ShowCursor(curVX, i.Y)
}
totalwidth += width
if vlocX >= i.Width {
break
}
}
if activeC.X == blocX {
screen.ShowCursor(vlocX, i.Y)
}
}
var keydisplay = []string{"^Q Quit, ^S Save, ^O Open, ^G Help, ^E Command Bar, ^K Cut Line", "^F Find, ^Z Undo, ^Y Redo, ^A Select All, ^D Duplicate Line, ^T New Tab"}
func (i *InfoWindow) displayKeyMenu() {
// TODO: maybe make this based on the actual keybindings
for y := 0; y < len(keydisplay); y++ {
for x := 0; x < i.Width; x++ {
if x < len(keydisplay[y]) {
screen.SetContent(x, i.Y-len(keydisplay)+y, rune(keydisplay[y][x]), nil, i.defStyle())
} else {
screen.SetContent(x, i.Y-len(keydisplay)+y, ' ', nil, i.defStyle())
}
}
}
}
func (i *InfoWindow) totalSize() int {
sum := 0
for _, n := range i.Suggestions {
sum += runewidth.StringWidth(n) + 1
}
return sum
}
func (i *InfoWindow) scrollToSuggestion() {
x := 0
s := i.totalSize()
for j, n := range i.Suggestions {
c := util.CharacterCountInString(n)
if j == i.CurSuggestion {
if x+c >= i.hscroll+i.Width {
i.hscroll = util.Clamp(x+c+1-i.Width, 0, s-i.Width)
} else if x < i.hscroll {
i.hscroll = util.Clamp(x-1, 0, s-i.Width)
}
break
}
x += c + 1
}
if s-i.Width <= 0 {
i.hscroll = 0
}
}
func (i *InfoWindow) Display() {
if i.HasPrompt || config.GlobalSettings["infobar"].(bool) {
i.Clear()
x := 0
if config.GetGlobalOption("keymenu").(bool) {
i.displayKeyMenu()
}
if !i.HasPrompt && !i.HasMessage && !i.HasError {
return
}
i.Clear()
style := i.defStyle()
if i.HasError {
style = i.errStyle()
}
display := i.Msg
for _, c := range display {
screen.SetContent(x, i.Y, c, nil, style)
x += runewidth.RuneWidth(c)
}
if i.HasPrompt {
i.displayBuffer()
}
}
if i.HasSuggestions && len(i.Suggestions) > 1 {
i.scrollToSuggestion()
x := -i.hscroll
done := false
statusLineStyle := config.DefStyle.Reverse(true)
if style, ok := config.Colorscheme["statusline.suggestions"]; ok {
statusLineStyle = style
} else if style, ok := config.Colorscheme["statusline"]; ok {
statusLineStyle = style
}
keymenuOffset := 0
if config.GetGlobalOption("keymenu").(bool) {
keymenuOffset = len(keydisplay)
}
draw := func(r rune, s tcell.Style) {
y := i.Y - keymenuOffset - 1
rw := runewidth.RuneWidth(r)
for j := 0; j < rw; j++ {
c := r
if j > 0 {
c = ' '
}
if x == i.Width-1 && !done {
screen.SetContent(i.Width-1, y, '>', nil, s)
x++
break
} else if x == 0 && i.hscroll > 0 {
screen.SetContent(0, y, '<', nil, s)
} else if x >= 0 && x < i.Width {
screen.SetContent(x, y, c, nil, s)
}
x++
}
}
for j, s := range i.Suggestions {
style := statusLineStyle
if i.CurSuggestion == j {
style = style.Reverse(true)
}
for _, r := range s {
draw(r, style)
// screen.SetContent(x, i.Y-keymenuOffset-1, r, nil, style)
}
draw(' ', statusLineStyle)
}
for x < i.Width {
draw(' ', statusLineStyle)
}
}
}
```
|
/content/code_sandbox/internal/display/infowindow.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 2,290
|
```go
package display
import (
runewidth "github.com/mattn/go-runewidth"
"github.com/zyedidia/tcell/v2"
"github.com/zyedidia/micro/v2/internal/buffer"
"github.com/zyedidia/micro/v2/internal/config"
"github.com/zyedidia/micro/v2/internal/screen"
"github.com/zyedidia/micro/v2/internal/util"
)
type TabWindow struct {
Names []string
active int
Y int
Width int
hscroll int
}
func NewTabWindow(w int, y int) *TabWindow {
tw := new(TabWindow)
tw.Width = w
tw.Y = y
return tw
}
func (w *TabWindow) Resize(width, height int) {
w.Width = width
}
func (w *TabWindow) LocFromVisual(vloc buffer.Loc) int {
x := -w.hscroll
for i, n := range w.Names {
x++
s := util.CharacterCountInString(n)
if vloc.Y == w.Y && vloc.X < x+s {
return i
}
x += s
x += 3
if x >= w.Width {
break
}
}
return -1
}
func (w *TabWindow) Scroll(amt int) {
w.hscroll += amt
s := w.TotalSize()
w.hscroll = util.Clamp(w.hscroll, 0, s-w.Width)
if s-w.Width <= 0 {
w.hscroll = 0
}
}
func (w *TabWindow) TotalSize() int {
sum := 2
for _, n := range w.Names {
sum += runewidth.StringWidth(n) + 4
}
return sum - 4
}
func (w *TabWindow) Active() int {
return w.active
}
func (w *TabWindow) SetActive(a int) {
w.active = a
x := 2
s := w.TotalSize()
for i, n := range w.Names {
c := util.CharacterCountInString(n)
if i == a {
if x+c >= w.hscroll+w.Width {
w.hscroll = util.Clamp(x+c+1-w.Width, 0, s-w.Width)
} else if x < w.hscroll {
w.hscroll = util.Clamp(x-4, 0, s-w.Width)
}
break
}
x += c + 4
}
if s-w.Width <= 0 {
w.hscroll = 0
}
}
func (w *TabWindow) Display() {
x := -w.hscroll
done := false
globalTabReverse := config.GetGlobalOption("tabreverse").(bool)
globalTabHighlight := config.GetGlobalOption("tabhighlight").(bool)
// xor of reverse and tab highlight to get tab character (as in filename and surrounding characters) reverse state
tabCharHighlight := (globalTabReverse || globalTabHighlight) && !(globalTabReverse && globalTabHighlight)
reverseStyles := func(reverse bool) (tcell.Style, tcell.Style) {
tabBarStyle := config.DefStyle.Reverse(reverse)
if style, ok := config.Colorscheme["tabbar"]; ok {
tabBarStyle = style
}
tabBarActiveStyle := tabBarStyle
if style, ok := config.Colorscheme["tabbar.active"]; ok {
tabBarActiveStyle = style
}
return tabBarStyle, tabBarActiveStyle
}
draw := func(r rune, n int, active bool, reversed bool) {
tabBarStyle, tabBarActiveStyle := reverseStyles(reversed)
style := tabBarStyle
if active {
style = tabBarActiveStyle
}
for i := 0; i < n; i++ {
rw := runewidth.RuneWidth(r)
for j := 0; j < rw; j++ {
c := r
if j > 0 {
c = ' '
}
if x == w.Width-1 && !done {
screen.SetContent(w.Width-1, w.Y, '>', nil, tabBarStyle)
x++
break
} else if x == 0 && w.hscroll > 0 {
screen.SetContent(0, w.Y, '<', nil, tabBarStyle)
} else if x >= 0 && x < w.Width {
screen.SetContent(x, w.Y, c, nil, style)
}
x++
}
}
}
for i, n := range w.Names {
if i == w.active {
draw('[', 1, true, tabCharHighlight)
} else {
draw(' ', 1, false, tabCharHighlight)
}
for _, c := range n {
draw(c, 1, i == w.active, tabCharHighlight)
}
if i == len(w.Names)-1 {
done = true
}
if i == w.active {
draw(']', 1, true, tabCharHighlight)
draw(' ', 2, true, globalTabReverse)
} else {
draw(' ', 1, false, tabCharHighlight)
draw(' ', 2, false, globalTabReverse)
}
if x >= w.Width {
break
}
}
if x < w.Width {
draw(' ', w.Width-x, false, globalTabReverse)
}
}
```
|
/content/code_sandbox/internal/display/tabwindow.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 1,180
|
```go
package display
import (
"strconv"
runewidth "github.com/mattn/go-runewidth"
"github.com/zyedidia/micro/v2/internal/buffer"
"github.com/zyedidia/micro/v2/internal/config"
"github.com/zyedidia/micro/v2/internal/screen"
"github.com/zyedidia/micro/v2/internal/util"
"github.com/zyedidia/tcell/v2"
)
// The BufWindow provides a way of displaying a certain section of a buffer.
type BufWindow struct {
*View
// Buffer being shown in this window
Buf *buffer.Buffer
active bool
sline *StatusLine
bufWidth int
bufHeight int
gutterOffset int
hasMessage bool
maxLineNumLength int
drawDivider bool
}
// NewBufWindow creates a new window at a location in the screen with a width and height
func NewBufWindow(x, y, width, height int, buf *buffer.Buffer) *BufWindow {
w := new(BufWindow)
w.View = new(View)
w.X, w.Y, w.Width, w.Height = x, y, width, height
w.SetBuffer(buf)
w.active = true
w.sline = NewStatusLine(w)
return w
}
// SetBuffer sets this window's buffer.
func (w *BufWindow) SetBuffer(b *buffer.Buffer) {
w.Buf = b
b.OptionCallback = func(option string, nativeValue interface{}) {
if option == "softwrap" {
if nativeValue.(bool) {
w.StartCol = 0
} else {
w.StartLine.Row = 0
}
}
if option == "softwrap" || option == "wordwrap" {
w.Relocate()
for _, c := range w.Buf.GetCursors() {
c.LastVisualX = c.GetVisualX()
}
}
}
b.GetVisualX = func(loc buffer.Loc) int {
return w.VLocFromLoc(loc).VisualX
}
}
// GetView gets the view.
func (w *BufWindow) GetView() *View {
return w.View
}
// GetView sets the view.
func (w *BufWindow) SetView(view *View) {
w.View = view
}
// Resize resizes this window.
func (w *BufWindow) Resize(width, height int) {
w.Width, w.Height = width, height
w.updateDisplayInfo()
w.Relocate()
}
// SetActive marks the window as active.
func (w *BufWindow) SetActive(b bool) {
w.active = b
}
// IsActive returns true if this window is active.
func (w *BufWindow) IsActive() bool {
return w.active
}
// BufView returns the width, height and x,y location of the actual buffer.
// It is not exactly the same as the whole window which also contains gutter,
// ruler, scrollbar and statusline.
func (w *BufWindow) BufView() View {
return View{
X: w.X + w.gutterOffset,
Y: w.Y,
Width: w.bufWidth,
Height: w.bufHeight,
StartLine: w.StartLine,
StartCol: w.StartCol,
}
}
func (w *BufWindow) updateDisplayInfo() {
b := w.Buf
w.drawDivider = false
if !b.Settings["statusline"].(bool) {
_, h := screen.Screen.Size()
infoY := h
if config.GetGlobalOption("infobar").(bool) {
infoY--
}
if w.Y+w.Height != infoY {
w.drawDivider = true
}
}
w.bufHeight = w.Height
if b.Settings["statusline"].(bool) || w.drawDivider {
w.bufHeight--
}
scrollbarWidth := 0
if w.Buf.Settings["scrollbar"].(bool) && w.Buf.LinesNum() > w.Height && w.Width > 0 {
scrollbarWidth = 1
}
w.hasMessage = len(b.Messages) > 0
// We need to know the string length of the largest line number
// so we can pad appropriately when displaying line numbers
w.maxLineNumLength = len(strconv.Itoa(b.LinesNum()))
w.gutterOffset = 0
if w.hasMessage {
w.gutterOffset += 2
}
if b.Settings["diffgutter"].(bool) {
w.gutterOffset++
}
if b.Settings["ruler"].(bool) {
w.gutterOffset += w.maxLineNumLength + 1
}
if w.gutterOffset > w.Width-scrollbarWidth {
w.gutterOffset = w.Width - scrollbarWidth
}
prevBufWidth := w.bufWidth
w.bufWidth = w.Width - w.gutterOffset - scrollbarWidth
if w.bufWidth != prevBufWidth && w.Buf.Settings["softwrap"].(bool) {
for _, c := range w.Buf.GetCursors() {
c.LastVisualX = c.GetVisualX()
}
}
}
func (w *BufWindow) getStartInfo(n, lineN int) ([]byte, int, int, *tcell.Style) {
tabsize := util.IntOpt(w.Buf.Settings["tabsize"])
width := 0
bloc := buffer.Loc{0, lineN}
b := w.Buf.LineBytes(lineN)
curStyle := config.DefStyle
var s *tcell.Style
for len(b) > 0 {
r, _, size := util.DecodeCharacter(b)
curStyle, found := w.getStyle(curStyle, bloc)
if found {
s = &curStyle
}
w := 0
switch r {
case '\t':
ts := tabsize - (width % tabsize)
w = ts
default:
w = runewidth.RuneWidth(r)
}
if width+w > n {
return b, n - width, bloc.X, s
}
width += w
b = b[size:]
bloc.X++
}
return b, n - width, bloc.X, s
}
// Clear resets all cells in this window to the default style
func (w *BufWindow) Clear() {
for y := 0; y < w.Height; y++ {
for x := 0; x < w.Width; x++ {
screen.SetContent(w.X+x, w.Y+y, ' ', nil, config.DefStyle)
}
}
}
// 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
// Returns true if the window location is moved
func (w *BufWindow) Relocate() bool {
b := w.Buf
height := w.bufHeight
ret := false
activeC := w.Buf.GetActiveCursor()
scrollmargin := int(b.Settings["scrollmargin"].(float64))
c := w.SLocFromLoc(activeC.Loc)
bStart := SLoc{0, 0}
bEnd := w.SLocFromLoc(b.End())
if c.LessThan(w.Scroll(w.StartLine, scrollmargin)) && c.GreaterThan(w.Scroll(bStart, scrollmargin-1)) {
w.StartLine = w.Scroll(c, -scrollmargin)
ret = true
} else if c.LessThan(w.StartLine) {
w.StartLine = c
ret = true
}
if c.GreaterThan(w.Scroll(w.StartLine, height-1-scrollmargin)) && c.LessEqual(w.Scroll(bEnd, -scrollmargin)) {
w.StartLine = w.Scroll(c, -height+1+scrollmargin)
ret = true
} else if c.GreaterThan(w.Scroll(bEnd, -scrollmargin)) && c.GreaterThan(w.Scroll(w.StartLine, height-1)) {
w.StartLine = w.Scroll(bEnd, -height+1)
ret = true
}
// horizontal relocation (scrolling)
if !b.Settings["softwrap"].(bool) {
cx := activeC.GetVisualX()
rw := runewidth.RuneWidth(activeC.RuneUnder(activeC.X))
if rw == 0 {
rw = 1 // tab or newline
}
if cx < w.StartCol {
w.StartCol = cx
ret = true
}
if cx+w.gutterOffset+rw > w.StartCol+w.Width {
w.StartCol = cx - w.Width + w.gutterOffset + rw
ret = true
}
}
return ret
}
// LocFromVisual takes a visual location (x and y position) and returns the
// position in the buffer corresponding to the visual location
// If the requested position does not correspond to a buffer location it returns
// the nearest position
func (w *BufWindow) LocFromVisual(svloc buffer.Loc) buffer.Loc {
vx := svloc.X - w.X - w.gutterOffset
if vx < 0 {
vx = 0
}
vloc := VLoc{
SLoc: w.Scroll(w.StartLine, svloc.Y-w.Y),
VisualX: vx + w.StartCol,
}
return w.LocFromVLoc(vloc)
}
func (w *BufWindow) drawGutter(vloc *buffer.Loc, bloc *buffer.Loc) {
char := ' '
s := config.DefStyle
for _, m := range w.Buf.Messages {
if m.Start.Y == bloc.Y || m.End.Y == bloc.Y {
s = m.Style()
char = '>'
break
}
}
for i := 0; i < 2 && vloc.X < w.gutterOffset; i++ {
screen.SetContent(w.X+vloc.X, w.Y+vloc.Y, char, nil, s)
vloc.X++
}
}
func (w *BufWindow) drawDiffGutter(backgroundStyle tcell.Style, softwrapped bool, vloc *buffer.Loc, bloc *buffer.Loc) {
if vloc.X >= w.gutterOffset {
return
}
symbol := ' '
styleName := ""
switch w.Buf.DiffStatus(bloc.Y) {
case buffer.DSAdded:
symbol = '\u258C' // Left half block
styleName = "diff-added"
case buffer.DSModified:
symbol = '\u258C' // Left half block
styleName = "diff-modified"
case buffer.DSDeletedAbove:
if !softwrapped {
symbol = '\u2594' // Upper one eighth block
styleName = "diff-deleted"
}
}
style := backgroundStyle
if s, ok := config.Colorscheme[styleName]; ok {
foreground, _, _ := s.Decompose()
style = style.Foreground(foreground)
}
screen.SetContent(w.X+vloc.X, w.Y+vloc.Y, symbol, nil, style)
vloc.X++
}
func (w *BufWindow) drawLineNum(lineNumStyle tcell.Style, softwrapped bool, vloc *buffer.Loc, bloc *buffer.Loc) {
cursorLine := w.Buf.GetActiveCursor().Loc.Y
var lineInt int
if w.Buf.Settings["relativeruler"] == false || cursorLine == bloc.Y {
lineInt = bloc.Y + 1
} else {
lineInt = bloc.Y - cursorLine
}
lineNum := []rune(strconv.Itoa(util.Abs(lineInt)))
// Write the spaces before the line number if necessary
for i := 0; i < w.maxLineNumLength-len(lineNum) && vloc.X < w.gutterOffset; i++ {
screen.SetContent(w.X+vloc.X, w.Y+vloc.Y, ' ', nil, lineNumStyle)
vloc.X++
}
// Write the actual line number
for i := 0; i < len(lineNum) && vloc.X < w.gutterOffset; i++ {
if softwrapped || (w.bufWidth == 0 && w.Buf.Settings["softwrap"] == true) {
screen.SetContent(w.X+vloc.X, w.Y+vloc.Y, ' ', nil, lineNumStyle)
} else {
screen.SetContent(w.X+vloc.X, w.Y+vloc.Y, lineNum[i], nil, lineNumStyle)
}
vloc.X++
}
// Write the extra space
if vloc.X < w.gutterOffset {
screen.SetContent(w.X+vloc.X, w.Y+vloc.Y, ' ', nil, lineNumStyle)
vloc.X++
}
}
// getStyle returns the highlight style for the given character position
// If there is no change to the current highlight style it just returns that
func (w *BufWindow) getStyle(style tcell.Style, bloc buffer.Loc) (tcell.Style, bool) {
if group, ok := w.Buf.Match(bloc.Y)[bloc.X]; ok {
s := config.GetColor(group.String())
return s, true
}
return style, false
}
func (w *BufWindow) showCursor(x, y int, main bool) {
if w.active {
if main {
screen.ShowCursor(x, y)
} else {
screen.ShowFakeCursorMulti(x, y)
}
}
}
// displayBuffer draws the buffer being shown in this window on the screen.Screen
func (w *BufWindow) displayBuffer() {
b := w.Buf
if w.Height <= 0 || w.Width <= 0 {
return
}
maxWidth := w.gutterOffset + w.bufWidth
if b.ModifiedThisFrame {
if b.Settings["diffgutter"].(bool) {
b.UpdateDiff()
}
b.ModifiedThisFrame = false
}
var matchingBraces []buffer.Loc
// bracePairs is defined in buffer.go
if b.Settings["matchbrace"].(bool) {
for _, c := range b.GetCursors() {
if c.HasSelection() {
continue
}
mb, left, found := b.FindMatchingBrace(c.Loc)
if found {
matchingBraces = append(matchingBraces, mb)
if !left {
if b.Settings["matchbracestyle"].(string) != "highlight" {
matchingBraces = append(matchingBraces, c.Loc)
}
} else {
matchingBraces = append(matchingBraces, c.Loc.Move(-1, b))
}
}
}
}
lineNumStyle := config.DefStyle
if style, ok := config.Colorscheme["line-number"]; ok {
lineNumStyle = style
}
curNumStyle := config.DefStyle
if style, ok := config.Colorscheme["current-line-number"]; ok {
if !b.Settings["cursorline"].(bool) {
curNumStyle = lineNumStyle
} else {
curNumStyle = style
}
}
softwrap := b.Settings["softwrap"].(bool)
wordwrap := softwrap && b.Settings["wordwrap"].(bool)
tabsize := util.IntOpt(b.Settings["tabsize"])
colorcolumn := util.IntOpt(b.Settings["colorcolumn"])
// this represents the current draw position
// within the current window
vloc := buffer.Loc{X: 0, Y: 0}
if softwrap {
// the start line may be partially out of the current window
vloc.Y = -w.StartLine.Row
}
// this represents the current draw position in the buffer (char positions)
bloc := buffer.Loc{X: -1, Y: w.StartLine.Line}
cursors := b.GetCursors()
curStyle := config.DefStyle
for ; vloc.Y < w.bufHeight; vloc.Y++ {
vloc.X = 0
currentLine := false
for _, c := range cursors {
if bloc.Y == c.Y && w.active {
currentLine = true
break
}
}
s := lineNumStyle
if currentLine {
s = curNumStyle
}
if vloc.Y >= 0 {
if w.hasMessage {
w.drawGutter(&vloc, &bloc)
}
if b.Settings["diffgutter"].(bool) {
w.drawDiffGutter(s, false, &vloc, &bloc)
}
if b.Settings["ruler"].(bool) {
w.drawLineNum(s, false, &vloc, &bloc)
}
} else {
vloc.X = w.gutterOffset
}
bline := b.LineBytes(bloc.Y)
blineLen := util.CharacterCount(bline)
leadingwsEnd := len(util.GetLeadingWhitespace(bline))
trailingwsStart := blineLen - util.CharacterCount(util.GetTrailingWhitespace(bline))
line, nColsBeforeStart, bslice, startStyle := w.getStartInfo(w.StartCol, bloc.Y)
if startStyle != nil {
curStyle = *startStyle
}
bloc.X = bslice
draw := func(r rune, combc []rune, style tcell.Style, highlight bool, showcursor bool) {
if nColsBeforeStart <= 0 && vloc.Y >= 0 {
if highlight {
if w.Buf.HighlightSearch && w.Buf.SearchMatch(bloc) {
style = config.DefStyle.Reverse(true)
if s, ok := config.Colorscheme["hlsearch"]; ok {
style = s
}
}
_, origBg, _ := style.Decompose()
_, defBg, _ := config.DefStyle.Decompose()
// syntax or hlsearch highlighting with non-default background takes precedence
// over cursor-line and color-column
dontOverrideBackground := origBg != defBg
if b.Settings["hltaberrors"].(bool) {
if s, ok := config.Colorscheme["tab-error"]; ok {
isTab := (r == '\t') || (r == ' ' && !showcursor)
if (b.Settings["tabstospaces"].(bool) && isTab) ||
(!b.Settings["tabstospaces"].(bool) && bloc.X < leadingwsEnd && r == ' ' && !isTab) {
fg, _, _ := s.Decompose()
style = style.Background(fg)
dontOverrideBackground = true
}
}
}
if b.Settings["hltrailingws"].(bool) {
if s, ok := config.Colorscheme["trailingws"]; ok {
if bloc.X >= trailingwsStart && bloc.X < blineLen {
hl := true
for _, c := range cursors {
if c.NewTrailingWsY == bloc.Y {
hl = false
break
}
}
if hl {
fg, _, _ := s.Decompose()
style = style.Background(fg)
dontOverrideBackground = true
}
}
}
}
for _, c := range cursors {
if c.HasSelection() &&
(bloc.GreaterEqual(c.CurSelection[0]) && bloc.LessThan(c.CurSelection[1]) ||
bloc.LessThan(c.CurSelection[0]) && bloc.GreaterEqual(c.CurSelection[1])) {
// The current character is selected
style = config.DefStyle.Reverse(true)
if s, ok := config.Colorscheme["selection"]; ok {
style = s
}
}
if b.Settings["cursorline"].(bool) && w.active && !dontOverrideBackground &&
!c.HasSelection() && c.Y == bloc.Y {
if s, ok := config.Colorscheme["cursor-line"]; ok {
fg, _, _ := s.Decompose()
style = style.Background(fg)
}
}
}
for _, m := range b.Messages {
if bloc.GreaterEqual(m.Start) && bloc.LessThan(m.End) ||
bloc.LessThan(m.End) && bloc.GreaterEqual(m.Start) {
style = style.Underline(true)
break
}
}
if r == '\t' {
indentrunes := []rune(b.Settings["indentchar"].(string))
// if empty indentchar settings, use space
if len(indentrunes) == 0 {
indentrunes = []rune{' '}
}
r = indentrunes[0]
if s, ok := config.Colorscheme["indent-char"]; ok && r != ' ' {
fg, _, _ := s.Decompose()
style = style.Foreground(fg)
}
}
if s, ok := config.Colorscheme["color-column"]; ok {
if colorcolumn != 0 && vloc.X-w.gutterOffset+w.StartCol == colorcolumn && !dontOverrideBackground {
fg, _, _ := s.Decompose()
style = style.Background(fg)
}
}
for _, mb := range matchingBraces {
if mb.X == bloc.X && mb.Y == bloc.Y {
if b.Settings["matchbracestyle"].(string) == "highlight" {
if s, ok := config.Colorscheme["match-brace"]; ok {
style = s
} else {
style = style.Reverse(true)
}
} else {
style = style.Underline(true)
}
}
}
}
screen.SetContent(w.X+vloc.X, w.Y+vloc.Y, r, combc, style)
if showcursor {
for _, c := range cursors {
if c.X == bloc.X && c.Y == bloc.Y && !c.HasSelection() {
w.showCursor(w.X+vloc.X, w.Y+vloc.Y, c.Num == 0)
}
}
}
}
if nColsBeforeStart <= 0 {
vloc.X++
}
nColsBeforeStart--
}
wrap := func() {
vloc.X = 0
if w.hasMessage {
w.drawGutter(&vloc, &bloc)
}
if b.Settings["diffgutter"].(bool) {
w.drawDiffGutter(lineNumStyle, true, &vloc, &bloc)
}
// This will draw an empty line number because the current line is wrapped
if b.Settings["ruler"].(bool) {
w.drawLineNum(lineNumStyle, true, &vloc, &bloc)
}
}
type glyph struct {
r rune
combc []rune
style tcell.Style
width int
}
var word []glyph
if wordwrap {
word = make([]glyph, 0, w.bufWidth)
} else {
word = make([]glyph, 0, 1)
}
wordwidth := 0
totalwidth := w.StartCol - nColsBeforeStart
for len(line) > 0 && vloc.X < maxWidth {
r, combc, size := util.DecodeCharacter(line)
line = line[size:]
loc := buffer.Loc{X: bloc.X + len(word), Y: bloc.Y}
curStyle, _ = w.getStyle(curStyle, loc)
width := 0
switch r {
case '\t':
ts := tabsize - (totalwidth % tabsize)
width = util.Min(ts, maxWidth-vloc.X)
totalwidth += ts
default:
width = runewidth.RuneWidth(r)
totalwidth += width
}
word = append(word, glyph{r, combc, curStyle, width})
wordwidth += width
// Collect a complete word to know its width.
// If wordwrap is off, every single character is a complete "word".
if wordwrap {
if !util.IsWhitespace(r) && len(line) > 0 && wordwidth < w.bufWidth {
continue
}
}
// If a word (or just a wide rune) does not fit in the window
if vloc.X+wordwidth > maxWidth && vloc.X > w.gutterOffset {
for vloc.X < maxWidth {
draw(' ', nil, config.DefStyle, false, false)
}
// We either stop or we wrap to draw the word in the next line
if !softwrap {
break
} else {
vloc.Y++
if vloc.Y >= w.bufHeight {
break
}
wrap()
}
}
for _, r := range word {
draw(r.r, r.combc, r.style, true, true)
// Draw any extra characters either spaces for tabs or @ for incomplete wide runes
if r.width > 1 {
char := ' '
if r.r != '\t' {
char = '@'
}
for i := 1; i < r.width; i++ {
draw(char, nil, r.style, true, false)
}
}
bloc.X++
}
word = word[:0]
wordwidth = 0
// If we reach the end of the window then we either stop or we wrap for softwrap
if vloc.X >= maxWidth {
if !softwrap {
break
} else {
vloc.Y++
if vloc.Y >= w.bufHeight {
break
}
wrap()
}
}
}
style := config.DefStyle
for _, c := range cursors {
if b.Settings["cursorline"].(bool) && w.active &&
!c.HasSelection() && c.Y == bloc.Y {
if s, ok := config.Colorscheme["cursor-line"]; ok {
fg, _, _ := s.Decompose()
style = style.Background(fg)
}
}
}
for i := vloc.X; i < maxWidth; i++ {
curStyle := style
if s, ok := config.Colorscheme["color-column"]; ok {
if colorcolumn != 0 && i-w.gutterOffset+w.StartCol == colorcolumn {
fg, _, _ := s.Decompose()
curStyle = style.Background(fg)
}
}
screen.SetContent(i+w.X, vloc.Y+w.Y, ' ', nil, curStyle)
}
if vloc.X != maxWidth {
// Display newline within a selection
draw(' ', nil, config.DefStyle, true, true)
}
bloc.X = w.StartCol
bloc.Y++
if bloc.Y >= b.LinesNum() {
break
}
}
}
func (w *BufWindow) displayStatusLine() {
if w.Buf.Settings["statusline"].(bool) {
w.sline.Display()
} else if w.drawDivider {
divchars := config.GetGlobalOption("divchars").(string)
if util.CharacterCountInString(divchars) != 2 {
divchars = "|-"
}
_, _, size := util.DecodeCharacterInString(divchars)
divchar, combc, _ := util.DecodeCharacterInString(divchars[size:])
dividerStyle := config.DefStyle
if style, ok := config.Colorscheme["divider"]; ok {
dividerStyle = style
}
divreverse := config.GetGlobalOption("divreverse").(bool)
if divreverse {
dividerStyle = dividerStyle.Reverse(true)
}
for x := w.X; x < w.X+w.Width; x++ {
screen.SetContent(x, w.Y+w.Height-1, divchar, combc, dividerStyle)
}
}
}
func (w *BufWindow) displayScrollBar() {
if w.Buf.Settings["scrollbar"].(bool) && w.Buf.LinesNum() > w.Height {
scrollX := w.X + w.Width - 1
barsize := int(float64(w.Height) / float64(w.Buf.LinesNum()) * float64(w.Height))
if barsize < 1 {
barsize = 1
}
barstart := w.Y + int(float64(w.StartLine.Line)/float64(w.Buf.LinesNum())*float64(w.Height))
scrollBarStyle := config.DefStyle.Reverse(true)
if style, ok := config.Colorscheme["scrollbar"]; ok {
scrollBarStyle = style
}
scrollBarChar := config.GetGlobalOption("scrollbarchar").(string)
if util.CharacterCountInString(scrollBarChar) != 1 {
scrollBarChar = "|"
}
scrollBarRune := []rune(scrollBarChar)
for y := barstart; y < util.Min(barstart+barsize, w.Y+w.bufHeight); y++ {
screen.SetContent(scrollX, y, scrollBarRune[0], nil, scrollBarStyle)
}
}
}
// Display displays the buffer and the statusline
func (w *BufWindow) Display() {
w.updateDisplayInfo()
w.displayStatusLine()
w.displayScrollBar()
w.displayBuffer()
}
```
|
/content/code_sandbox/internal/display/bufwindow.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 6,357
|
```go
package display
import (
runewidth "github.com/mattn/go-runewidth"
"github.com/zyedidia/micro/v2/internal/buffer"
"github.com/zyedidia/micro/v2/internal/util"
)
// SLoc represents a vertical scrolling location, i.e. a location of a visual line
// in the buffer. When softwrap is enabled, a buffer line may be displayed as
// multiple visual lines (rows). So SLoc stores a number of a line in the buffer
// and a number of a row within this line.
type SLoc struct {
Line, Row int
}
// LessThan returns true if s is less b
func (s SLoc) LessThan(b SLoc) bool {
if s.Line < b.Line {
return true
}
return s.Line == b.Line && s.Row < b.Row
}
// GreaterThan returns true if s is bigger than b
func (s SLoc) GreaterThan(b SLoc) bool {
if s.Line > b.Line {
return true
}
return s.Line == b.Line && s.Row > b.Row
}
// LessEqual returns true if s is less than or equal to b
func (s SLoc) LessEqual(b SLoc) bool {
if s.Line < b.Line {
return true
}
if s.Line == b.Line && s.Row < b.Row {
return true
}
return s == b
}
// GreaterEqual returns true if s is bigger than or equal to b
func (s SLoc) GreaterEqual(b SLoc) bool {
if s.Line > b.Line {
return true
}
if s.Line == b.Line && s.Row > b.Row {
return true
}
return s == b
}
// VLoc represents a location in the buffer as a visual location in the
// linewrapped buffer.
type VLoc struct {
SLoc
VisualX int
}
type SoftWrap interface {
Scroll(s SLoc, n int) SLoc
Diff(s1, s2 SLoc) int
SLocFromLoc(loc buffer.Loc) SLoc
VLocFromLoc(loc buffer.Loc) VLoc
LocFromVLoc(vloc VLoc) buffer.Loc
}
func (w *BufWindow) getVLocFromLoc(loc buffer.Loc) VLoc {
vloc := VLoc{SLoc: SLoc{loc.Y, 0}, VisualX: 0}
if loc.X <= 0 {
return vloc
}
if w.bufWidth <= 0 {
return vloc
}
wordwrap := w.Buf.Settings["wordwrap"].(bool)
tabsize := util.IntOpt(w.Buf.Settings["tabsize"])
line := w.Buf.LineBytes(loc.Y)
x := 0
totalwidth := 0
wordwidth := 0
wordoffset := 0
for len(line) > 0 {
r, _, size := util.DecodeCharacter(line)
line = line[size:]
width := 0
switch r {
case '\t':
ts := tabsize - (totalwidth % tabsize)
width = util.Min(ts, w.bufWidth-vloc.VisualX)
totalwidth += ts
default:
width = runewidth.RuneWidth(r)
totalwidth += width
}
wordwidth += width
// Collect a complete word to know its width.
// If wordwrap is off, every single character is a complete "word".
if wordwrap {
if !util.IsWhitespace(r) && len(line) > 0 && wordwidth < w.bufWidth {
if x < loc.X {
wordoffset += width
x++
}
continue
}
}
// If a word (or just a wide rune) does not fit in the window
if vloc.VisualX+wordwidth > w.bufWidth && vloc.VisualX > 0 {
vloc.Row++
vloc.VisualX = 0
}
if x == loc.X {
vloc.VisualX += wordoffset
return vloc
}
x++
vloc.VisualX += wordwidth
wordwidth = 0
wordoffset = 0
if vloc.VisualX >= w.bufWidth {
vloc.Row++
vloc.VisualX = 0
}
}
return vloc
}
func (w *BufWindow) getLocFromVLoc(svloc VLoc) buffer.Loc {
loc := buffer.Loc{X: 0, Y: svloc.Line}
if w.bufWidth <= 0 {
return loc
}
wordwrap := w.Buf.Settings["wordwrap"].(bool)
tabsize := util.IntOpt(w.Buf.Settings["tabsize"])
line := w.Buf.LineBytes(svloc.Line)
vloc := VLoc{SLoc: SLoc{svloc.Line, 0}, VisualX: 0}
totalwidth := 0
var widths []int
if wordwrap {
widths = make([]int, 0, w.bufWidth)
} else {
widths = make([]int, 0, 1)
}
wordwidth := 0
for len(line) > 0 {
r, _, size := util.DecodeCharacter(line)
line = line[size:]
width := 0
switch r {
case '\t':
ts := tabsize - (totalwidth % tabsize)
width = util.Min(ts, w.bufWidth-vloc.VisualX)
totalwidth += ts
default:
width = runewidth.RuneWidth(r)
totalwidth += width
}
widths = append(widths, width)
wordwidth += width
// Collect a complete word to know its width.
// If wordwrap is off, every single character is a complete "word".
if wordwrap {
if !util.IsWhitespace(r) && len(line) > 0 && wordwidth < w.bufWidth {
continue
}
}
// If a word (or just a wide rune) does not fit in the window
if vloc.VisualX+wordwidth > w.bufWidth && vloc.VisualX > 0 {
if vloc.Row == svloc.Row {
if wordwrap {
// it's a word, not a wide rune
loc.X--
}
return loc
}
vloc.Row++
vloc.VisualX = 0
}
for i := range widths {
vloc.VisualX += widths[i]
if vloc.Row == svloc.Row && vloc.VisualX > svloc.VisualX {
return loc
}
loc.X++
}
widths = widths[:0]
wordwidth = 0
if vloc.VisualX >= w.bufWidth {
vloc.Row++
vloc.VisualX = 0
}
}
return loc
}
func (w *BufWindow) getRowCount(line int) int {
eol := buffer.Loc{X: util.CharacterCount(w.Buf.LineBytes(line)), Y: line}
return w.getVLocFromLoc(eol).Row + 1
}
func (w *BufWindow) scrollUp(s SLoc, n int) SLoc {
for n > 0 {
if n <= s.Row {
s.Row -= n
n = 0
} else if s.Line > 0 {
s.Line--
n -= s.Row + 1
s.Row = w.getRowCount(s.Line) - 1
} else {
s.Row = 0
break
}
}
return s
}
func (w *BufWindow) scrollDown(s SLoc, n int) SLoc {
for n > 0 {
rc := w.getRowCount(s.Line)
if n < rc-s.Row {
s.Row += n
n = 0
} else if s.Line < w.Buf.LinesNum()-1 {
s.Line++
n -= rc - s.Row
s.Row = 0
} else {
s.Row = rc - 1
break
}
}
return s
}
func (w *BufWindow) scroll(s SLoc, n int) SLoc {
if n < 0 {
return w.scrollUp(s, -n)
}
return w.scrollDown(s, n)
}
func (w *BufWindow) diff(s1, s2 SLoc) int {
n := 0
for s1.LessThan(s2) {
if s1.Line < s2.Line {
n += w.getRowCount(s1.Line) - s1.Row
s1.Line++
s1.Row = 0
} else {
n += s2.Row - s1.Row
s1.Row = s2.Row
}
}
return n
}
// Scroll returns the location which is n visual lines below the location s
// i.e. the result of scrolling n lines down. n can be negative,
// which means scrolling up. The returned location is guaranteed to be
// within the buffer boundaries.
func (w *BufWindow) Scroll(s SLoc, n int) SLoc {
if !w.Buf.Settings["softwrap"].(bool) {
s.Line += n
if s.Line < 0 {
s.Line = 0
}
if s.Line > w.Buf.LinesNum()-1 {
s.Line = w.Buf.LinesNum() - 1
}
return s
}
return w.scroll(s, n)
}
// Diff returns the difference (the vertical distance) between two SLocs.
func (w *BufWindow) Diff(s1, s2 SLoc) int {
if !w.Buf.Settings["softwrap"].(bool) {
return s2.Line - s1.Line
}
if s1.GreaterThan(s2) {
return -w.diff(s2, s1)
}
return w.diff(s1, s2)
}
// SLocFromLoc takes a position in the buffer and returns the location
// of the visual line containing this position.
func (w *BufWindow) SLocFromLoc(loc buffer.Loc) SLoc {
if !w.Buf.Settings["softwrap"].(bool) {
return SLoc{loc.Y, 0}
}
return w.getVLocFromLoc(loc).SLoc
}
// VLocFromLoc takes a position in the buffer and returns the corresponding
// visual location in the linewrapped buffer.
func (w *BufWindow) VLocFromLoc(loc buffer.Loc) VLoc {
if !w.Buf.Settings["softwrap"].(bool) {
tabsize := util.IntOpt(w.Buf.Settings["tabsize"])
visualx := util.StringWidth(w.Buf.LineBytes(loc.Y), loc.X, tabsize)
return VLoc{SLoc{loc.Y, 0}, visualx}
}
return w.getVLocFromLoc(loc)
}
// LocFromVLoc takes a visual location in the linewrapped buffer and returns
// the position in the buffer corresponding to this visual location.
func (w *BufWindow) LocFromVLoc(vloc VLoc) buffer.Loc {
if !w.Buf.Settings["softwrap"].(bool) {
tabsize := util.IntOpt(w.Buf.Settings["tabsize"])
x := util.GetCharPosInLine(w.Buf.LineBytes(vloc.Line), vloc.VisualX, tabsize)
return buffer.Loc{x, vloc.Line}
}
return w.getLocFromVLoc(vloc)
}
```
|
/content/code_sandbox/internal/display/softwrap.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 2,488
|
```go
package clipboard
type internalClipboard map[Register]string
var internal internalClipboard
func init() {
internal = make(internalClipboard)
}
func (c internalClipboard) read(r Register) string {
return c[r]
}
func (c internalClipboard) write(text string, r Register) {
c[r] = text
}
```
|
/content/code_sandbox/internal/clipboard/internal.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 66
|
```go
package clipboard
import (
"errors"
"time"
"github.com/zyedidia/micro/v2/internal/screen"
"github.com/zyedidia/tcell/v2"
)
type terminalClipboard struct{}
var terminal terminalClipboard
func (t terminalClipboard) read(reg string) (string, error) {
screen.Screen.GetClipboard(reg)
// wait at most 200ms for response
for {
select {
case event := <-screen.Events:
e, ok := event.(*tcell.EventPaste)
if ok {
return e.Text(), nil
}
case <-time.After(200 * time.Millisecond):
return "", errors.New("No clipboard received from terminal")
}
}
}
func (t terminalClipboard) write(text, reg string) error {
return screen.Screen.SetClipboard(text, reg)
}
```
|
/content/code_sandbox/internal/clipboard/terminal.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 174
|
```go
package clipboard
import (
"bytes"
)
// For storing multi cursor clipboard contents
type multiClipboard map[Register][]string
var multi multiClipboard
func (c multiClipboard) getAllText(r Register) string {
content := c[r]
if content == nil {
return ""
}
buf := &bytes.Buffer{}
for _, s := range content {
buf.WriteString(s)
}
return buf.String()
}
func (c multiClipboard) getText(r Register, num int) string {
content := c[r]
if content == nil || len(content) <= num {
return ""
}
return content[num]
}
// isValid checks if the text stored in this multi-clipboard is the same as the
// text stored in the system clipboard (provided as an argument), and therefore
// if it is safe to use the multi-clipboard for pasting instead of the system
// clipboard.
func (c multiClipboard) isValid(r Register, clipboard string, ncursors int) bool {
content := c[r]
if content == nil || len(content) != ncursors {
return false
}
return clipboard == c.getAllText(r)
}
func (c multiClipboard) writeText(text string, r Register, num int, ncursors int) {
content := c[r]
if content == nil || len(content) != ncursors {
content = make([]string, ncursors, ncursors)
c[r] = content
}
if num >= ncursors {
return
}
content[num] = text
}
func init() {
multi = make(multiClipboard)
}
```
|
/content/code_sandbox/internal/clipboard/multi.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 325
|
```go
package clipboard
import (
"errors"
"github.com/zyedidia/clipper"
)
type Method int
const (
// External relies on external tools for accessing the clipboard
// These include xclip, xsel, wl-clipboard for linux, pbcopy/pbpaste on Mac,
// and Syscalls on Windows.
External Method = iota
// Terminal uses the terminal to manage the clipboard via OSC 52. Many
// terminals do not support OSC 52, in which case this method won't work.
Terminal
// Internal just manages the clipboard with an internal buffer and doesn't
// attempt to interface with the system clipboard
Internal
)
// CurrentMethod is the method used to store clipboard information
var CurrentMethod Method = Internal
// A Register is a buffer used to store text. The system clipboard has the 'clipboard'
// and 'primary' (linux-only) registers, but other registers may be used internal to micro.
type Register int
const (
// ClipboardReg is the main system clipboard
ClipboardReg Register = -1
// PrimaryReg is the system primary clipboard (linux only)
PrimaryReg = -2
)
var clipboard clipper.Clipboard
// Initialize attempts to initialize the clipboard using the given method
func Initialize(m Method) error {
var err error
switch m {
case External:
clips := make([]clipper.Clipboard, 0, len(clipper.Clipboards)+1)
clips = append(clips, &clipper.Custom{
Name: "micro-clip",
})
clips = append(clips, clipper.Clipboards...)
clipboard, err = clipper.GetClipboard(clips...)
}
if err != nil {
CurrentMethod = Internal
}
return err
}
// SetMethod changes the clipboard access method
func SetMethod(m string) Method {
switch m {
case "internal":
CurrentMethod = Internal
case "external":
CurrentMethod = External
case "terminal":
CurrentMethod = Terminal
}
return CurrentMethod
}
// Read reads from a clipboard register
func Read(r Register) (string, error) {
return read(r, CurrentMethod)
}
// Write writes text to a clipboard register
func Write(text string, r Register) error {
return write(text, r, CurrentMethod)
}
// ReadMulti reads text from a clipboard register for a certain multi-cursor
func ReadMulti(r Register, num, ncursors int) (string, error) {
clip, err := Read(r)
if err != nil {
return "", err
}
if ValidMulti(r, clip, ncursors) {
return multi.getText(r, num), nil
}
return clip, nil
}
// WriteMulti writes text to a clipboard register for a certain multi-cursor
func WriteMulti(text string, r Register, num int, ncursors int) error {
return writeMulti(text, r, num, ncursors, CurrentMethod)
}
// ValidMulti checks if the internal multi-clipboard is valid and up-to-date
// with the system clipboard
func ValidMulti(r Register, clip string, ncursors int) bool {
return multi.isValid(r, clip, ncursors)
}
func writeMulti(text string, r Register, num int, ncursors int, m Method) error {
multi.writeText(text, r, num, ncursors)
return write(multi.getAllText(r), r, m)
}
func read(r Register, m Method) (string, error) {
switch m {
case External:
switch r {
case ClipboardReg:
b, e := clipboard.ReadAll(clipper.RegClipboard)
return string(b), e
case PrimaryReg:
b, e := clipboard.ReadAll(clipper.RegPrimary)
return string(b), e
default:
return internal.read(r), nil
}
case Internal:
return internal.read(r), nil
case Terminal:
switch r {
case ClipboardReg:
// terminal paste works by sending an esc sequence to the
// terminal to trigger a paste event
return terminal.read("clipboard")
case PrimaryReg:
return terminal.read("primary")
default:
return internal.read(r), nil
}
}
return "", errors.New("Invalid clipboard method")
}
func write(text string, r Register, m Method) error {
switch m {
case External:
switch r {
case ClipboardReg:
return clipboard.WriteAll(clipper.RegClipboard, []byte(text))
case PrimaryReg:
return clipboard.WriteAll(clipper.RegPrimary, []byte(text))
default:
internal.write(text, r)
}
case Internal:
internal.write(text, r)
case Terminal:
switch r {
case ClipboardReg:
return terminal.write(text, "c")
case PrimaryReg:
return terminal.write(text, "p")
default:
internal.write(text, r)
}
}
return nil
}
```
|
/content/code_sandbox/internal/clipboard/clipboard.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 1,046
|
```go
package lua
import (
"archive/zip"
"bytes"
"errors"
"fmt"
"io"
"io/ioutil"
"math"
"math/rand"
"net"
"net/http"
"os"
"path"
"path/filepath"
"regexp"
"runtime"
"strings"
"time"
"unicode/utf8"
humanize "github.com/dustin/go-humanize"
lua "github.com/yuin/gopher-lua"
luar "layeh.com/gopher-luar"
)
var L *lua.LState
// LoadFile loads a lua file
func LoadFile(module string, file string, data []byte) error {
pluginDef := []byte("module(\"" + module + "\", package.seeall)")
if fn, err := L.Load(bytes.NewReader(append(pluginDef, data...)), file); err != nil {
return err
} else {
L.Push(fn)
return L.PCall(0, lua.MultRet, nil)
}
}
// Import allows a lua plugin to import a package
func Import(pkg string) *lua.LTable {
switch pkg {
case "fmt":
return importFmt()
case "io":
return importIo()
case "io/ioutil", "ioutil":
return importIoUtil()
case "net":
return importNet()
case "math":
return importMath()
case "math/rand":
return importMathRand()
case "os":
return importOs()
case "runtime":
return importRuntime()
case "path":
return importPath()
case "path/filepath", "filepath":
return importFilePath()
case "strings":
return importStrings()
case "regexp":
return importRegexp()
case "errors":
return importErrors()
case "time":
return importTime()
case "unicode/utf8", "utf8":
return importUtf8()
case "humanize":
return importHumanize()
case "net/http", "http":
return importHTTP()
case "archive/zip":
return importArchiveZip()
default:
return nil
}
}
func importFmt() *lua.LTable {
pkg := L.NewTable()
L.SetField(pkg, "Errorf", luar.New(L, fmt.Errorf))
L.SetField(pkg, "Fprint", luar.New(L, fmt.Fprint))
L.SetField(pkg, "Fprintf", luar.New(L, fmt.Fprintf))
L.SetField(pkg, "Fprintln", luar.New(L, fmt.Fprintln))
L.SetField(pkg, "Fscan", luar.New(L, fmt.Fscan))
L.SetField(pkg, "Fscanf", luar.New(L, fmt.Fscanf))
L.SetField(pkg, "Fscanln", luar.New(L, fmt.Fscanln))
L.SetField(pkg, "Print", luar.New(L, fmt.Print))
L.SetField(pkg, "Printf", luar.New(L, fmt.Printf))
L.SetField(pkg, "Println", luar.New(L, fmt.Println))
L.SetField(pkg, "Scan", luar.New(L, fmt.Scan))
L.SetField(pkg, "Scanf", luar.New(L, fmt.Scanf))
L.SetField(pkg, "Scanln", luar.New(L, fmt.Scanln))
L.SetField(pkg, "Sprint", luar.New(L, fmt.Sprint))
L.SetField(pkg, "Sprintf", luar.New(L, fmt.Sprintf))
L.SetField(pkg, "Sprintln", luar.New(L, fmt.Sprintln))
L.SetField(pkg, "Sscan", luar.New(L, fmt.Sscan))
L.SetField(pkg, "Sscanf", luar.New(L, fmt.Sscanf))
L.SetField(pkg, "Sscanln", luar.New(L, fmt.Sscanln))
return pkg
}
func importIo() *lua.LTable {
pkg := L.NewTable()
L.SetField(pkg, "Copy", luar.New(L, io.Copy))
L.SetField(pkg, "CopyN", luar.New(L, io.CopyN))
L.SetField(pkg, "EOF", luar.New(L, io.EOF))
L.SetField(pkg, "ErrClosedPipe", luar.New(L, io.ErrClosedPipe))
L.SetField(pkg, "ErrNoProgress", luar.New(L, io.ErrNoProgress))
L.SetField(pkg, "ErrShortBuffer", luar.New(L, io.ErrShortBuffer))
L.SetField(pkg, "ErrShortWrite", luar.New(L, io.ErrShortWrite))
L.SetField(pkg, "ErrUnexpectedEOF", luar.New(L, io.ErrUnexpectedEOF))
L.SetField(pkg, "LimitReader", luar.New(L, io.LimitReader))
L.SetField(pkg, "MultiReader", luar.New(L, io.MultiReader))
L.SetField(pkg, "MultiWriter", luar.New(L, io.MultiWriter))
L.SetField(pkg, "NewSectionReader", luar.New(L, io.NewSectionReader))
L.SetField(pkg, "Pipe", luar.New(L, io.Pipe))
L.SetField(pkg, "ReadAtLeast", luar.New(L, io.ReadAtLeast))
L.SetField(pkg, "ReadFull", luar.New(L, io.ReadFull))
L.SetField(pkg, "TeeReader", luar.New(L, io.TeeReader))
L.SetField(pkg, "WriteString", luar.New(L, io.WriteString))
return pkg
}
func importIoUtil() *lua.LTable {
pkg := L.NewTable()
L.SetField(pkg, "ReadAll", luar.New(L, ioutil.ReadAll))
L.SetField(pkg, "ReadDir", luar.New(L, ioutil.ReadDir))
L.SetField(pkg, "ReadFile", luar.New(L, ioutil.ReadFile))
L.SetField(pkg, "WriteFile", luar.New(L, ioutil.WriteFile))
return pkg
}
func importNet() *lua.LTable {
pkg := L.NewTable()
L.SetField(pkg, "CIDRMask", luar.New(L, net.CIDRMask))
L.SetField(pkg, "Dial", luar.New(L, net.Dial))
L.SetField(pkg, "DialIP", luar.New(L, net.DialIP))
L.SetField(pkg, "DialTCP", luar.New(L, net.DialTCP))
L.SetField(pkg, "DialTimeout", luar.New(L, net.DialTimeout))
L.SetField(pkg, "DialUDP", luar.New(L, net.DialUDP))
L.SetField(pkg, "DialUnix", luar.New(L, net.DialUnix))
L.SetField(pkg, "ErrWriteToConnected", luar.New(L, net.ErrWriteToConnected))
L.SetField(pkg, "FileConn", luar.New(L, net.FileConn))
L.SetField(pkg, "FileListener", luar.New(L, net.FileListener))
L.SetField(pkg, "FilePacketConn", luar.New(L, net.FilePacketConn))
L.SetField(pkg, "FlagBroadcast", luar.New(L, net.FlagBroadcast))
L.SetField(pkg, "FlagLoopback", luar.New(L, net.FlagLoopback))
L.SetField(pkg, "FlagMulticast", luar.New(L, net.FlagMulticast))
L.SetField(pkg, "FlagPointToPoint", luar.New(L, net.FlagPointToPoint))
L.SetField(pkg, "FlagUp", luar.New(L, net.FlagUp))
L.SetField(pkg, "IPv4", luar.New(L, net.IPv4))
L.SetField(pkg, "IPv4Mask", luar.New(L, net.IPv4Mask))
L.SetField(pkg, "IPv4allrouter", luar.New(L, net.IPv4allrouter))
L.SetField(pkg, "IPv4allsys", luar.New(L, net.IPv4allsys))
L.SetField(pkg, "IPv4bcast", luar.New(L, net.IPv4bcast))
L.SetField(pkg, "IPv4len", luar.New(L, net.IPv4len))
L.SetField(pkg, "IPv4zero", luar.New(L, net.IPv4zero))
L.SetField(pkg, "IPv6interfacelocalallnodes", luar.New(L, net.IPv6interfacelocalallnodes))
L.SetField(pkg, "IPv6len", luar.New(L, net.IPv6len))
L.SetField(pkg, "IPv6linklocalallnodes", luar.New(L, net.IPv6linklocalallnodes))
L.SetField(pkg, "IPv6linklocalallrouters", luar.New(L, net.IPv6linklocalallrouters))
L.SetField(pkg, "IPv6loopback", luar.New(L, net.IPv6loopback))
L.SetField(pkg, "IPv6unspecified", luar.New(L, net.IPv6unspecified))
L.SetField(pkg, "IPv6zero", luar.New(L, net.IPv6zero))
L.SetField(pkg, "InterfaceAddrs", luar.New(L, net.InterfaceAddrs))
L.SetField(pkg, "InterfaceByIndex", luar.New(L, net.InterfaceByIndex))
L.SetField(pkg, "InterfaceByName", luar.New(L, net.InterfaceByName))
L.SetField(pkg, "Interfaces", luar.New(L, net.Interfaces))
L.SetField(pkg, "JoinHostPort", luar.New(L, net.JoinHostPort))
L.SetField(pkg, "Listen", luar.New(L, net.Listen))
L.SetField(pkg, "ListenIP", luar.New(L, net.ListenIP))
L.SetField(pkg, "ListenMulticastUDP", luar.New(L, net.ListenMulticastUDP))
L.SetField(pkg, "ListenPacket", luar.New(L, net.ListenPacket))
L.SetField(pkg, "ListenTCP", luar.New(L, net.ListenTCP))
L.SetField(pkg, "ListenUDP", luar.New(L, net.ListenUDP))
L.SetField(pkg, "ListenUnix", luar.New(L, net.ListenUnix))
L.SetField(pkg, "ListenUnixgram", luar.New(L, net.ListenUnixgram))
L.SetField(pkg, "LookupAddr", luar.New(L, net.LookupAddr))
L.SetField(pkg, "LookupCNAME", luar.New(L, net.LookupCNAME))
L.SetField(pkg, "LookupHost", luar.New(L, net.LookupHost))
L.SetField(pkg, "LookupIP", luar.New(L, net.LookupIP))
L.SetField(pkg, "LookupMX", luar.New(L, net.LookupMX))
L.SetField(pkg, "LookupNS", luar.New(L, net.LookupNS))
L.SetField(pkg, "LookupPort", luar.New(L, net.LookupPort))
L.SetField(pkg, "LookupSRV", luar.New(L, net.LookupSRV))
L.SetField(pkg, "LookupTXT", luar.New(L, net.LookupTXT))
L.SetField(pkg, "ParseCIDR", luar.New(L, net.ParseCIDR))
L.SetField(pkg, "ParseIP", luar.New(L, net.ParseIP))
L.SetField(pkg, "ParseMAC", luar.New(L, net.ParseMAC))
L.SetField(pkg, "Pipe", luar.New(L, net.Pipe))
L.SetField(pkg, "ResolveIPAddr", luar.New(L, net.ResolveIPAddr))
L.SetField(pkg, "ResolveTCPAddr", luar.New(L, net.ResolveTCPAddr))
L.SetField(pkg, "ResolveUDPAddr", luar.New(L, net.ResolveUDPAddr))
L.SetField(pkg, "ResolveUnixAddr", luar.New(L, net.ResolveUnixAddr))
L.SetField(pkg, "SplitHostPort", luar.New(L, net.SplitHostPort))
return pkg
}
func importMath() *lua.LTable {
pkg := L.NewTable()
L.SetField(pkg, "Abs", luar.New(L, math.Abs))
L.SetField(pkg, "Acos", luar.New(L, math.Acos))
L.SetField(pkg, "Acosh", luar.New(L, math.Acosh))
L.SetField(pkg, "Asin", luar.New(L, math.Asin))
L.SetField(pkg, "Asinh", luar.New(L, math.Asinh))
L.SetField(pkg, "Atan", luar.New(L, math.Atan))
L.SetField(pkg, "Atan2", luar.New(L, math.Atan2))
L.SetField(pkg, "Atanh", luar.New(L, math.Atanh))
L.SetField(pkg, "Cbrt", luar.New(L, math.Cbrt))
L.SetField(pkg, "Ceil", luar.New(L, math.Ceil))
L.SetField(pkg, "Copysign", luar.New(L, math.Copysign))
L.SetField(pkg, "Cos", luar.New(L, math.Cos))
L.SetField(pkg, "Cosh", luar.New(L, math.Cosh))
L.SetField(pkg, "Dim", luar.New(L, math.Dim))
L.SetField(pkg, "Erf", luar.New(L, math.Erf))
L.SetField(pkg, "Erfc", luar.New(L, math.Erfc))
L.SetField(pkg, "Exp", luar.New(L, math.Exp))
L.SetField(pkg, "Exp2", luar.New(L, math.Exp2))
L.SetField(pkg, "Expm1", luar.New(L, math.Expm1))
L.SetField(pkg, "Float32bits", luar.New(L, math.Float32bits))
L.SetField(pkg, "Float32frombits", luar.New(L, math.Float32frombits))
L.SetField(pkg, "Float64bits", luar.New(L, math.Float64bits))
L.SetField(pkg, "Float64frombits", luar.New(L, math.Float64frombits))
L.SetField(pkg, "Floor", luar.New(L, math.Floor))
L.SetField(pkg, "Frexp", luar.New(L, math.Frexp))
L.SetField(pkg, "Gamma", luar.New(L, math.Gamma))
L.SetField(pkg, "Hypot", luar.New(L, math.Hypot))
L.SetField(pkg, "Ilogb", luar.New(L, math.Ilogb))
L.SetField(pkg, "Inf", luar.New(L, math.Inf))
L.SetField(pkg, "IsInf", luar.New(L, math.IsInf))
L.SetField(pkg, "IsNaN", luar.New(L, math.IsNaN))
L.SetField(pkg, "J0", luar.New(L, math.J0))
L.SetField(pkg, "J1", luar.New(L, math.J1))
L.SetField(pkg, "Jn", luar.New(L, math.Jn))
L.SetField(pkg, "Ldexp", luar.New(L, math.Ldexp))
L.SetField(pkg, "Lgamma", luar.New(L, math.Lgamma))
L.SetField(pkg, "Log", luar.New(L, math.Log))
L.SetField(pkg, "Log10", luar.New(L, math.Log10))
L.SetField(pkg, "Log1p", luar.New(L, math.Log1p))
L.SetField(pkg, "Log2", luar.New(L, math.Log2))
L.SetField(pkg, "Logb", luar.New(L, math.Logb))
L.SetField(pkg, "Max", luar.New(L, math.Max))
L.SetField(pkg, "Min", luar.New(L, math.Min))
L.SetField(pkg, "Mod", luar.New(L, math.Mod))
L.SetField(pkg, "Modf", luar.New(L, math.Modf))
L.SetField(pkg, "NaN", luar.New(L, math.NaN))
L.SetField(pkg, "Nextafter", luar.New(L, math.Nextafter))
L.SetField(pkg, "Pow", luar.New(L, math.Pow))
L.SetField(pkg, "Pow10", luar.New(L, math.Pow10))
L.SetField(pkg, "Remainder", luar.New(L, math.Remainder))
L.SetField(pkg, "Signbit", luar.New(L, math.Signbit))
L.SetField(pkg, "Sin", luar.New(L, math.Sin))
L.SetField(pkg, "Sincos", luar.New(L, math.Sincos))
L.SetField(pkg, "Sinh", luar.New(L, math.Sinh))
L.SetField(pkg, "Sqrt", luar.New(L, math.Sqrt))
L.SetField(pkg, "Tan", luar.New(L, math.Tan))
L.SetField(pkg, "Tanh", luar.New(L, math.Tanh))
L.SetField(pkg, "Trunc", luar.New(L, math.Trunc))
L.SetField(pkg, "Y0", luar.New(L, math.Y0))
L.SetField(pkg, "Y1", luar.New(L, math.Y1))
L.SetField(pkg, "Yn", luar.New(L, math.Yn))
return pkg
}
func importMathRand() *lua.LTable {
pkg := L.NewTable()
L.SetField(pkg, "ExpFloat64", luar.New(L, rand.ExpFloat64))
L.SetField(pkg, "Float32", luar.New(L, rand.Float32))
L.SetField(pkg, "Float64", luar.New(L, rand.Float64))
L.SetField(pkg, "Int", luar.New(L, rand.Int))
L.SetField(pkg, "Int31", luar.New(L, rand.Int31))
L.SetField(pkg, "Int31n", luar.New(L, rand.Int31n))
L.SetField(pkg, "Int63", luar.New(L, rand.Int63))
L.SetField(pkg, "Int63n", luar.New(L, rand.Int63n))
L.SetField(pkg, "Intn", luar.New(L, rand.Intn))
L.SetField(pkg, "NormFloat64", luar.New(L, rand.NormFloat64))
L.SetField(pkg, "Perm", luar.New(L, rand.Perm))
L.SetField(pkg, "Seed", luar.New(L, rand.Seed))
L.SetField(pkg, "Uint32", luar.New(L, rand.Uint32))
return pkg
}
func importOs() *lua.LTable {
pkg := L.NewTable()
L.SetField(pkg, "Args", luar.New(L, os.Args))
L.SetField(pkg, "Chdir", luar.New(L, os.Chdir))
L.SetField(pkg, "Chmod", luar.New(L, os.Chmod))
L.SetField(pkg, "Chown", luar.New(L, os.Chown))
L.SetField(pkg, "Chtimes", luar.New(L, os.Chtimes))
L.SetField(pkg, "Clearenv", luar.New(L, os.Clearenv))
L.SetField(pkg, "Create", luar.New(L, os.Create))
L.SetField(pkg, "DevNull", luar.New(L, os.DevNull))
L.SetField(pkg, "Environ", luar.New(L, os.Environ))
L.SetField(pkg, "ErrExist", luar.New(L, os.ErrExist))
L.SetField(pkg, "ErrInvalid", luar.New(L, os.ErrInvalid))
L.SetField(pkg, "ErrNotExist", luar.New(L, os.ErrNotExist))
L.SetField(pkg, "ErrPermission", luar.New(L, os.ErrPermission))
L.SetField(pkg, "Exit", luar.New(L, os.Exit))
L.SetField(pkg, "Expand", luar.New(L, os.Expand))
L.SetField(pkg, "ExpandEnv", luar.New(L, os.ExpandEnv))
L.SetField(pkg, "FindProcess", luar.New(L, os.FindProcess))
L.SetField(pkg, "Getegid", luar.New(L, os.Getegid))
L.SetField(pkg, "Getenv", luar.New(L, os.Getenv))
L.SetField(pkg, "Geteuid", luar.New(L, os.Geteuid))
L.SetField(pkg, "Getgid", luar.New(L, os.Getgid))
L.SetField(pkg, "Getgroups", luar.New(L, os.Getgroups))
L.SetField(pkg, "Getpagesize", luar.New(L, os.Getpagesize))
L.SetField(pkg, "Getpid", luar.New(L, os.Getpid))
L.SetField(pkg, "Getuid", luar.New(L, os.Getuid))
L.SetField(pkg, "Getwd", luar.New(L, os.Getwd))
L.SetField(pkg, "Hostname", luar.New(L, os.Hostname))
L.SetField(pkg, "Interrupt", luar.New(L, os.Interrupt))
L.SetField(pkg, "IsExist", luar.New(L, os.IsExist))
L.SetField(pkg, "IsNotExist", luar.New(L, os.IsNotExist))
L.SetField(pkg, "IsPathSeparator", luar.New(L, os.IsPathSeparator))
L.SetField(pkg, "IsPermission", luar.New(L, os.IsPermission))
L.SetField(pkg, "Kill", luar.New(L, os.Kill))
L.SetField(pkg, "Lchown", luar.New(L, os.Lchown))
L.SetField(pkg, "Link", luar.New(L, os.Link))
L.SetField(pkg, "Lstat", luar.New(L, os.Lstat))
L.SetField(pkg, "Mkdir", luar.New(L, os.Mkdir))
L.SetField(pkg, "MkdirAll", luar.New(L, os.MkdirAll))
L.SetField(pkg, "ModeAppend", luar.New(L, os.ModeAppend))
L.SetField(pkg, "ModeCharDevice", luar.New(L, os.ModeCharDevice))
L.SetField(pkg, "ModeDevice", luar.New(L, os.ModeDevice))
L.SetField(pkg, "ModeDir", luar.New(L, os.ModeDir))
L.SetField(pkg, "ModeExclusive", luar.New(L, os.ModeExclusive))
L.SetField(pkg, "ModeNamedPipe", luar.New(L, os.ModeNamedPipe))
L.SetField(pkg, "ModePerm", luar.New(L, os.ModePerm))
L.SetField(pkg, "ModeSetgid", luar.New(L, os.ModeSetgid))
L.SetField(pkg, "ModeSetuid", luar.New(L, os.ModeSetuid))
L.SetField(pkg, "ModeSocket", luar.New(L, os.ModeSocket))
L.SetField(pkg, "ModeSticky", luar.New(L, os.ModeSticky))
L.SetField(pkg, "ModeSymlink", luar.New(L, os.ModeSymlink))
L.SetField(pkg, "ModeTemporary", luar.New(L, os.ModeTemporary))
L.SetField(pkg, "ModeType", luar.New(L, os.ModeType))
L.SetField(pkg, "NewFile", luar.New(L, os.NewFile))
L.SetField(pkg, "NewSyscallError", luar.New(L, os.NewSyscallError))
L.SetField(pkg, "O_APPEND", luar.New(L, os.O_APPEND))
L.SetField(pkg, "O_CREATE", luar.New(L, os.O_CREATE))
L.SetField(pkg, "O_EXCL", luar.New(L, os.O_EXCL))
L.SetField(pkg, "O_RDONLY", luar.New(L, os.O_RDONLY))
L.SetField(pkg, "O_RDWR", luar.New(L, os.O_RDWR))
L.SetField(pkg, "O_SYNC", luar.New(L, os.O_SYNC))
L.SetField(pkg, "O_TRUNC", luar.New(L, os.O_TRUNC))
L.SetField(pkg, "O_WRONLY", luar.New(L, os.O_WRONLY))
L.SetField(pkg, "Open", luar.New(L, os.Open))
L.SetField(pkg, "OpenFile", luar.New(L, os.OpenFile))
L.SetField(pkg, "PathListSeparator", luar.New(L, os.PathListSeparator))
L.SetField(pkg, "PathSeparator", luar.New(L, os.PathSeparator))
L.SetField(pkg, "Pipe", luar.New(L, os.Pipe))
L.SetField(pkg, "Readlink", luar.New(L, os.Readlink))
L.SetField(pkg, "Remove", luar.New(L, os.Remove))
L.SetField(pkg, "RemoveAll", luar.New(L, os.RemoveAll))
L.SetField(pkg, "Rename", luar.New(L, os.Rename))
L.SetField(pkg, "SEEK_CUR", luar.New(L, io.SeekCurrent))
L.SetField(pkg, "SEEK_END", luar.New(L, io.SeekEnd))
L.SetField(pkg, "SEEK_SET", luar.New(L, io.SeekStart))
L.SetField(pkg, "SameFile", luar.New(L, os.SameFile))
L.SetField(pkg, "Setenv", luar.New(L, os.Setenv))
L.SetField(pkg, "StartProcess", luar.New(L, os.StartProcess))
L.SetField(pkg, "Stat", luar.New(L, os.Stat))
L.SetField(pkg, "Stderr", luar.New(L, os.Stderr))
L.SetField(pkg, "Stdin", luar.New(L, os.Stdin))
L.SetField(pkg, "Stdout", luar.New(L, os.Stdout))
L.SetField(pkg, "Symlink", luar.New(L, os.Symlink))
L.SetField(pkg, "TempDir", luar.New(L, os.TempDir))
L.SetField(pkg, "Truncate", luar.New(L, os.Truncate))
L.SetField(pkg, "UserHomeDir", luar.New(L, os.UserHomeDir))
return pkg
}
func importRuntime() *lua.LTable {
pkg := L.NewTable()
L.SetField(pkg, "GC", luar.New(L, runtime.GC))
L.SetField(pkg, "GOARCH", luar.New(L, runtime.GOARCH))
L.SetField(pkg, "GOMAXPROCS", luar.New(L, runtime.GOMAXPROCS))
L.SetField(pkg, "GOOS", luar.New(L, runtime.GOOS))
L.SetField(pkg, "GOROOT", luar.New(L, runtime.GOROOT))
return pkg
}
func importPath() *lua.LTable {
pkg := L.NewTable()
L.SetField(pkg, "Base", luar.New(L, path.Base))
L.SetField(pkg, "Clean", luar.New(L, path.Clean))
L.SetField(pkg, "Dir", luar.New(L, path.Dir))
L.SetField(pkg, "ErrBadPattern", luar.New(L, path.ErrBadPattern))
L.SetField(pkg, "Ext", luar.New(L, path.Ext))
L.SetField(pkg, "IsAbs", luar.New(L, path.IsAbs))
L.SetField(pkg, "Join", luar.New(L, path.Join))
L.SetField(pkg, "Match", luar.New(L, path.Match))
L.SetField(pkg, "Split", luar.New(L, path.Split))
return pkg
}
func importFilePath() *lua.LTable {
pkg := L.NewTable()
L.SetField(pkg, "Join", luar.New(L, filepath.Join))
L.SetField(pkg, "Abs", luar.New(L, filepath.Abs))
L.SetField(pkg, "Base", luar.New(L, filepath.Base))
L.SetField(pkg, "Clean", luar.New(L, filepath.Clean))
L.SetField(pkg, "Dir", luar.New(L, filepath.Dir))
L.SetField(pkg, "EvalSymlinks", luar.New(L, filepath.EvalSymlinks))
L.SetField(pkg, "Ext", luar.New(L, filepath.Ext))
L.SetField(pkg, "FromSlash", luar.New(L, filepath.FromSlash))
L.SetField(pkg, "Glob", luar.New(L, filepath.Glob))
L.SetField(pkg, "HasPrefix", luar.New(L, filepath.HasPrefix))
L.SetField(pkg, "IsAbs", luar.New(L, filepath.IsAbs))
L.SetField(pkg, "Join", luar.New(L, filepath.Join))
L.SetField(pkg, "Match", luar.New(L, filepath.Match))
L.SetField(pkg, "Rel", luar.New(L, filepath.Rel))
L.SetField(pkg, "Split", luar.New(L, filepath.Split))
L.SetField(pkg, "SplitList", luar.New(L, filepath.SplitList))
L.SetField(pkg, "ToSlash", luar.New(L, filepath.ToSlash))
L.SetField(pkg, "VolumeName", luar.New(L, filepath.VolumeName))
return pkg
}
func importStrings() *lua.LTable {
pkg := L.NewTable()
L.SetField(pkg, "Contains", luar.New(L, strings.Contains))
L.SetField(pkg, "ContainsAny", luar.New(L, strings.ContainsAny))
L.SetField(pkg, "ContainsRune", luar.New(L, strings.ContainsRune))
L.SetField(pkg, "Count", luar.New(L, strings.Count))
L.SetField(pkg, "EqualFold", luar.New(L, strings.EqualFold))
L.SetField(pkg, "Fields", luar.New(L, strings.Fields))
L.SetField(pkg, "FieldsFunc", luar.New(L, strings.FieldsFunc))
L.SetField(pkg, "HasPrefix", luar.New(L, strings.HasPrefix))
L.SetField(pkg, "HasSuffix", luar.New(L, strings.HasSuffix))
L.SetField(pkg, "Index", luar.New(L, strings.Index))
L.SetField(pkg, "IndexAny", luar.New(L, strings.IndexAny))
L.SetField(pkg, "IndexByte", luar.New(L, strings.IndexByte))
L.SetField(pkg, "IndexFunc", luar.New(L, strings.IndexFunc))
L.SetField(pkg, "IndexRune", luar.New(L, strings.IndexRune))
L.SetField(pkg, "Join", luar.New(L, strings.Join))
L.SetField(pkg, "LastIndex", luar.New(L, strings.LastIndex))
L.SetField(pkg, "LastIndexAny", luar.New(L, strings.LastIndexAny))
L.SetField(pkg, "LastIndexFunc", luar.New(L, strings.LastIndexFunc))
L.SetField(pkg, "Map", luar.New(L, strings.Map))
L.SetField(pkg, "NewReader", luar.New(L, strings.NewReader))
L.SetField(pkg, "NewReplacer", luar.New(L, strings.NewReplacer))
L.SetField(pkg, "Repeat", luar.New(L, strings.Repeat))
L.SetField(pkg, "Replace", luar.New(L, strings.Replace))
L.SetField(pkg, "Split", luar.New(L, strings.Split))
L.SetField(pkg, "SplitAfter", luar.New(L, strings.SplitAfter))
L.SetField(pkg, "SplitAfterN", luar.New(L, strings.SplitAfterN))
L.SetField(pkg, "SplitN", luar.New(L, strings.SplitN))
L.SetField(pkg, "Title", luar.New(L, strings.Title))
L.SetField(pkg, "ToLower", luar.New(L, strings.ToLower))
L.SetField(pkg, "ToLowerSpecial", luar.New(L, strings.ToLowerSpecial))
L.SetField(pkg, "ToTitle", luar.New(L, strings.ToTitle))
L.SetField(pkg, "ToTitleSpecial", luar.New(L, strings.ToTitleSpecial))
L.SetField(pkg, "ToUpper", luar.New(L, strings.ToUpper))
L.SetField(pkg, "ToUpperSpecial", luar.New(L, strings.ToUpperSpecial))
L.SetField(pkg, "Trim", luar.New(L, strings.Trim))
L.SetField(pkg, "TrimFunc", luar.New(L, strings.TrimFunc))
L.SetField(pkg, "TrimLeft", luar.New(L, strings.TrimLeft))
L.SetField(pkg, "TrimLeftFunc", luar.New(L, strings.TrimLeftFunc))
L.SetField(pkg, "TrimPrefix", luar.New(L, strings.TrimPrefix))
L.SetField(pkg, "TrimRight", luar.New(L, strings.TrimRight))
L.SetField(pkg, "TrimRightFunc", luar.New(L, strings.TrimRightFunc))
L.SetField(pkg, "TrimSpace", luar.New(L, strings.TrimSpace))
L.SetField(pkg, "TrimSuffix", luar.New(L, strings.TrimSuffix))
return pkg
}
func importRegexp() *lua.LTable {
pkg := L.NewTable()
L.SetField(pkg, "Match", luar.New(L, regexp.Match))
L.SetField(pkg, "MatchReader", luar.New(L, regexp.MatchReader))
L.SetField(pkg, "MatchString", luar.New(L, regexp.MatchString))
L.SetField(pkg, "QuoteMeta", luar.New(L, regexp.QuoteMeta))
L.SetField(pkg, "Compile", luar.New(L, regexp.Compile))
L.SetField(pkg, "CompilePOSIX", luar.New(L, regexp.CompilePOSIX))
L.SetField(pkg, "MustCompile", luar.New(L, regexp.MustCompile))
L.SetField(pkg, "MustCompilePOSIX", luar.New(L, regexp.MustCompilePOSIX))
return pkg
}
func importErrors() *lua.LTable {
pkg := L.NewTable()
L.SetField(pkg, "New", luar.New(L, errors.New))
return pkg
}
func importTime() *lua.LTable {
pkg := L.NewTable()
L.SetField(pkg, "Sleep", luar.New(L, time.Sleep))
L.SetField(pkg, "Since", luar.New(L, time.Since))
L.SetField(pkg, "FixedZone", luar.New(L, time.FixedZone))
L.SetField(pkg, "LoadLocation", luar.New(L, time.LoadLocation))
L.SetField(pkg, "Date", luar.New(L, time.Date))
L.SetField(pkg, "Now", luar.New(L, time.Now))
L.SetField(pkg, "Parse", luar.New(L, time.Parse))
L.SetField(pkg, "ParseDuration", luar.New(L, time.ParseDuration))
L.SetField(pkg, "ParseInLocation", luar.New(L, time.ParseInLocation))
L.SetField(pkg, "Unix", luar.New(L, time.Unix))
L.SetField(pkg, "Nanosecond", luar.New(L, time.Nanosecond))
L.SetField(pkg, "Microsecond", luar.New(L, time.Microsecond))
L.SetField(pkg, "Millisecond", luar.New(L, time.Millisecond))
L.SetField(pkg, "Second", luar.New(L, time.Second))
L.SetField(pkg, "Minute", luar.New(L, time.Minute))
L.SetField(pkg, "Hour", luar.New(L, time.Hour))
// TODO: these raw Go timer APIs don't provide any synchronization
// with micro. Stop exposing them to lua once plugins switch to using
// the safer micro.After() interface instead. See issue #3209
L.SetField(pkg, "After", luar.New(L, time.After))
L.SetField(pkg, "AfterFunc", luar.New(L, time.AfterFunc))
L.SetField(pkg, "NewTicker", luar.New(L, time.NewTicker))
L.SetField(pkg, "NewTimer", luar.New(L, time.NewTimer))
L.SetField(pkg, "Tick", luar.New(L, time.Tick))
return pkg
}
func importUtf8() *lua.LTable {
pkg := L.NewTable()
L.SetField(pkg, "DecodeLastRune", luar.New(L, utf8.DecodeLastRune))
L.SetField(pkg, "DecodeLastRuneInString", luar.New(L, utf8.DecodeLastRuneInString))
L.SetField(pkg, "DecodeRune", luar.New(L, utf8.DecodeRune))
L.SetField(pkg, "DecodeRuneInString", luar.New(L, utf8.DecodeRuneInString))
L.SetField(pkg, "EncodeRune", luar.New(L, utf8.EncodeRune))
L.SetField(pkg, "FullRune", luar.New(L, utf8.FullRune))
L.SetField(pkg, "FullRuneInString", luar.New(L, utf8.FullRuneInString))
L.SetField(pkg, "RuneCount", luar.New(L, utf8.RuneCount))
L.SetField(pkg, "RuneCountInString", luar.New(L, utf8.RuneCountInString))
L.SetField(pkg, "RuneLen", luar.New(L, utf8.RuneLen))
L.SetField(pkg, "RuneStart", luar.New(L, utf8.RuneStart))
L.SetField(pkg, "Valid", luar.New(L, utf8.Valid))
L.SetField(pkg, "ValidRune", luar.New(L, utf8.ValidRune))
L.SetField(pkg, "ValidString", luar.New(L, utf8.ValidString))
return pkg
}
func importHumanize() *lua.LTable {
pkg := L.NewTable()
L.SetField(pkg, "Bytes", luar.New(L, humanize.Bytes))
L.SetField(pkg, "Ordinal", luar.New(L, humanize.Ordinal))
return pkg
}
func importHTTP() *lua.LTable {
pkg := L.NewTable()
L.SetField(pkg, "Get", luar.New(L, http.Get))
L.SetField(pkg, "Post", luar.New(L, http.Post))
return pkg
}
func importArchiveZip() *lua.LTable {
pkg := L.NewTable()
L.SetField(pkg, "OpenReader", luar.New(L, zip.OpenReader))
L.SetField(pkg, "NewReader", luar.New(L, zip.NewReader))
L.SetField(pkg, "NewWriter", luar.New(L, zip.NewWriter))
return pkg
}
```
|
/content/code_sandbox/internal/lua/lua.go
|
go
| 2016-03-11T02:06:28
| 2024-08-16T15:15:57
|
micro
|
zyedidia/micro
| 24,604
| 7,952
|
```smalltalk
using System;
using CodeFirst.DataAccess.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace CodeFirst.DataAccess.Configurations;
public class RentalsConfiguration : IEntityTypeConfiguration<Rentals>
{
public void Configure(EntityTypeBuilder<Rentals> builder)
{
builder.HasKey(e => new {e.ClientId, e.CopyId})
.HasName("rentals_pkey");
builder.HasOne(e => e.Client)
.WithMany(e => e.Rentals)
.OnDelete(DeleteBehavior.Cascade)
.HasForeignKey(e => e.ClientId);
builder.HasOne(e => e.Copy)
.WithMany(e => e.Rentals)
.OnDelete(DeleteBehavior.Cascade)
.HasForeignKey(e => e.CopyId);
builder.Property(e => e.ClientId)
.IsRequired()
.HasColumnName("client_id");
builder.Property(e => e.CopyId)
.IsRequired()
.HasColumnName("copy_id");
builder.Property(e => e.DateOfRental)
.HasColumnName("date_of_rental");
builder.Property(e => e.DateOfReturn)
.HasColumnName("date_of_return");
builder.ToTable("rentals");
builder.HasData(
new Rentals(1, 1, Convert.ToDateTime("2005-07-04"), Convert.ToDateTime("2005-07-05")),
new Rentals(1, 6, Convert.ToDateTime("2005-07-19"), Convert.ToDateTime("2005-07-22")),
new Rentals(2, 3, Convert.ToDateTime("2005-07-24"), Convert.ToDateTime("2005-07-25")),
new Rentals(2, 5, Convert.ToDateTime("2005-07-26"), Convert.ToDateTime("2005-07-27")),
new Rentals(2, 7, Convert.ToDateTime("2005-07-29"), Convert.ToDateTime("2005-07-30")),
new Rentals(3, 12, Convert.ToDateTime("2005-07-10"), Convert.ToDateTime("2005-07-13")),
new Rentals(3, 20, Convert.ToDateTime("2005-07-16"), Convert.ToDateTime("2005-07-17")),
new Rentals(3, 3, Convert.ToDateTime("2005-07-22"), Convert.ToDateTime("2005-07-23")),
new Rentals(3, 7, Convert.ToDateTime("2005-07-24"), Convert.ToDateTime("2005-07-25")),
new Rentals(4, 13, Convert.ToDateTime("2005-07-01"), Convert.ToDateTime("2005-07-05")),
new Rentals(5, 11, Convert.ToDateTime("2005-07-10"), Convert.ToDateTime("2005-07-13")),
new Rentals(6, 1, Convert.ToDateTime("2005-07-06"), Convert.ToDateTime("2005-07-07")),
new Rentals(6, 7, Convert.ToDateTime("2005-07-29"), Convert.ToDateTime("2005-07-30")),
new Rentals(6, 19, Convert.ToDateTime("2005-07-29"), Convert.ToDateTime("2005-07-30")));
}
}
```
|
/content/code_sandbox/src-examples/CodeFirst.DataAccess/Configurations/RentalsConfiguration.cs
|
smalltalk
| 2016-04-08T16:41:51
| 2024-08-16T05:55:59
|
System.Linq.Dynamic.Core
|
zzzprojects/System.Linq.Dynamic.Core
| 1,537
| 654
|
```smalltalk
using CodeFirst.DataAccess.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace CodeFirst.DataAccess.Configurations;
public class MoviesConfiguration : IEntityTypeConfiguration<Movies>
{
public void Configure(EntityTypeBuilder<Movies> builder)
{
builder.HasKey(k => k.MovieId)
.HasName("movies_pkey");
// one to many movie - copies
builder.HasMany(e => e.Copies)
.WithOne(e => e.Movie);
builder.Property(e => e.MovieId)
.ValueGeneratedOnAdd()
.HasColumnName("movie_id");
builder.Property(e => e.Title)
.HasColumnName("title");
builder.Property(e => e.AgeRestriction)
.HasColumnName("age_restriction");
builder.Property(e => e.Price)
.HasColumnName("price");
builder.Property(e => e.Year)
.HasColumnName("year");
builder.ToTable("movies");
builder.HasData(
new Movies(1, "Star Wars Episode IV: A New Hope", 1979, 12, 10f),
new Movies(2, "Ghostbusters", 1984, 12, 5.5f),
new Movies(3, "Terminator", 1984, 15, 8.5f),
new Movies(4, "Taxi Driver", 1976, 17, 5f),
new Movies(5, "Platoon", 1986, 18, 5f),
new Movies(6, "Frantic", 1988, 15, 8.5f),
new Movies(7, "Ronin", 1998, 13, 9.5f),
new Movies(8, "Analyze This", 1999, 16, 10.5f),
new Movies(9, "Leon: the Professional", 1994, 16, 8.5f),
new Movies(10, "Mission Impossible", 1996, 13, 8.5f));
}
}
```
|
/content/code_sandbox/src-examples/CodeFirst.DataAccess/Configurations/MoviesConfiguration.cs
|
smalltalk
| 2016-04-08T16:41:51
| 2024-08-16T05:55:59
|
System.Linq.Dynamic.Core
|
zzzprojects/System.Linq.Dynamic.Core
| 1,537
| 429
|
```smalltalk
using CodeFirst.DataAccess.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace CodeFirst.DataAccess.Configurations;
public class EmployeesConfiguration : IEntityTypeConfiguration<Employees>
{
public void Configure(EntityTypeBuilder<Employees> builder)
{
builder.HasKey(e => e.EmployeeId)
.HasName("employee_id");
builder.Property(e => e.EmployeeId)
.HasColumnName("employee_id");
builder.Property(e => e.Firstname)
.IsRequired()
.HasColumnName("first_name");
builder.Property(e => e.Lastname)
.IsRequired()
.HasColumnName("last_name");
builder.Property(e => e.Salary)
.HasColumnName("salary");
builder.ToTable("employees");
builder.HasData(
new Employees
{EmployeeId = 1, Firstname = "John", Lastname = "Smith", Salary = 150.0f, City = "New York"},
new Employees
{EmployeeId = 2, Firstname = "Ben", Lastname = "Johnson", Salary = 250.0f, City = "New York"},
new Employees
{EmployeeId = 3, Firstname = "Louis", Lastname = "Armstrong", Salary = 75.0f, City = "New Orleans"},
new Employees
{EmployeeId = 4, Firstname = "John", Lastname = "Lennon", Salary = 300.0f, City = "London"},
new Employees
{EmployeeId = 5, Firstname = "Peter", Lastname = "Gabriel", Salary = 150.0f, City = "London"}
);
}
}
```
|
/content/code_sandbox/src-examples/CodeFirst.DataAccess/Configurations/EmployeesConfiguration.cs
|
smalltalk
| 2016-04-08T16:41:51
| 2024-08-16T05:55:59
|
System.Linq.Dynamic.Core
|
zzzprojects/System.Linq.Dynamic.Core
| 1,537
| 348
|
```xml
<Project>
<PropertyGroup>
<MsBuildAllProjects>$(MsBuildAllProjects);$(MsBuildThisFileFullPath)</MsBuildAllProjects>
</PropertyGroup>
<Choose>
<!-- The environment variable `Prerelease` is set in the azure-pipelines.yml file. -->
<When Condition=" '$(Prerelease)' != '' ">
<PropertyGroup>
<!-- Set the version to x.x.x.x-{Prerelease}-1{Build_BuildId} (this is same buildId as defined in the azure-pipelines.yml file). -->
<VersionSuffix>$(Prerelease)-1$(BUILD_BUILDID)</VersionSuffix>
</PropertyGroup>
</When>
</Choose>
</Project>
```
|
/content/code_sandbox/Directory.Build.props
|
xml
| 2016-04-08T16:41:51
| 2024-08-16T05:55:59
|
System.Linq.Dynamic.Core
|
zzzprojects/System.Linq.Dynamic.Core
| 1,537
| 155
|
```unknown
[config]
project = doc\System.Linq.Dynamic.Core.SandCastle
```
|
/content/code_sandbox/.deployment
|
unknown
| 2016-04-08T16:41:51
| 2024-08-16T05:55:59
|
System.Linq.Dynamic.Core
|
zzzprojects/System.Linq.Dynamic.Core
| 1,537
| 14
|
```xml
<Project>
<PropertyGroup>
<PatchVersion>5</PatchVersion>
</PropertyGroup>
</Project>
```
|
/content/code_sandbox/version.xml
|
xml
| 2016-04-08T16:41:51
| 2024-08-16T05:55:59
|
System.Linq.Dynamic.Core
|
zzzprojects/System.Linq.Dynamic.Core
| 1,537
| 26
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.