before_code stringlengths 14 465k | reviewer_comment stringlengths 16 64.5k | after_code stringlengths 9 467k | diff_context stringlengths 0 97k | file_path stringlengths 5 226 | comment_line int32 0 26 | language stringclasses 37
values | quality_score float32 0.07 1 | comment_type stringclasses 9
values | comment_length int32 16 64.5k | before_lines int32 1 17.2k | after_lines int32 1 12.1k | is_negative bool 2
classes | pr_title stringlengths 1 308 | pr_number int32 1 299k | repo_name stringclasses 533
values | repo_stars int64 321 419k | repo_language stringclasses 27
values | reviewer_username stringlengths 0 39 | author_username stringlengths 2 39 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
}
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 the string is a 'word character'
// Word characters are defined as... | There references to regex patterns are not quite accurate, since `unicode.IsLetter()` returns true not only for Latin (ascii) letters. | 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 charac... | @@ -219,7 +219,61 @@ func FSize(f *os.File) int64 {
// IsWordChar returns whether or not the string is a 'word character'
// Word characters are defined as numbers, letters, or '_'
func IsWordChar(r rune) bool {
- return unicode.IsLetter(r) || unicode.IsNumber(r) || r == '_'
+ return IsAlphanumeric(r) || IsWordDelim... | internal/util/util.go | 26 | Go | 0.5 | suggestion | 134 | 51 | 51 | false | Implemented sub-word cursor movement | 2,665 | zyedidia/micro | 13,805 | Go | dmaluka | masmu |
func FSize(f *os.File) int64 {
fi, _ := f.Stat()
return fi.Size()
}
// IsWordChar returns whether or not the string is a 'word character'
// Word characters are defined as numbers, letters, or '_'
func IsWordChar(r rune) bool {
return IsAlphanumeric(r) || IsWordDelimiter(r)
}
// IsUpperWordChar returns whether or ... | IMHO this function is redundant and actually makes the code less readable (what is "word delimiter"? isn't it rather a "subword delimiter"? etc). What's wrong with using simple explicit `== '_'` checks instead? |
// 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) || IsSubwordDelimi... | @@ -219,7 +219,61 @@ func FSize(f *os.File) int64 {
// IsWordChar returns whether or not the string is a 'word character'
// Word characters are defined as numbers, letters, or '_'
func IsWordChar(r rune) bool {
- return unicode.IsLetter(r) || unicode.IsNumber(r) || r == '_'
+ return IsAlphanumeric(r) || IsWordDelim... | internal/util/util.go | 26 | Go | 0.643 | bug | 210 | 51 | 51 | false | Implemented sub-word cursor movement | 2,665 | zyedidia/micro | 13,805 | Go | dmaluka | masmu |
// Word characters are defined as numbers, letters, or '_'
func IsWordChar(r rune) bool {
return IsAlphanumeric(r) || IsWordDelimiter(r)
}
// IsUpperWordChar returns whether or not the string is a 'upper word character'
// Upper word characters are defined as numbers, upper-case letters, or delimiters ([A-Z0-9_])
fun... | This also seems rather unneeded. What's wrong with explicit `!IsWordChar() && !IsWhitespace()` checks?
Moreover, there is already `IsNonAlphaNumeric()`, i.e. a function that uses almost the same naming style but different semantics: it returns true for whitespace. So it you add these functions but leave the existing... |
// 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 character... | @@ -219,7 +219,61 @@ func FSize(f *os.File) int64 {
// IsWordChar returns whether or not the string is a 'word character'
// Word characters are defined as numbers, letters, or '_'
func IsWordChar(r rune) bool {
- return unicode.IsLetter(r) || unicode.IsNumber(r) || r == '_'
+ return IsAlphanumeric(r) || IsWordDelim... | internal/util/util.go | 26 | Go | 0.643 | bug | 751 | 51 | 51 | false | Implemented sub-word cursor movement | 2,665 | zyedidia/micro | 13,805 | Go | dmaluka | masmu |
func IsNoneWordChar(r rune) bool {
return !IsAlphanumeric(r) && !IsWhitespace(r) && !IsWordDelimiter(r)
}
// IsAlphanumeric returns whether or not the string is an 'alphanumeric character'
// Alphanumeric characters are defined as numbers or letters ([A-Za-z0-9])
func IsAlphanumeric(r rune) bool {
return unicode.IsL... | `unicode.IsLetter(r)` check is redundant: `unicode.IsUpper()` and `unicode.IsLower()` return true for letters only.
Which means that `IsUpperLetter()` and `IsLowerLetter()`, as such, are also redundant? |
// 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 == '_'
}
// IsAlphanumeri... | @@ -219,7 +219,61 @@ func FSize(f *os.File) int64 {
// IsWordChar returns whether or not the string is a 'word character'
// Word characters are defined as numbers, letters, or '_'
func IsWordChar(r rune) bool {
- return unicode.IsLetter(r) || unicode.IsNumber(r) || r == '_'
+ return IsAlphanumeric(r) || IsWordDelim... | internal/util/util.go | 26 | Go | 0.571 | performance | 205 | 51 | 51 | false | Implemented sub-word cursor movement | 2,665 | zyedidia/micro | 13,805 | Go | dmaluka | masmu |
}
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 the string is a 'word character'
// Word characters are defined as... | nit: It would be good to keep this sentence in line with the corresponding sentence in `IsWordChar()` description.
Maybe just replace this sentence with `See IsWordChar`? | }
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 num... | @@ -224,6 +224,12 @@ func IsWordChar(r rune) bool {
return unicode.IsLetter(r) || unicode.IsNumber(r) || r == '_'
}
+// IsNonWordChar returns whether or not the string is not a 'word character'
+// Non word characters are defined as all characters not being alphanumerics nor delimiters | internal/util/util.go | 26 | Go | 0.571 | question | 171 | 51 | 51 | false | Implemented sub-word cursor movement | 2,665 | zyedidia/micro | 13,805 | Go | dmaluka | masmu |
// Word characters are defined as numbers, letters or delimiters
func IsWordChar(r rune) bool {
return IsAlphanumeric(r) || IsSubwordDelimiter(r)
}
// IsNonWordChar returns whether or not the string is not a 'word character'
// Non word characters are defined as all characters not being numbers, letters or delimiters... | ...So now that I'm looking more closely at this: the function description, like the function name, should be clear and call it a subword delimiter, not just a delimiter, right?
Maybe let's make it as clear as possible right away, e.g.: "IsSubwordDelimiter returns whether or not the string is a 'sub-word delimiter ch... | // 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-w... | @@ -219,18 +219,68 @@ func FSize(f *os.File) int64 {
}
// IsWordChar returns whether or not the string is a 'word character'
-// Word characters are defined as numbers, letters or '_'
+// Word characters are defined as numbers, letters or delimiters
func IsWordChar(r rune) bool {
- return unicode.IsLetter(r) || un... | internal/util/util.go | 26 | Go | 0.643 | question | 717 | 51 | 51 | false | Implemented sub-word cursor movement | 2,665 | zyedidia/micro | 13,805 | Go | dmaluka | masmu |
// 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 betwe... | As above `IsWordChar(c)` instead of `!IsNonWordChar(c)`? |
// 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 betwe... | @@ -445,14 +503,9 @@ func Clamp(val, min, max int) int {
return val
}
-// IsNonAlphaNumeric returns if the rune is not a number of letter or underscore.
-func IsNonAlphaNumeric(c rune) bool {
- return !unicode.IsLetter(c) && !unicode.IsNumber(c) && c != '_'
-}
-
// IsAutocomplete returns whether a character shoul... | internal/util/util.go | 26 | Go | 0.429 | question | 56 | 51 | 51 | false | Implemented sub-word cursor movement | 2,665 | zyedidia/micro | 13,805 | Go | JoeKar | masmu |
}
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.HasSel... | I would have used `util.IsWordChar(r)` in the first place, but hey...my style is sometimes confusing too.
Furthermore update the comment to not autocomplete in the moment the cursor is on a word character? | }
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.HasSel... | @@ -745,7 +805,7 @@ func (h *BufPane) Autocomplete() bool {
}
r := h.Cursor.RuneUnder(h.Cursor.X)
prev := h.Cursor.RuneUnder(h.Cursor.X - 1)
- if !util.IsAutocomplete(prev) || !util.IsNonAlphaNumeric(r) {
+ if !util.IsAutocomplete(prev) || !util.IsNonWordChar(r) { | internal/action/actions.go | 26 | Go | 0.643 | question | 206 | 51 | 51 | false | Implemented sub-word cursor movement | 2,665 | zyedidia/micro | 13,805 | Go | JoeKar | masmu |
package config
import (
"os"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestAssetDir(t *testing.T) {
t.Parallel()
// Change working directory to runtime if needed
cwd, err := os.Getwd()
assert.NoError(t, err)
if !strings.Contains(cwd, "runtime") {
... | Is changing directories at all necessary? Shouldn't the syntax files be embedded? | package config
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestAssetDir(t *testing.T) {
t.Parallel()
// Test AssetDir
entries, err := AssetDir("syntax")
assert.NoError(t, err)
assert.Contains(t, entries, "go.yaml")
assert.True(t, len(entries) > 5)
}
| @@ -0,0 +1,26 @@
+package config
+
+import (
+ "os"
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func TestAssetDir(t *testing.T) {
+ t.Parallel()
+ // Change working directory to runtime if needed
+ cwd, err := os.Getwd()
+ assert.NoError(t, err)
+ if !s... | runtime/runtime_test.go | 17 | Go | 0.286 | question | 81 | 27 | 17 | false | refactor(runtime): simplify AssetDir() | 2,761 | zyedidia/micro | 13,805 | Go | zyedidia | mjholub |
break
} else {
syntaxFiles = append(syntaxFiles, SyntaxFileBuffer{header, f.Name(), syndef})
}
}
}
if !foundDef {
// search in the default syntax files
for _, f := range config.ListRuntimeFiles(config.RTSyntaxHeader) {
data, err := f.Data()
if err != nil {
screen.TermMessage("Error load... | IIUC adding this `if` is a separate logical change, in particular it makes user's custom syntax files take precedence over built-in syntax files (so this change is useful even regardless of the rest of the PR). Am I correct?
I'd suggest to add this `if` in a separate commit (prior to this commit), to make the PR eas... | }
file, err := highlight.ParseFile(data)
if err != nil {
screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
continue
}
if ((ft == "unknown" || ft == "") && header.MatchFileName(b.Path)) || header.FileType == ft {
syndef, err := highlight.ParseDef(file, header)
if err... | @@ -697,41 +706,78 @@ func (b *Buffer) UpdateRules() {
continue
}
- if ((ft == "unknown" || ft == "") && highlight.MatchFiletype(header.FtDetect, b.Path, b.lines[0].data)) || header.FileType == ft {
+ if ((ft == "unknown" || ft == "") && highlight.MatchFileType(header.FtDetect, b.Path)) || header.FileType ==... | internal/buffer/buffer.go | 26 | Go | 0.643 | suggestion | 334 | 51 | 51 | false | Improve file detection with signature check capabilities | 2,819 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
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 ... | I'd prefer more conventional `length > 1`. | screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
continue
}
foundDef = true
if header.FileType == ft {
b.SyntaxDef = syndef
syntaxFile = f.Name()
break
} else {
syntaxFiles = append(syntaxFiles, syntaxFileBuffer{header, f.Name(), syndef})
}
}
}
... | @@ -697,41 +706,78 @@ func (b *Buffer) UpdateRules() {
continue
}
- if ((ft == "unknown" || ft == "") && highlight.MatchFiletype(header.FtDetect, b.Path, b.lines[0].data)) || header.FileType == ft {
+ if ((ft == "unknown" || ft == "") && highlight.MatchFileType(header.FtDetect, b.Path)) || header.FileType ==... | internal/buffer/buffer.go | 26 | Go | 0.286 | suggestion | 42 | 51 | 51 | false | Improve file detection with signature check capabilities | 2,819 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
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 highlight.... | I'd prefer `!signatureMatch` instead of `signatureMatch == false`.
Ditto line 760. | }
foundDef = true
if header.FileType == ft {
b.SyntaxDef = syndef
syntaxFile = f.Name()
break
} else {
syntaxFiles = append(syntaxFiles, syntaxFileBuffer{header, f.Name(), syndef})
}
}
}
if !foundDef {
// search in the default syntax files
for _, f := range config.ListRuntimeFil... | @@ -697,41 +706,78 @@ func (b *Buffer) UpdateRules() {
continue
}
- if ((ft == "unknown" || ft == "") && highlight.MatchFiletype(header.FtDetect, b.Path, b.lines[0].data)) || header.FileType == ft {
+ if ((ft == "unknown" || ft == "") && highlight.MatchFileType(header.FtDetect, b.Path)) || header.FileType ==... | internal/buffer/buffer.go | 26 | Go | 0.429 | suggestion | 83 | 51 | 51 | false | Improve file detection with signature check capabilities | 2,819 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
header = syntaxFiles[i].Header
signatureMatch = true
}
}
}
}
if !signatureMatch {
syntaxFile = syntaxFiles[0].FileName
b.SyntaxDef = syntaxFiles[0].SyntaxDef
header = syntaxFiles[0].Header
}
} else {
if 0 < length {
syntaxFile = syntaxFiles[0].FileName
b.Sy... | How about reorganizing the code the following way (to avoid duplication of the above 3 lines):
```
length := len(syntaxFiles)
if length > 0 {
signatureMatch := false
if length > 1 {
for i := 0; i < length && !signatureMatch; i++ {
...
}
}
if length == 1 || !signatureMatch {
syntaxFile = syntax... | } else if header.FileType == ft {
syntaxFile = f.Name()
break
}
}
}
if syntaxFile == "" {
length := len(syntaxFiles)
if length > 0 {
signatureMatch := false
if length > 1 {
detectlimit := util.IntOpt(b.Settings["detectlimit"])
lineCount := len(b.lines)
limit := lineCount
if ... | @@ -697,41 +706,78 @@ func (b *Buffer) UpdateRules() {
continue
}
- if ((ft == "unknown" || ft == "") && highlight.MatchFiletype(header.FtDetect, b.Path, b.lines[0].data)) || header.FileType == ft {
+ if ((ft == "unknown" || ft == "") && highlight.MatchFileType(header.FtDetect, b.Path)) || header.FileType ==... | internal/buffer/buffer.go | 26 | Go | 0.857 | suggestion | 425 | 51 | 51 | false | Improve file detection with signature check capabilities | 2,819 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
break
}
}
if syntaxFile == "" {
length := len(syntaxFiles)
if length > 0 {
signatureMatch := false
if length > 1 {
detectlimit := util.IntOpt(b.Settings["detectlimit"])
lineCount := len(b.lines)
limit := 0
if detectlimit > 0 {
if lineCount < detectlimit {
limit = lineCount
... | I see you've moved the detectlimit stuff from the next commit to this one (I guess not on purpose). Could you move it back? :) | screen.TermMessage("Error reading syntax header file", f.Name(), err)
continue
}
if ft == "unknown" || ft == "" {
if header.MatchFileName(b.Path) {
syntaxFiles = append(syntaxFiles, syntaxFileBuffer{header, f.Name(), nil})
}
} else if header.FileType == ft {
syntaxFile = f.Name()
... | @@ -734,16 +748,53 @@ func (b *Buffer) UpdateRules() {
}
if ft == "unknown" || ft == "" {
- if highlight.MatchFiletype(header.FtDetect, b.Path, b.lines[0].data) {
- syntaxFile = f.Name()
- break
+ if highlight.MatchFileName(header, b.Path) {
+ syntaxFiles = append(syntaxFiles, SyntaxFileBuffer{head... | internal/buffer/buffer.go | 26 | Go | 0.429 | suggestion | 126 | 51 | 51 | false | Improve file detection with signature check capabilities | 2,819 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
break
}
}
if syntaxFile == "" {
length := len(syntaxFiles)
if length > 0 {
signatureMatch := false
if length > 1 {
detectlimit := util.IntOpt(b.Settings["detectlimit"])
lineCount := len(b.lines)
limit := 0
if detectlimit > 0 {
if lineCount < detectlimit {
limit = lineCount
... | Looks like it can be made much shorter:
```
limit := lineCount
if detectlimit > 0 && lineCount > detectlimit {
limit = detectlimit
}
``` | screen.TermMessage("Error reading syntax header file", f.Name(), err)
continue
}
if ft == "unknown" || ft == "" {
if header.MatchFileName(b.Path) {
syntaxFiles = append(syntaxFiles, syntaxFileBuffer{header, f.Name(), nil})
}
} else if header.FileType == ft {
syntaxFile = f.Name()
... | @@ -762,9 +762,21 @@ func (b *Buffer) UpdateRules() {
if length > 0 {
signatureMatch := false
if length > 1 {
+ detectlimit := util.IntOpt(b.Settings["detectlimit"])
+ lineCount := len(b.lines)
+ limit := 0
+ if detectlimit > 0 {
+ if lineCount < detectlimit {
+ limit = lineCount
+ }... | internal/buffer/buffer.go | 26 | Go | 0.714 | suggestion | 143 | 51 | 51 | false | Improve file detection with signature check capabilities | 2,819 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
"matchbrace": true,
"mkparents": false,
"permbackup": false,
"readonly": false,
"rmtrailingws": false,
"ruler": true,
"relativeruler": false,
"savecursor": false,
"saveundo": false,
"scrollbar": false,
"scrollmargin": float64(3),
"scrollspeed": float64(2),
... | The options here are sorted alphabetically. And likewise in `options.md`. | "hltaberrors": false,
"hltrailingws": false,
"incsearch": true,
"ignorecase": true,
"indentchar": " ",
"keepautoindent": false,
"matchbrace": true,
"matchbracestyle": "underline",
"mkparents": false,
"permbackup": false,
"readonly": false,
"reload": "p... | @@ -315,6 +316,7 @@ var defaultCommonSettings = map[string]interface{}{
"tabstospaces": false,
"useprimary": true,
"wordwrap": false,
+ "detectlimit": float64(100), | internal/config/settings.go | 26 | Go | 0.357 | style | 73 | 51 | 51 | false | Improve file detection with signature check capabilities | 2,819 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
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 ... | Very nit: I'd prefer `Regex`, not `RegEx`, no need for so much capitalization. | 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 ... | @@ -33,26 +33,25 @@ func (g Group) String() string {
// Then it has the rules which define how to highlight the file
type Def struct {
*Header
-
rules *rules
}
type Header struct {
- FileType string
- FtDetect [2]*regexp.Regexp
+ FileType string
+ FileNameRegEx *regexp.Regexp
+ SignatureRegEx *regexp.R... | pkg/highlight/parser.go | 26 | Go | 0.429 | suggestion | 78 | 51 | 51 | false | Improve file detection with signature check capabilities | 2,819 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
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 bo... | More nitpicking (sorry...): as this is merely an internal helper structure, probably makes sense to keep it actually internal, i.e. non-capitalize its name and its field names? (Not only to avoid exposing it needlessly, but also to make it more clear for code readers that its purpose it purely internal.)
Furthermore... |
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 bo... | @@ -126,6 +126,13 @@ type SharedBuffer struct {
origHash [md5.Size]byte
}
+// SyntaxFileBuffer is a helper structure to store properties of one single syntax file
+type SyntaxFileBuffer struct { | internal/buffer/buffer.go | 26 | Go | 0.643 | refactor | 422 | 51 | 51 | false | Improve file detection with signature check capabilities | 2,819 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
// 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 rep... | Here (with the introduced `nil`) I'm currently unsure if this will work in Go, since the targeting type is passed by reference by default. |
// 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 rep... | @@ -237,7 +237,7 @@ func (eh *EventHandler) Execute(t *TextEvent) {
}
eh.UndoStack.Push(t)
- b, err := config.RunPluginFnBool("onBeforeTextEvent", luar.New(ulua.L, eh.buf), luar.New(ulua.L, t))
+ b, err := config.RunPluginFnBool(nil, "onBeforeTextEvent", luar.New(ulua.L, eh.buf), luar.New(ulua.L, t)) | internal/buffer/eventhandler.go | 26 | Go | 0.643 | suggestion | 138 | 51 | 51 | false | plugins: Add capability to dis-/enable them per buffer | 2,836 | zyedidia/micro | 13,805 | Go | JoeKar | JoeKar |
}
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 =... | init and deinit are a global thing, right? Calling them has effect on all buffers. | }
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 =... | @@ -55,7 +55,26 @@ func (b *Buffer) SetOptionNative(option string, nativeValue interface{}) error {
buf.HighlightSearch = nativeValue.(bool)
}
}
- }
+ } else {
+ for _, pl := range config.Plugins {
+ if option == pl.Name {
+ if nativeValue.(bool) {
+ if !pl.Loaded {
+ pl.Load()
+ }
+ ... | internal/buffer/settings.go | 26 | Go | 0.214 | nitpick | 82 | 41 | 51 | false | plugins: Add capability to dis-/enable them per buffer | 2,836 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
// 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 rep... | Why nil? Shouldn't this be per-buffer too? |
// 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 rep... | @@ -237,7 +237,7 @@ func (eh *EventHandler) Execute(t *TextEvent) {
}
eh.UndoStack.Push(t)
- b, err := config.RunPluginFnBool("onBeforeTextEvent", luar.New(ulua.L, eh.buf), luar.New(ulua.L, t))
+ b, err := config.RunPluginFnBool(nil, "onBeforeTextEvent", luar.New(ulua.L, eh.buf), luar.New(ulua.L, t)) | internal/buffer/eventhandler.go | 26 | Go | 0.143 | question | 42 | 51 | 51 | false | plugins: Add capability to dis-/enable them per buffer | 2,836 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
c := make(map[string]tcell.Style)
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 {
include := string(matches[1])
err = LoadColorscheme(... | What happens if the included colorscheme itself includes the original colorscheme?
(It's a rhetorical question. I already know what happens.) | // 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[s... | @@ -96,7 +97,17 @@ func ParseColorscheme(text string) (map[string]tcell.Style, error) {
continue
}
- matches := parser.FindSubmatch([]byte(line))
+ matches := includeParser.FindSubmatch([]byte(line))
+ if len(matches) == 2 {
+ include := string(matches[1])
+ err = LoadColorscheme(include) | internal/config/colorscheme.go | 26 | Go | 0.357 | question | 145 | 51 | 51 | false | colorscheme: Add capability to include schemes | 2,844 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
}
// 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 Parse... | So now a colorscheme can include itself. Yet still, what if colorscheme A includes colorscheme B which includes colorscheme A? Or if colorscheme A includes colorscheme B which includes colorscheme C which includes colorscheme D which includes colorscheme E which includes colorscheme A? | } 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 link... | @@ -96,7 +97,19 @@ func ParseColorscheme(text string) (map[string]tcell.Style, error) {
continue
}
- matches := parser.FindSubmatch([]byte(line))
+ matches := includeParser.FindSubmatch([]byte(line))
+ if len(matches) == 2 {
+ include := string(matches[1])
+ if include != name { | internal/config/colorscheme.go | 26 | Go | 0.429 | question | 286 | 51 | 51 | false | colorscheme: Add capability to include schemes | 2,844 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
// LoadColorscheme loads the given colorscheme from a directory
func LoadColorscheme(colorschemeName string) error {
file := FindRuntimeFile(RTColorscheme, colorschemeName)
if file == nil {
return errors.New(colorschemeName + " is not a valid colorscheme")
}
if data, err := file.Data(); err != nil {
return err... | `include` seems better than `include:` (more consistent with `color-link`). |
// 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 ... | @@ -81,9 +81,10 @@ func LoadColorscheme(colorschemeName string) error {
// Colorschemes are made up of color-link statements linking a color group to a list of colors
// For example, color-link keyword (blue,red) makes all keywords have a blue foreground and
// red background
-func ParseColorscheme(text string) (map... | internal/config/colorscheme.go | 26 | Go | 0.429 | suggestion | 75 | 51 | 51 | false | colorscheme: Add capability to include schemes | 2,844 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
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
// ParsedColorschemes keeps track of the already pa... | It doesn't need to be publicly visible.
In fact, I think it doesn't even need to be global. You could pass it down to the recursive call as a parameter instead (unless it would unnecessarily complicate the code). | 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... | @@ -15,6 +15,9 @@ var DefStyle tcell.Style = tcell.StyleDefault
// Colorscheme is the current colorscheme
var Colorscheme map[string]tcell.Style
+// ParsedColorschemes keeps track of the already parsed colorschemes
+var ParsedColorschemes []string | internal/config/colorscheme.go | 19 | Go | 0.5 | suggestion | 213 | 44 | 44 | false | colorscheme: Add capability to include schemes | 2,844 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
lines := strings.Split(text, "\n")
c := make(map[string]tcell.Style)
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 {
include... | So the included colorscheme cancels previous colors even if it doesn't override them?
And in general, relying on the recursive call to set the global `Colorscheme` variable, in order to assign it to a local variable and return it only to assign it again to the same global variable, feels... interesting. | 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 _... | @@ -81,22 +85,42 @@ func LoadColorscheme(colorschemeName string) error {
// Colorschemes are made up of color-link statements linking a color group to a list of colors
// For example, color-link keyword (blue,red) makes all keywords have a blue foreground and
// red background
-func ParseColorscheme(text string) (ma... | internal/config/colorscheme.go | 26 | Go | 0.571 | suggestion | 307 | 51 | 51 | false | colorscheme: Add capability to include schemes | 2,844 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
}
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 parsedCol... | No need for "else".
Otherwise, LGTM. | }
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 parsedCol... | @@ -52,51 +52,87 @@ func InitColorscheme() error {
Colorscheme = make(map[string]tcell.Style)
DefStyle = tcell.StyleDefault
- return LoadDefaultColorscheme()
+ c, err := LoadDefaultColorscheme()
+ if err == nil {
+ Colorscheme = c
+ }
+
+ return err
}
// LoadDefaultColorscheme loads the default colorscheme f... | internal/config/colorscheme.go | 26 | Go | 0.071 | suggestion | 39 | 51 | 51 | false | colorscheme: Add capability to include schemes | 2,844 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
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()
}
}
// Init creates and initializes the tcell screen
fun... | I've found that this detection is actually already done by tcell: https://github.com/gdamore/tcell/blob/08c7757cd1c98810e46975da457c033dc8657ad8/terminfo/terminfo.go#L688
See also its readme: https://github.com/gdamore/tcell/blob/08c7757cd1c98810e46975da457c033dc8657ad8/README.md#24-bit-color
So no need to do it ag... | Screen.SetContent(x, y, mainc, combc, style)
if UseFake() && lastCursor.x == x && lastCursor.y == y {
lastCursor.r = mainc
lastCursor.style = style
lastCursor.combc = combc
}
}
// RegisterRawSeq registers a raw escape sequence that should be parsed by tcell
func RegisterRawSeq(r string) {
for _, seq := range... | @@ -141,8 +141,16 @@ func TempStart(screenWasNil bool) {
func Init() error {
drawChan = make(chan bool, 8)
+ // Is true color support available?
+ truecolorAvailable := (os.Getenv("COLORTERM") == "truecolor") ||
+ (os.Getenv("COLORTERM") == "24bit") ||
+ (os.Getenv("COLORTERM") == "24-bit") | internal/screen/screen.go | 26 | Go | 0.643 | bug | 1,278 | 51 | 51 | false | options: Add `truecolor` to control the mode | 2,867 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
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 := (config.GetGlobalOption("truecolor... | Trying to revive this PR... So, why not implement a simple intuitive desirable yet backward-compatible behavior: set `truecolor` to `auto` by default, but let MICRO_TRUECOLOR=1 make truecolor=auto behave like truecolor=on (and ignore MICRO_TRUECOLOR in any other cases, treating is as legacy)? So that the existing behav... | rawSeq = append(rawSeq, r)
if Screen != nil {
Screen.RegisterRawSeq(r)
}
}
// UnregisterRawSeq unregisters a raw escape sequence that should be parsed by tcell
func UnregisterRawSeq(r string) {
for i, seq := range rawSeq {
if seq == r {
rawSeq[i] = rawSeq[len(rawSeq)-1]
rawSeq = rawSeq[:len(rawSeq)-1]
... | @@ -150,9 +150,16 @@ func Init() error {
drawChan = make(chan bool, 8)
// Should we enable true color?
- truecolor := os.Getenv("MICRO_TRUECOLOR") == "1"
-
- if !truecolor {
+ truecolor := (config.GetGlobalOption("truecolor").(string) == "auto") ||
+ (config.GetGlobalOption("truecolor").(string) == "on") ||
+ (... | internal/screen/screen.go | 26 | Go | 0.857 | suggestion | 1,260 | 51 | 51 | false | options: Add `truecolor` to control the mode | 2,867 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
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() err... | With TCELL_TRUECOLOR=enable usage, this comment becomes rather obvious? | 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() err... | @@ -184,10 +184,14 @@ func Init() error {
drawChan = make(chan bool, 8)
// Should we enable true color?
- truecolor := os.Getenv("MICRO_TRUECOLOR") == "1"
-
- if !truecolor {
+ truecolor := config.GetGlobalOption("truecolor").(string)
+ if truecolor == "on" || (truecolor == "auto" && os.Getenv("MICRO_TRUECOLOR") ... | internal/screen/screen.go | 26 | Go | 0.214 | question | 71 | 51 | 51 | false | options: Add `truecolor` to control the mode | 2,867 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
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 = retb... | Why changing the indentation? :)
Sorry, but I'm a neurotic. :D | 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 = retb... | @@ -71,7 +71,7 @@ type Plugin struct {
Info *PluginInfo // json file containing info
Srcs []RuntimeFile // lua files
Loaded bool
- Default bool // pre-installed plugin
+ Default bool // pre-installed plugin | internal/config/plugin.go | 26 | Go | 0.214 | question | 63 | 51 | 51 | false | options: add `matchbracestyle` | 2,876 | zyedidia/micro | 13,805 | Go | JoeKar | toiletbril |
func validateEncoding(option string, value interface{}) error {
_, err := htmlindex.Get(value.(string))
return err
}
func validateMultiOpen(option string, value interface{}) error {
val, ok := value.(string)
if !ok {
return errors.New("Expected string type for multiopen")
}
switch val {
case "tab", "hsplit"... | `matchhighlightstyle` -> `matchbracestyle` | return errors.New("Expected string type for file format")
}
if endingType != "unix" && endingType != "dos" {
return errors.New("File format must be either 'unix' or 'dos'")
}
return nil
}
func validateEncoding(option string, value interface{}) error {
_, err := htmlindex.Get(value.(string))
return err
}
f... | @@ -526,3 +528,19 @@ func validateMultiOpen(option string, value interface{}) error {
return nil
}
+
+func validateMatchBraceStyle(option string, value interface{}) error {
+ val, ok := value.(string)
+
+ if !ok {
+ errors.New("Expected string type for matchhighlightstyle") | internal/config/settings.go | 26 | Go | 0.214 | style | 42 | 37 | 51 | false | options: add `matchbracestyle` | 2,876 | zyedidia/micro | 13,805 | Go | JoeKar | toiletbril |
}
})
}
b.ModifiedThisFrame = false
}
var matchingBraces []buffer.Loc
// bracePairs is defined in buffer.go
if b.Settings["matchbrace"].(bool) {
for _, bp := range buffer.BracePairs {
for _, c := range b.GetCursors() {
if c.HasSelection() {
continue
}
curX := c.X
curLoc := c.Loc... | This doesn't work, since `curLoc` is added to `matchingBraces` below at line 413 regardless of the above check. Also it causes unwanted extra underlining if `left` is true and matchbracestyle is set to underlined (since both curLoc-1 and curLoc are added to `matchingBraces` in this case).
Please take a look again at... | }
})
}
b.ModifiedThisFrame = false
}
var matchingBraces []buffer.Loc
// bracePairs is defined in buffer.go
if b.Settings["matchbrace"].(bool) {
for _, bp := range buffer.BracePairs {
for _, c := range b.GetCursors() {
if c.HasSelection() {
continue
}
curX := c.X
curLoc := c.Loc... | @@ -406,6 +406,9 @@ func (w *BufWindow) displayBuffer() {
mb, left, found := b.FindMatchingBrace(bp, curLoc)
if found {
matchingBraces = append(matchingBraces, mb)
+ if b.Settings["matchbracestyle"].(string) != "highlight" {
+ matchingBraces = append(matchingBraces, curLoc)
+ } | internal/display/bufwindow.go | 26 | Go | 0.643 | style | 370 | 51 | 51 | false | options: add `matchbracestyle` | 2,876 | zyedidia/micro | 13,805 | Go | dmaluka | toiletbril |
// FindMatchingBrace returns the location in the buffer of the matching bracket
// It is given a brace type containing the open and closing character, (for example
// '{' and '}') as well as the location to match from
// TODO: maybe can be more efficient with utf8 package
// returns the location of the matching brace
/... | Regarding Co-authored-by in the commit message: this is the only line I wrote, the rest of this patch was written by JoeKar.
BTW if you want to correct the commit message, I believe it requires force-pushing, so it might be also an occasion to clean up the history of patches in this PR (to ease its further review by... |
var BracePairs = [][2]rune{
{'(', ')'},
{'{', '}'},
{'[', ']'},
}
// FindMatchingBrace returns the location in the buffer of the matching bracket
// It is given a brace type containing the open and closing character, (for example
// '{' and '}') as well as the location to match from
// TODO: maybe can be more effi... | @@ -1008,7 +1008,7 @@ func (b *Buffer) FindMatchingBrace(braceType [2]rune, start Loc) (Loc, bool, boo
leftChar = curLine[start.X-1]
}
var i int
- if startChar == braceType[0] || leftChar == braceType[0] {
+ if startChar == braceType[0] || (leftChar == braceType[0] && startChar != braceType[1]) { | internal/buffer/buffer.go | 26 | Go | 0.5 | bug | 990 | 51 | 51 | false | options: add `matchbracestyle` | 2,876 | zyedidia/micro | 13,805 | Go | dmaluka | toiletbril |
} 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)
}
Ope... | Return was redundant in `CloseOpenBuffers()` but it is not exactly redundant here in `Close()`: it is to break from the loop once we've found our buffer and thus don't need to traverse `OpenBuffers` anymore. | } 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)
}
Ope... | @@ -438,7 +447,6 @@ func (b *Buffer) Close() {
copy(OpenBuffers[i:], OpenBuffers[i+1:])
OpenBuffers[len(OpenBuffers)-1] = nil
OpenBuffers = OpenBuffers[:len(OpenBuffers)-1]
- return | internal/buffer/buffer.go | 26 | Go | 0.571 | suggestion | 207 | 51 | 51 | false | actions: Fix the iteration over a slice under modification in QuitAll() | 2,898 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
}
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... | What if the user wants to use his own custom `default.yaml`? | 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 matche... | @@ -810,6 +810,30 @@ func (b *Buffer) UpdateRules() {
if b.Highlighter == nil || syntaxFile != "" {
if b.SyntaxDef != nil {
b.Settings["filetype"] = b.SyntaxDef.FileType
+ } else {
+ for _, f := range config.ListRuntimeFiles(config.RTSyntax) { | internal/buffer/buffer.go | 26 | Go | 0.429 | question | 60 | 51 | 51 | false | syntax: Provide default.yaml as fallback definition | 2,933 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
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) Cl... | How about de-duplicating the code? The size of `UpdateRules()` is getting scary. | 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(b.SyntaxDef, files)
}
if b.Highlighter == nil ||... | @@ -889,6 +898,33 @@ func (b *Buffer) UpdateRules() {
break
}
}
+
+ if b.SyntaxDef == nil {
+ // search for the default file in the runtime files
+ for _, f := range config.ListRuntimeFiles(config.RTSyntax) {
+ if f.Name() == "default" {
+ data, err := f.Data()
+ if err != nil {
+ ... | internal/buffer/buffer.go | 26 | Go | 0.357 | question | 80 | 51 | 51 | false | syntax: Provide default.yaml as fallback definition | 2,933 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
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, syntaxFile... | ```
if f.Name() == "default" {
continue
}
```
?
If you do this (and if you do this not in a separate commit but by updating this commit), this commit will become, in particular, much easier to review? | ft := b.Settings["filetype"].(string)
if ft == "off" {
b.ClearMatches()
b.SyntaxDef = nil
return
}
// 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
}
... | @@ -710,57 +710,59 @@ func (b *Buffer) UpdateRules() {
var header *highlight.Header
// search for the syntax file in the user's custom syntax files
for _, f := range config.ListRealRuntimeFiles(config.RTSyntax) {
- data, err := f.Data()
- if err != nil {
- screen.TermMessage("Error loading syntax file " + f.N... | internal/buffer/buffer.go | 26 | Go | 0.786 | question | 209 | 51 | 51 | false | syntax: Provide default.yaml as fallback definition | 2,933 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
package highlight
import (
"bytes"
"errors"
"fmt"
"regexp"
"gopkg.in/yaml.v2"
"github.com/zyedidia/micro/v2/internal/config"
"github.com/zyedidia/micro/v2/internal/screen"
)
// A Group represents a syntax group
type Group uint8
// Groups contains all of the groups that are defined
// You can access them in ... | I guess originally the `pkg/highlight` package was supposed to be "independent" of the rest of micro (e.g. to be potentially "reusable" in completely different projects, that are just required to implement the same `LineStates` interface as micro).
I doubt we still need to adhere to that assumption and cannot just a... | 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 ... | @@ -7,6 +7,9 @@ import (
"regexp"
"gopkg.in/yaml.v2"
+
+ "github.com/zyedidia/micro/v2/internal/config"
+ "github.com/zyedidia/micro/v2/internal/screen" | pkg/highlight/parser.go | 12 | Go | 0.643 | refactor | 1,047 | 37 | 37 | false | syntax: Provide default.yaml as fallback definition | 2,933 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
if header == nil {
header, err = MakeHeaderYaml(data)
if err != nil {
screen.TermMessage("Error parsing header for syntax file " + f.Name() + ": " + err.Error())
return nil
}
}
file, err := ParseFile(data)
if err != nil {
screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error()... | These return a Def, not a RuntimeFile. So, rather something like `FindDefInRealRuntimeFiles()` and `FindDefInRuntimeFiles()`?
OTOH, that's a mouthful... If we move these functions to `internal/buffer/buffer.go` before `UpdateRules()`, as I've suggested, then maybe let them be named `findRuntimeFile()` and `findRealR... | 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 = ap... | @@ -298,6 +298,36 @@ func ParseDefFromFile(f config.RuntimeFile, header *Header) *Def {
return syndef
}
+// FindRealRuntimeFile can be used to find a specific definition in the user's
+// custom syntax files
+func FindRealRuntimeFile(name string, header *Header) *Def { | pkg/highlight/parser.go | 26 | Go | 0.643 | suggestion | 639 | 51 | 51 | false | syntax: Provide default.yaml as fallback definition | 2,933 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
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(incl... | Extra variable seems a bit excessive, I'd just "hardcode" `"default"` in both function calls. (BTW it is "hardcoded" also at the beginning of `UpdateRules()`, right? So it if your intention is to avoid harcoding it in more than one place, you should use a variable in all 3 places? But anyway, it seems excessive to me a... | 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(inclu... | @@ -931,31 +951,11 @@ func (b *Buffer) UpdateRules() {
b.Settings["filetype"] = b.SyntaxDef.FileType
} else {
// search for the default file in the user's custom syntax files
- for _, f := range config.ListRealRuntimeFiles(config.RTSyntax) {
- if f.Name() == "default" {
- syndef := parseDefFromFile(... | internal/buffer/buffer.go | 26 | Go | 0.643 | suggestion | 327 | 51 | 51 | false | syntax: Provide default.yaml as fallback definition | 2,933 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
}
size += n
for _, l := range b.lines[1:] {
n, e = h.Write([]byte{'\n'})
if e != nil {
return e
}
size += n
n, e = h.Write(l.data)
if e != nil {
return e
}
size += n
}
}
if size > LargeFileThreshold {
return ErrFileTooLarge
}
h.Sum((*out)[:0])
return nil
}
// parseDefF... | nit: It doesn't sound quite clear what does it mean to "generalize the syntax file parsing".
Actually I guess we can just remove this comment, it's more or less obvious what does this function do anyway. | }
size += n
for _, l := range b.lines[1:] {
n, e = h.Write([]byte{'\n'})
if e != nil {
return e
}
size += n
n, e = h.Write(l.data)
if e != nil {
return e
}
size += n
}
}
if size > LargeFileThreshold {
return ErrFileTooLarge
}
h.Sum((*out)[:0])
return nil
}
func parseDe... | @@ -682,6 +682,37 @@ func calcHash(b *Buffer, out *[md5.Size]byte) error {
return nil
}
+// parseDefFromFile can be used to generalize the syntax file parsing | internal/buffer/buffer.go | 26 | Go | 0.5 | refactor | 206 | 51 | 51 | false | syntax: Provide default.yaml as fallback definition | 2,933 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
}
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.Nam... | nit: "can be used" seems redundant. We can just say what it does, then it will obviously mean that's what it can be used for. (Though I see I myself added such an unneeded "can be used", in the `ScrollAdjust()` description...) |
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()... | @@ -713,6 +713,36 @@ func parseDefFromFile(f config.RuntimeFile, header *highlight.Header) *highlight
return syndef
}
+// findRealRuntimeSyntaxDef can be used to find a specific syntax definition | internal/buffer/buffer.go | 26 | Go | 0.643 | nitpick | 226 | 51 | 51 | false | syntax: Provide default.yaml as fallback definition | 2,933 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
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
... | Why not just
```
if syndef != nil {
return syndef
}
```
?
``` | 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
... | @@ -713,6 +713,36 @@ func parseDefFromFile(f config.RuntimeFile, header *highlight.Header) *highlight
return syndef
}
+// findRealRuntimeSyntaxDef can be used to find a specific syntax definition
+// in the user's custom syntax files
+func findRealRuntimeSyntaxDef(name string, header *highlight.Header) *highlight.... | internal/buffer/buffer.go | 26 | Go | 0.571 | question | 71 | 51 | 51 | false | syntax: Provide default.yaml as fallback definition | 2,933 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
}
return event, nil
}
// 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.... | `TryBindKey()` is also used from Lua, so this escaping might mess up with Lua's own escaping of its strings. So perhaps it's better to do it in `BindCmd()`, not here? (i.e. do it only on the UI level, specifically for the `bind` command)
(I see that, although Lua >=5.2 [supports](https://www.lua.org/manual/5.2/manua... | if !ok {
return nil, errors.New(k + " is not a bindable event")
}
}
return event, nil
}
// 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 err... | @@ -258,6 +258,9 @@ func TryBindKey(k, v string, overwrite bool) (bool, error) {
return false, errors.New("Error reading bindings.json: " + err.Error())
}
+ // Convert possible received string of raw escape sequence
+ k = strings.ReplaceAll(k, "\\x1b", "\x1b") | internal/action/bindings.go | 26 | Go | 0.643 | suggestion | 545 | 51 | 51 | false | bindings: Allow raw escape sequence to be bound with `bind` | 2,959 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
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 &&... | I think it should not be capitalized. Also maybe a bit shorter name? | 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 &&... | @@ -539,6 +539,10 @@ func SetGlobalOptionNative(option string, nativeValue interface{}) error {
return config.WriteSettings(filepath.Join(config.ConfigDir, "settings.json"))
}
+func ConvertRawEscFromString2Byte(rawEsc string) string { | internal/action/command.go | 26 | Go | 0.286 | question | 68 | 51 | 51 | false | bindings: Allow raw escape sequence to be bound with `bind` | 2,959 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
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)
}
// ShowKeyCmd displays the action... | No need to duplicate the comment 3 times either. :) I would move the comment above the function definition. | 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 sequ... | @@ -641,6 +645,9 @@ func (h *BufPane) ShowKeyCmd(args []string) {
return
}
+ // Convert possible received string of raw escape sequence | internal/action/command.go | 26 | Go | 0.429 | refactor | 107 | 51 | 51 | false | bindings: Allow raw escape sequence to be bound with `bind` | 2,959 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
}
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)
}
// ShowKeyCmd displays the action that a k... | I would use it directly without intermediate assignment, e.g. `TryBindKey(convertRawEscStr2Byte(args[0]), args[1], true)`. | 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... | @@ -641,6 +645,9 @@ func (h *BufPane) ShowKeyCmd(args []string) {
return
}
+ // Convert possible received string of raw escape sequence
+ args[0] = ConvertRawEscFromString2Byte(args[0]) | internal/action/command.go | 26 | Go | 0.571 | suggestion | 122 | 51 | 51 | false | bindings: Allow raw escape sequence to be bound with `bind` | 2,959 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
}
// 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 {... | Just noticed this `2Hex` and it seems doesn't make much sense to me. What is a "hexadecimal byte"? It is just a byte.
...So now I have another pedantic suggestion: rename this function to something simple and "generic" like `parseKeyArg()` (i.e. without mentioning raw escape sequence in the function name) and move t... | }
// 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 {... | @@ -634,14 +634,19 @@ func (h *BufPane) ShowCmd(args []string) {
InfoBar.Message(option)
}
+// Convert possible received string of raw escape sequence to a hexadecimal byte
+func convertRawEsc2Hex(rawEsc string) string { | internal/action/command.go | 26 | Go | 0.643 | security | 745 | 51 | 51 | false | bindings: Allow raw escape sequence to be bound with `bind` | 2,959 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
linters[name] = {}
linters[name].filetype = filetype
linters[name].cmd = cmd
linters[name].args = args
linters[name].errorformat = errorformat
linters[name].os = os or {}
linters[name].whitelist = whitelist or false
linters[name].domatch = domatch or false... | Just a note: this change might be unnecessary (though will not hurt either), since it's basically the same compiler.
BTW... it might be a good idea to remove the `-std=c++14` param, to support newer versions of the standard. | linters[name] = {}
linters[name].filetype = filetype
linters[name].cmd = cmd
linters[name].args = args
linters[name].errorformat = errorformat
linters[name].os = os or {}
linters[name].whitelist = whitelist or false
linters[name].domatch = domatch or false... | @@ -66,7 +66,7 @@ function preinit()
end
makeLinter("gcc", "c", "gcc", {"-fsyntax-only", "-Wall", "-Wextra", "%f"}, "%f:%l:%c:.+: %m")
- makeLinter("g++", "c++", "gcc", {"-fsyntax-only","-std=c++14", "-Wall", "-Wextra", "%f"}, "%f:%l:%c:.+: %m")
+ makeLinter("g++", "c++", "g++", {"-fsyntax-only","-std... | runtime/plugins/linter/linter.lua | 26 | Lua | 0.643 | suggestion | 227 | 51 | 51 | false | plugin: Add new `onBufferOptionChanged` callback | 2,962 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
package buffer
import (
"crypto/md5"
"reflect"
luar "layeh.com/gopher-luar"
ulua "github.com/zyedidia/micro/v2/internal/lua"
"github.com/zyedidia/micro/v2/internal/config"
"github.com/zyedidia/micro/v2/internal/screen"
)
func (b *Buffer) ReloadSettings(reloadFiletype bool) {
settings := config.ParsedSettings(... | gofmt complains about the order of these. | package buffer
import (
"crypto/md5"
"reflect"
"github.com/zyedidia/micro/v2/internal/config"
ulua "github.com/zyedidia/micro/v2/internal/lua"
"github.com/zyedidia/micro/v2/internal/screen"
luar "layeh.com/gopher-luar"
)
func (b *Buffer) ReloadSettings(reloadFiletype bool) {
settings := config.ParsedSettings(... | @@ -4,6 +4,8 @@ import (
"crypto/md5"
"reflect"
+ luar "layeh.com/gopher-luar"
+ ulua "github.com/zyedidia/micro/v2/internal/lua" | internal/buffer/settings.go | 8 | Go | 0.071 | suggestion | 41 | 33 | 33 | false | plugin: Add new `onBufferOptionChanged` callback | 2,962 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
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.DoS... | This would be useful for the above `reflect.DeepEqual` check as well. | 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.DoS... | @@ -50,8 +52,16 @@ func (b *Buffer) DoSetOptionNative(option string, nativeValue interface{}) {
return
}
+ oldValue := b.Settings[option] | internal/buffer/settings.go | 26 | Go | 0.429 | suggestion | 69 | 51 | 51 | false | plugin: Add new `onBufferOptionChanged` callback | 2,962 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
}
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.DoSetOptionN... | Any reason why do this before all the below stuff? Shouldn't we rather call `onBufferOptionChanged` at the end, after the option has been fully set? | }
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.DoSetOptionN... | @@ -50,8 +52,16 @@ func (b *Buffer) DoSetOptionNative(option string, nativeValue interface{}) {
return
}
+ oldValue := b.Settings[option]
b.Settings[option] = nativeValue
+ if oldValue != nativeValue { | internal/buffer/settings.go | 26 | Go | 0.571 | question | 148 | 51 | 51 | false | plugin: Add new `onBufferOptionChanged` callback | 2,962 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
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.ErrNoS... | This is what happens when changing any non-string option:
```
Micro encountered an error: *runtime.TypeAssertionError interface conversion: interface {} is bool, not string
runtime/iface.go:261 (0x40a575)
github.com/zyedidia/micro/v2/internal/buffer/settings.go:127 (0x839adb)
github.com/zyedidia/micro/v2/interna... | 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.ErrNoS... | @@ -117,6 +120,15 @@ func (b *Buffer) DoSetOptionNative(option string, nativeValue interface{}) {
if b.OptionCallback != nil {
b.OptionCallback(option, nativeValue)
}
+
+ _, err := config.RunPluginFnBool(b.Settings, "onBufferOptionChanged",
+ luar.New(ulua.L, b),
+ luar.New(ulua.L, option),
+ luar.New(ulua.L,... | internal/buffer/settings.go | 26 | Go | 0.929 | question | 1,352 | 51 | 51 | false | plugin: Add new `onBufferOptionChanged` callback | 2,962 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
} 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 {
... | A bit more idiomatic: `if err := config.RunPluginFn(...); err != nil {` ? | } 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 {
... | @@ -117,6 +120,13 @@ func (b *Buffer) DoSetOptionNative(option string, nativeValue interface{}) {
if b.OptionCallback != nil {
b.OptionCallback(option, nativeValue)
}
+
+ err := config.RunPluginFn("onBufferOptionChanged", | internal/buffer/settings.go | 26 | Go | 0.357 | question | 73 | 51 | 51 | false | plugin: Add new `onBufferOptionChanged` callback | 2,962 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
// QuitCmd closes the main view
func (h *BufPane) QuitCmd(args []string) {
h.Quit()
}
func convertLine(h *BufPane, line string) (int, error) {
lineNum, err := strconv.Atoi(line)
relative := false
if err != nil {
return 0, err
}
// Check for relative numbers
if strings.Contains(line, "-") || strings.Contains(... | I don't think this wrapping makes sense. I think we should just clamp it between the beginning and the end of file, that's the behavior I would expect as a user.
(Actually this clamping is already done below. So now the behavior is even more confusing: we wrap once, and if it still doesn't fit, we clamp it.) | // QuitCmd closes the main view
func (h *BufPane) QuitCmd(args []string) {
h.Quit()
}
func convertLine(h *BufPane, line string) (int, error) {
lineNum := 0
var err error
// Check for special negative movement beginning from the end of the file
if strings.HasPrefix(line, "~") {
lineNum, err = strconv.Atoi(line[... | @@ -697,6 +697,34 @@ func (h *BufPane) QuitCmd(args []string) {
h.Quit()
}
+func convertLine(h *BufPane, line string) (int, error) {
+ lineNum, err := strconv.Atoi(line)
+ relative := false
+ if err != nil {
+ return 0, err
+ }
+
+ // Check for relative numbers
+ if strings.Contains(line, "-") || strings.Contains... | internal/action/command.go | 26 | Go | 0.5 | suggestion | 312 | 51 | 51 | false | command: Add capability to use relative numbers in goto | 2,985 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
func (h *BufPane) GotoCmd(args []string) {
if len(args) <= 0 {
InfoBar.Error("Not enough arguments")
} else {
h.RemoveAllMultiCursors()
if strings.Contains(args[0], ":") {
parts := strings.SplitN(args[0], ":", 2)
line, err := convertLine(h, parts[0])
if err != nil {
InfoBar.Error(err)
return
... | I don't think it's a good idea. When I jump to another line without specifying the column, I expect to be at the beginning of the line, not at some unrelated position somewhere in the middle of it. |
// 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 f... | @@ -782,7 +782,8 @@ func (h *BufPane) GotoCmd(args []string) {
InfoBar.Error(err)
return
}
- h.GotoLoc(buffer.Loc{0, line})
+ col := util.Clamp(h.Buf.GetActiveCursor().X, 0, util.CharacterCount(h.Buf.LineBytes(line)))
+ h.GotoLoc(buffer.Loc{col, line}) | internal/action/command.go | 26 | Go | 0.357 | suggestion | 197 | 51 | 51 | false | command: Add capability to use relative numbers in goto | 2,985 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
}
// 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 *... | Why not `line = line[1:]`?
And generally IMO the code becomes a bit messy (this extra `fromEnd` state we need to remember below, etc). I would prefer:
```
// Check for special negative movement beginning from the end of the file
if strings.HasPrefix(line, "~") {
lineNum, err := strconv.Atoi(line[1:])
if... | }
// 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 *... | @@ -698,16 +698,29 @@ func (h *BufPane) QuitCmd(args []string) {
}
func convertLine(h *BufPane, line string) (int, error) {
+ fromEnd := false
+
+ // Check for special negative movement beginning from the end of the file
+ if strings.Contains(line, "~") {
+ line = strings.ReplaceAll(line, "~", "-") | internal/action/command.go | 26 | Go | 0.857 | question | 717 | 51 | 51 | false | command: Add capability to use relative numbers in goto | 2,985 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
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 {
Info... | Maybe add something like this...
```
if leadingPasteWS == "" {
clipLines := strings.Split(clip, "\n")
if len(clipLines) > 1 {
leadingPasteWS = string(util.GetLeadingWhitespace([]byte(clipLines[1])))
if len(clipLines) > 2 {
for _, clipLine := range clipLines[2:] {
tmpPasteWS :... | 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 {
Info... | @@ -1273,9 +1273,13 @@ func (h *BufPane) PastePrimary() bool {
func (h *BufPane) paste(clip string) {
if h.Buf.Settings["smartpaste"].(bool) {
- if h.Cursor.X > 0 && len(util.GetLeadingWhitespace([]byte(strings.TrimLeft(clip, "\r\n")))) == 0 {
- leadingWS := util.GetLeadingWhitespace(h.Buf.LineBytes(h.Cursor.Y)... | internal/action/actions.go | 26 | Go | 1 | suggestion | 833 | 51 | 51 | false | Smarter smartpaste (#3001) | 3,002 | zyedidia/micro | 13,805 | Go | JoeKar | Andriamanitra |
package config
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"reflect"
"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{}... | Nit: it seems better to make it singular `validateChoice`, to be consistent with other validators names (and afterall it validates just one given choice)? | 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, ... | @@ -22,16 +22,24 @@ type optionValidator func(string, interface{}) error
// a list of settings that need option validators
var optionValidators = map[string]optionValidator{
"autosave": validateNonNegativeValue,
- "clipboard": validateClipboard,
+ "clipboard": validateChoices, | internal/config/settings.go | 25 | Go | 0.571 | question | 154 | 50 | 50 | false | Reduce the available string option validators and add autocompletion for them | 3,021 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
return errors.New(option + " must be non-negative")
}
return nil
}
func validateChoices(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)
}
var choicesStr string
first :=... | You could just use `strings.Join(choices, ", ")`? |
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 := stri... | @@ -466,45 +474,43 @@ func validateNonNegativeValue(option string, value interface{}) error {
return nil
}
-func validateColorscheme(option string, value interface{}) error {
- colorscheme, ok := value.(string)
-
- if !ok {
- return errors.New("Expected string type for colorscheme")
- }
-
- if !ColorschemeExists(... | internal/config/settings.go | 26 | Go | 0.286 | question | 49 | 51 | 43 | false | Reduce the available string option validators and add autocompletion for them | 3,021 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
})
} 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 ... | AFAICS this `realoadAll=false` case is broken. This is what I'm seeing when calling `Reload()` from a plugin:
```
Lua Error: initlua.toggleTabtospaceClick does not exist
Press enter to continue
Lua Error: search.searchClick does not exist
Press enter to continue
Lua Error: nav.jumpBack does not exist
Pre... | })
} 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 ... | @@ -329,12 +329,17 @@ func (h *BufPane) ToggleLogCmd(args []string) {
}
}
-// ReloadCmd reloads all files (syntax files, colorschemes...)
+// ReloadCmd reloads all files (syntax files, colorschemes, plugins...)
func (h *BufPane) ReloadCmd(args []string) {
- ReloadConfig()
+ reloadRuntime(true)
}
+// ReloadConf... | internal/action/command.go | 26 | Go | 1 | bug | 2,236 | 51 | 51 | false | command: Fix `reload` command to correctly initialize and reload all runtime files | 3,062 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
}
}
// 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(reloadAll bool) {
config.InitRuntimeFiles()
err := config.... | This probably should be done *before* reinitializing the list of plugins in `InitRuntimeFiles()`. | }
}
// 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.Ru... | @@ -344,14 +349,40 @@ func ReloadConfig() {
if err != nil {
screen.TermMessage(err)
}
+
+ if reloadAll {
+ err = config.RunPluginFn("deinit") | internal/action/command.go | 26 | Go | 0.429 | suggestion | 97 | 51 | 51 | false | command: Fix `reload` command to correctly initialize and reload all runtime files | 3,062 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
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... | nit: This `init()` seems not needed now. `InitRuntimeFiles()` is called during early startup anyway. | 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... | @@ -40,15 +40,12 @@ var allFiles [][]RuntimeFile
var realFiles [][]RuntimeFile
func init() { | internal/config/rtfiles.go | 26 | Go | 0.5 | nitpick | 100 | 51 | 51 | false | command: Fix `reload` command to correctly initialize and reload all runtime files | 3,062 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
// 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.N... | This assumes that the pattern is of the form `*.ext`, which may not always be the case. I see `AddRuntimeFilesFromAssets()` can be also called from lua, so the pattern may be arbitrary.
Can't we just do this?
```
if f.Name() == rf.Name() {
``` |
// 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.N... | @@ -129,8 +129,15 @@ func AddRuntimeFilesFromAssets(fileType RTFiletype, directory, pattern string) {
if err != nil {
return
}
+
+assetLoop:
for _, f := range files {
if ok, _ := path.Match(pattern, f); ok {
+ for _, rf := range realFiles[fileType] {
+ if f == rf.Name()+strings.TrimPrefix(pattern, "*")... | internal/config/rtfiles.go | 26 | Go | 0.786 | suggestion | 249 | 51 | 51 | false | rtfiles: Give user defined runtime files precedence over asset files | 3,066 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
}
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 S... | `else` is not needed after `return`, and that's what I actually had in mind. We can move the bulk of the function out of this `if`, since we are done with the `local` case and can forget about it.
For cleanliness all this can be done in 2 separate commits (no matter in which order): the actual fix for unneeded rewri... | 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.SetActiv... | @@ -479,7 +479,10 @@ func SetGlobalOptionNative(option string, nativeValue interface{}) error {
}
}
- if !local {
+ if local {
+ MainTab().CurPane().Buf.SetOptionNative(option, nativeValue)
+ return nil
+ } else { | internal/action/command.go | 26 | Go | 0.643 | refactor | 345 | 51 | 51 | false | command: Prevent re-writing settings in case of local option | 3,178 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
return chosen, suggestions
}
// filetypeComplete autocompletes filetype
func filetypeComplete(input string) (string, []string) {
var suggestions []string
// Since we need to complete the file type instead of the file name
// we need to parse the RTSyntax* files and search for a matching FileType.
// The followin... | If the user (wrongfully) adds a file with `filetype: "unknown"` or `filetype: "off"` to `~/.config/micro/syntax`, we get duplicated suggestions for `unknown` or `off`. | 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 fi... | @@ -81,9 +82,40 @@ func colorschemeComplete(input string) (string, []string) {
func filetypeComplete(input string) (string, []string) {
var suggestions []string
- for _, f := range config.ListRuntimeFiles(config.RTSyntax) {
- if strings.HasPrefix(f.Name(), input) {
- suggestions = append(suggestions, f.Name())
... | internal/action/infocomplete.go | 26 | Go | 0.714 | bug | 167 | 51 | 51 | false | infocomplete: Complete filetypes (follow-up) | 3,218 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
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 {
chos... | The comment is confusing to a casual reader not familiar with the context (what "previous state"? "the file type instead of the file name" - wtf? which file name? etc). | 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 {
chos... | @@ -81,9 +82,40 @@ func colorschemeComplete(input string) (string, []string) {
func filetypeComplete(input string) (string, []string) {
var suggestions []string
- for _, f := range config.ListRuntimeFiles(config.RTSyntax) {
- if strings.HasPrefix(f.Name(), input) {
- suggestions = append(suggestions, f.Name())
... | internal/action/infocomplete.go | 26 | Go | 0.571 | suggestion | 168 | 51 | 51 | false | infocomplete: Complete filetypes (follow-up) | 3,218 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
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(L... | I would do this (and line 245) in a separate commit, with an explanation in the commit message that this removes unneeded recursion and thus allows locking without deadlocks as a preparation for bla-bla-bla, for the descendants who will dig through the git history and wonder what was this for. | 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... | @@ -233,14 +235,14 @@ func (la *LineArray) insertByte(pos Loc, value byte) {
// joinLines joins the two lines a and b
func (la *LineArray) joinLines(a, b int) {
- la.insert(Loc{len(la.lines[a].data), a}, la.lines[b].data)
+ la.lines[a].data = append(la.lines[a].data, la.lines[b].data...) | internal/buffer/line_array.go | 26 | Go | 0.643 | bug | 294 | 51 | 51 | false | buffer: Add proper lock mechanism to lock the full `LineArray` instead of single lines | 3,224 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
}
// substr returns the string representation between two locations (non-locked)
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]
d... | I don't think we need locking in this and other functions that are only called from the main goroutine and only read the buffer, not modify it. | 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([]by... | @@ -310,8 +314,17 @@ func (la *LineArray) Substr(start, end Loc) []byte {
return str
}
+// Substr returns the string representation between two locations (locked)
+func (la *LineArray) Substr(start, end Loc) []byte {
+ la.lock.Lock() | internal/buffer/line_array.go | 26 | Go | 0.357 | suggestion | 143 | 51 | 51 | false | buffer: Add proper lock mechanism to lock the full `LineArray` instead of single lines | 3,224 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
defer la.lock.Unlock()
return la.substr(start, end)
}
// LinesNum returns the number of lines in the buffer
func (la *LineArray) LinesNum() int {
la.lock.Lock()
defer la.lock.Unlock()
return len(la.lines)
}
// Start returns the start of the buffer
func (la *LineArray) Start() Loc {
return Loc{0, 0}
}
// End re... | Any actual examples of those "bulk modifications"?
I'm assuming there are none. So the actual goal of this commit is not to support bulk modifications but to allow the highlighter to explicitly lock the linearray via `input.Lock()` and `input.Unlock()` (in the next commit)?
AFAICS since the next commit the highli... | 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 *Line... | @@ -341,56 +341,81 @@ func (la *LineArray) End() Loc {
return Loc{util.CharacterCount(la.lines[numlines-1].data), numlines - 1}
}
-// LineBytes returns line n as an array of bytes
-func (la *LineArray) LineBytes(n int) []byte {
- la.lock.Lock()
- defer la.lock.Unlock()
+// LineBytes returns line n as an array of b... | internal/buffer/line_array.go | 26 | Go | 0.786 | performance | 1,979 | 51 | 51 | false | buffer: Add proper lock mechanism to lock the full `LineArray` instead of single lines | 3,224 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
}
input.Lock()
line := input.LineBytesNoLock(i)
highlights := make(LineMatch)
var match LineMatch
if i == 0 || input.StateNoLock(i-1) == nil {
match = h.highlightEmptyRegion(highlights, 0, true, i, line, false)
} else {
match = h.highlightRegion(highlights, 0, true, i, line, input.StateNoLock(i-1),... | No locking at all here?
Looks like one more argument for restoring per-line locks for `state` and `match`. | // 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)
va... | @@ -350,10 +355,11 @@ func (h *Highlighter) ReHighlightStates(input LineStates, startline int) int {
h.lastRegion = nil
if startline > 0 {
- h.lastRegion = input.State(startline - 1)
+ h.lastRegion = input.StateNoLock(startline - 1) | pkg/highlight/highlighter.go | 26 | Go | 0.5 | suggestion | 107 | 51 | 51 | false | buffer: Add proper lock mechanism to lock the full `LineArray` instead of single lines | 3,224 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
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()
line := input.LineBytesNoLock(lineN)
highlights := make(LineMatch)
h.lastRegi... | nit: `defer input.Unlock()` would suit. | 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)
... | @@ -377,12 +384,13 @@ func (h *Highlighter) ReHighlightStates(input LineStates, startline int) int {
// ReHighlightLine will rehighlight the state and match for a single line
func (h *Highlighter) ReHighlightLine(input LineStates, lineN int) {
- line := input.LineBytes(lineN)
+ input.Lock() | pkg/highlight/highlighter.go | 26 | Go | 0.214 | nitpick | 39 | 33 | 48 | false | buffer: Add proper lock mechanism to lock the full `LineArray` instead of single lines | 3,224 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
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 ... | Just a note: I can actually imagine a use for it: if we move all the highlighting to the async goroutine (to fix the other race we were talking about: the race between initial highlighting in the async goroutine and rehighlighting in the main goroutine; i.e. to ensure that initial highlighting and rehighlighting for th... | 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 ... | @@ -46,9 +46,8 @@ type searchState struct {
type Line struct {
data []byte
- state highlight.State
- match highlight.LineMatch
- rehighlight bool | internal/buffer/line_array.go | 26 | Go | 0.643 | suggestion | 629 | 51 | 51 | false | buffer: Add proper lock mechanism to lock the full `LineArray` instead of single lines | 3,224 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
}
// 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 return... | These should be before trying to lock `la.lines[lineN].lock`.
Because of this, the test actually still fails: I've run the test 100 times, 99 passed, but 1 failed, with `index out of range` in `SetState()`. | 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.l... | @@ -337,27 +337,39 @@ func (la *LineArray) LineBytes(lineN int) []byte {
func (la *LineArray) State(lineN int) highlight.State {
la.lines[lineN].lock.Lock()
defer la.lines[lineN].lock.Unlock()
+ if lineN >= len(la.lines) || lineN < 0 { | internal/buffer/line_array.go | 26 | Go | 0.643 | bug | 209 | 51 | 51 | false | buffer: Add proper lock mechanism to lock the full `LineArray` instead of single lines | 3,224 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
// 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... | Hmmm... strictly speaking, even calling `LinesNum()` without locking (i.e. obtaining `len(la.lines)` while `la.lines` may change in the meantime) is probably not guaranteed to be safe. (Though I can suspect that it is actually safe in practice, assuming that `len()` is implemented as a simple `int` read which is atomic... |
// 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... | @@ -304,6 +306,7 @@ func (h *Highlighter) HighlightString(input string) []LineMatch {
// HighlightStates correctly sets all states for the buffer
func (h *Highlighter) HighlightStates(input LineStates) {
for i := 0; i < input.LinesNum(); i++ { | pkg/highlight/highlighter.go | 26 | Go | 0.857 | suggestion | 839 | 51 | 51 | false | buffer: Add proper lock mechanism to lock the full `LineArray` instead of single lines | 3,224 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
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,
m... | nit: maybe add an empty line after? | }
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: []byt... | @@ -206,6 +207,8 @@ func (la *LineArray) newlineBelow(y int) {
// Inserts a byte array at a given location
func (la *LineArray) insert(pos Loc, value []byte) {
+ la.lock.Lock()
+ defer la.lock.Unlock() | internal/buffer/line_array.go | 26 | Go | 0.071 | question | 35 | 51 | 51 | false | buffer: Add proper lock mechanism to lock the full `LineArray` instead of single lines | 3,224 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
}
// 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... | nit: maybe add an empty line after? | 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.de... | @@ -251,6 +254,8 @@ func (la *LineArray) split(pos Loc) {
// removes from start to end
func (la *LineArray) remove(start, end Loc) []byte {
+ la.lock.Lock()
+ defer la.lock.Unlock() | internal/buffer/line_array.go | 26 | Go | 0.071 | question | 35 | 51 | 51 | false | buffer: Add proper lock mechanism to lock the full `LineArray` instead of single lines | 3,224 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
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{' '},
sta... | Hmm, also need locking in Buffer's `Retab()`. | 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] ... | @@ -206,6 +207,8 @@ func (la *LineArray) newlineBelow(y int) {
// Inserts a byte array at a given location
func (la *LineArray) insert(pos Loc, value []byte) {
+ la.lock.Lock() | internal/buffer/line_array.go | 26 | Go | 0.214 | suggestion | 45 | 51 | 51 | false | buffer: Add proper lock mechanism to lock the full `LineArray` instead of single lines | 3,224 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
if r == braceType[1] {
i++
} else if r == braceType[0] {
i--
if i == 0 {
if startChar == braceType[1] {
return Loc{x, y}, false, true
}
return Loc{x, y}, true, true
}
}
}
}
}
return start, true, false
}
// Retab changes all tabs to spaces or vice versa
fu... | I don't think this check is needed here. The number of lines is only changed by the main goroutine, and this code is only running in the main goroutine.
I think we can just add `b.Lock()` and `b.Unlock()` around `b.lines[i].data = append(ws, l...)`.
BTW, this raw access to `data` from here looks ugly, and we can ... | if r == braceType[1] {
i++
} else if r == braceType[0] {
i--
if i == 0 {
if startChar == braceType[1] {
return Loc{x, y}, false, true
}
return Loc{x, y}, true, true
}
}
}
}
}
return start, true, false
}
// Retab changes all tabs to spaces or vice versa
fu... | @@ -1167,9 +1167,14 @@ func (b *Buffer) Retab() {
tabsize := util.IntOpt(b.Settings["tabsize"])
dirty := false
- for i := 0; i < b.LinesNum(); i++ {
- l := b.LineBytes(i)
+ for i := 0; ; i++ {
+ b.Lock()
+ if i >= b.LinesNum() { | internal/buffer/buffer.go | 26 | Go | 0.786 | bug | 928 | 51 | 51 | false | buffer: Add proper lock mechanism to lock the full `LineArray` instead of single lines | 3,224 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
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[... | I think we could avoid doing the map lookup twice
```suggestion
if start, ok := regionInfo["start"]; ok {
start := start.(string)
``` | 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[... | @@ -408,22 +412,44 @@ func parseRegion(group string, regionInfo map[interface{}]interface{}, prevRegio
r.group = groupNum
r.parent = prevRegion
- r.start, err = regexp.Compile(regionInfo["start"].(string))
+ // start is mandatory
+ if _, ok := regionInfo["start"]; ok {
+ start := regionInfo["start"].(string) | pkg/highlight/parser.go | 26 | Go | 0.786 | suggestion | 140 | 51 | 51 | false | parser: Check and prompt for empty patterns and region properties (fix crash) | 3,256 | zyedidia/micro | 13,805 | Go | Andriamanitra | JoeKar |
size += n
n, e = h.Write(l.data)
if e != nil {
return e
}
size += n
}
}
if size > LargeFileThreshold {
return ErrFileTooLarge
}
h.Sum((*out)[:0])
return nil
}
func parseDefFromFile(f config.RuntimeFile, header *highlight.Header) *highlight.Def {
data, err := f.Data()
if err != nil {
s... | But `highlight.MakeHeader()` can only be used, when we iterate over `config.RTSyntaxHeader`, otherwise we can't guarantee, that we access the correct lines or am I wrong?
So in case of `findRuntimeSyntaxDef()` we could iterate over the `config.RTSyntaxHeader` first, to create the `header` structure and then iterate ov... | size += n
n, e = h.Write(l.data)
if e != nil {
return e
}
size += n
}
}
if size > LargeFileThreshold {
return ErrFileTooLarge
}
h.Sum((*out)[:0])
return nil
}
func parseDefFromFile(f config.RuntimeFile, header *highlight.Header) *highlight.Def {
data, err := f.Data()
if err != nil {
s... | @@ -690,6 +690,7 @@ func parseDefFromFile(f config.RuntimeFile, header *highlight.Header) *highlight
}
if header == nil {
+ // TODO: use faster highlight.MakeHeader() when possible | internal/buffer/buffer.go | 26 | Go | 0.643 | bug | 417 | 51 | 51 | false | Follow-ups after adding `default.yaml` support | 3,259 | zyedidia/micro | 13,805 | Go | JoeKar | dmaluka |
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 u... | Yep, user defined includes aren't considered yet, but are worth to be considered.
It wasn't in the scope of my PR. |
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 > ... | @@ -909,10 +912,22 @@ func (b *Buffer) UpdateRules() {
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("defa... | internal/buffer/buffer.go | 26 | Go | 0.429 | suggestion | 115 | 51 | 51 | false | Follow-ups after adding `default.yaml` support | 3,259 | zyedidia/micro | 13,805 | Go | JoeKar | dmaluka |
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.TermMess... | Yep, this could have been rearranged by me already, sorry. | 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(syntaxF... | @@ -909,10 +912,22 @@ func (b *Buffer) UpdateRules() {
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("defa... | internal/buffer/buffer.go | 26 | Go | 0.286 | suggestion | 58 | 51 | 51 | false | Follow-ups after adding `default.yaml` support | 3,259 | zyedidia/micro | 13,805 | Go | JoeKar | dmaluka |
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 syn... | So, I was wrong about this one too: since #3066 we already ensure that exactly one file will be included.
This `len(files) >= len(includes)` check is now not strictly necessary, but it provides a simple optimization (to exit the loop earlier), so we can keep it. | 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 {
... | @@ -950,6 +952,8 @@ func (b *Buffer) UpdateRules() {
break
}
}
+ // TODO: fix this mess. For each include, we should include
+ // exactly one file: either a built-in one or a user's custom one | internal/buffer/buffer.go | 26 | Go | 0.571 | bug | 265 | 51 | 51 | false | Follow-ups after adding `default.yaml` support | 3,259 | zyedidia/micro | 13,805 | Go | dmaluka | dmaluka |
}
// 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 {... | Why not keep it returning `*BufPane`, and in the callers just check if the returned value is not nil?
The lua-exported function returns `Pane`, yes, but according to the documentation it should return `*BufPane`. Isn't it better to fix it to be in accordance with the documentation? | // 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 {
... | @@ -345,10 +347,16 @@ func (t *Tab) Resize() {
}
// CurPane returns the currently active pane
-func (t *Tab) CurPane() *BufPane {
- p, ok := t.Panes[t.active].(*BufPane)
+func (t *Tab) CurPane() Pane { | internal/action/tab.go | 26 | Go | 0.643 | question | 285 | 39 | 31 | false | action: Stop processing chained actions/commands in the moment the current `Pane` is not a `BufPane` (fix crash) | 3,261 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
// 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 {
... | We don't need to convert `Pane` to `Pane`, it is already a `Pane`. | 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 :... | @@ -345,10 +347,16 @@ func (t *Tab) Resize() {
}
// CurPane returns the currently active pane
-func (t *Tab) CurPane() *BufPane {
- p, ok := t.Panes[t.active].(*BufPane)
+func (t *Tab) CurPane() Pane {
+ p, ok := t.Panes[t.active].(Pane) | internal/action/tab.go | 26 | Go | 0.357 | suggestion | 66 | 38 | 30 | false | action: Stop processing chained actions/commands in the moment the current `Pane` is not a `BufPane` (fix crash) | 3,261 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
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 {
cursors := h.Buf.GetCursors()
success := true
for i, a := range actionfns {
... | Doesn't sound quite clear to me. I'd leave the existing comment as is, and add a comment inside the `if !ok`, e.g.: "if the new pane is not a BufPane, stop". | 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 {
cursors := h.Buf.GetCursors()
success := true
for i, a := range actionfns {
... | @@ -166,8 +166,12 @@ func BufMapEvent(k Event, action string) {
break
}
}
- // if the action changed the current pane, update the reference
- h = MainTab().CurPane()
+ // if the action changed the current BufPane to a BufPane again, update the reference | internal/action/bufpane.go | 26 | Go | 0.5 | suggestion | 157 | 51 | 51 | false | action: Stop processing chained actions/commands in the moment the current `Pane` is not a `BufPane` (fix crash) | 3,261 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
screen.TermMessage("Error in bindings: action", a, "does not exist")
continue
}
actionfns = append(actionfns, afn)
}
bufAction := func(h *BufPane, te *tcell.EventMouse) bool {
cursors := h.Buf.GetCursors()
success := true
for i, a := range actionfns {
innerSuccess := true
for j, c := range curso... | It always return true otherwise. It returning `innerSuccess` here useful? Looks like the return value of this function is never really used.
In other words, can we just `break` here? | screen.TermMessage("Error in bindings: action", a, "does not exist")
continue
}
actionfns = append(actionfns, afn)
}
bufAction := func(h *BufPane, te *tcell.EventMouse) bool {
cursors := h.Buf.GetCursors()
success := true
for i, a := range actionfns {
innerSuccess := true
for j, c := range curso... | @@ -166,8 +166,12 @@ func BufMapEvent(k Event, action string) {
break
}
}
- // if the action changed the current pane, update the reference
- h = MainTab().CurPane()
+ // if the action changed the current BufPane to a BufPane again, update the reference
+ bp, ok := MainTab().CurPane().(*BufPane)
... | internal/action/bufpane.go | 26 | Go | 0.571 | question | 185 | 51 | 51 | false | action: Stop processing chained actions/commands in the moment the current `Pane` is not a `BufPane` (fix crash) | 3,261 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
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("", "", buf... | I think this error message is gonna be confusing to the user in *any* scenarios of using `SetGlobalOptionNative()`.
I think `SetGlobalOptionNative()` should not display any error message in the infobar on its own, it should rather *return* an error to the caller. | 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("", "", buf... | @@ -516,7 +516,11 @@ func SetGlobalOptionNative(option string, nativeValue interface{}) error {
// check for local option first...
for _, s := range config.LocalSettings {
if s == option {
- MainTab().CurPane().Buf.SetOptionNative(option, nativeValue)
+ if bp, ok := MainTab().CurPane().(*BufPane); ok {
+ ... | internal/action/command.go | 26 | Go | 0.786 | suggestion | 266 | 51 | 51 | false | action: Stop processing chained actions/commands in the moment the current `Pane` is not a `BufPane` (fix crash) | 3,261 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
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(act... | I don't think this is equivalent to the previous logic. Also this seems buggy.
1. In the previous logic, if the action failed for the given cursor, we still keep executing it for the remaining cursors, before stopping the action chain. In your new logic, we stop as soon as the action failed, so some cursors may remain... |
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(act... | @@ -151,24 +151,22 @@ func BufMapEvent(k Event, action string) {
}
bufAction := func(h *BufPane, te *tcell.EventMouse) bool {
cursors := h.Buf.GetCursors()
- success := true
for i, a := range actionfns {
- innerSuccess := true
+ success := true
for j, c := range cursors {
if c == nil {
con... | internal/action/bufpane.go | 26 | Go | 0.714 | bug | 1,157 | 51 | 51 | false | action: Stop processing chained actions/commands in the moment the current `Pane` is not a `BufPane` (fix crash) | 3,261 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
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... | I'd rather add a generic function which would just compare two arbitrary events (i.e. what you are doing at lines 261-276), i.e. just a replacement for `e == key`, nothing more.
If you also want to de-duplicate the outer `for ev := range parsed` loop as well, - ok, maybe that's a good idea too. But that could be imp... | 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... | @@ -251,6 +251,35 @@ func findEvent(k string) (Event, error) {
return event, nil
}
+func compareEvents(keyEvent Event, parsed map[string]interface{}) (bool, string) { | internal/action/bindings.go | 26 | Go | 0.643 | refactor | 490 | 51 | 51 | false | bindings: Correct `KeySequenceEvent` comparison (fix crash) | 3,266 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
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 compareEvents(keyEvent Event, parsed map[... | I'd prefer a more idiomatic and readable way, like:
```
switch e := event.(type) {
case KeySequenceEvent:
k, ok := keyEvent.(KeySequenceEvent)
if !ok {
return false
}
for ...
default:
return event == keyEvent
}
``` |
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 {
s... | @@ -251,6 +251,35 @@ func findEvent(k string) (Event, error) {
return event, nil
}
+func compareEvents(keyEvent Event, parsed map[string]interface{}) (bool, string) {
+ var event string
+ keySequence, keyIsKeySequence := keyEvent.(KeySequenceEvent)
+
+parseLoop:
+ for event = range parsed {
+ if e, err := findEve... | internal/action/bindings.go | 26 | Go | 1 | suggestion | 235 | 51 | 51 | false | bindings: Correct `KeySequenceEvent` comparison (fix crash) | 3,266 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
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... | nit: Maybe something like `eventsEqual()` (to make it unambiguous what is the return value)? | 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... | @@ -251,6 +251,27 @@ func findEvent(k string) (Event, error) {
return event, nil
}
+func compareEvents(a Event, b Event) bool { | internal/action/bindings.go | 26 | Go | 0.357 | question | 92 | 51 | 51 | false | bindings: Correct `KeySequenceEvent` comparison (fix crash) | 3,266 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
}, 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")
... | Hmm... My apologies, I've realized that the style I suggested makes it rather confusing in this case: it makes it non-obvious that the function behaves symmetrically with regard to both arguments.
Maybe something like:
```
func equalEvents(e1 Event, e2 Event) {
seq1, ok1 := e1.(KeySequenceEvent)
seq2, ok2 := e... | }, 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")
... | @@ -251,6 +251,27 @@ func findEvent(k string) (Event, error) {
return event, nil
}
+func compareEvents(a Event, b Event) bool {
+ switch aSequence := a.(type) { | internal/action/bindings.go | 26 | Go | 0.786 | suggestion | 412 | 51 | 51 | false | bindings: Correct `KeySequenceEvent` comparison (fix crash) | 3,266 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
t.Scroll(-4)
return
} else if my == t.Y && mx == t.Width-1 {
t.Scroll(4)
return
}
if len(t.List) > 1 {
ind := t.LocFromVisual(buffer.Loc{mx, my})
if ind != -1 {
t.SetActive(ind)
return
}
if my == 0 {
return
}
}
case tcell.ButtonNone:
if t.List[t.Active... | It prevents resizing if the active tab changed, but still doesn't prevent it if the screen stopped.
Looks like we should further unify `ReleaseMouse()` which you unified in the next commit (which is nice BTW, thanks), to make it also reset `tab.resizing` for each tab. (And then probably also reuse `ReleaseMouse()` h... | t.Scroll(-4)
return
} else if my == t.Y && mx == t.Width-1 {
t.Scroll(4)
return
}
if len(t.List) > 1 {
ind := t.LocFromVisual(buffer.Loc{mx, my})
if ind != -1 {
t.SetActive(ind)
return
}
if my == 0 {
return
}
}
case tcell.ButtonNone:
if t.List[t.Active... | @@ -124,6 +124,17 @@ func (t *TabList) HandleEvent(event tcell.Event) {
return
}
}
+ case tcell.ButtonNone:
+ if t.List[t.Active()].release {
+ // Mouse release received, while already released:
+ // Check for unreleased tabs which are resizing and reset them.
+ for _, tab := range t.List {
+... | internal/action/tab.go | 26 | Go | 0.643 | suggestion | 379 | 51 | 51 | false | Fix lost mouse release events in case the pane becomes inactive | 3,271 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
}
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... | nit: Maybe `ResetMouse()`? (I'm ok with either name actually.) | 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 s... | @@ -177,6 +177,21 @@ func (t *TabList) SetActive(a int) {
}
}
+// ReleaseMouse 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) Relea... | internal/action/tab.go | 26 | Go | 0.429 | nitpick | 62 | 51 | 51 | false | Fix lost mouse release events in case the pane becomes inactive | 3,271 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
case *tcell.EventResize:
t.Resize()
case *tcell.EventMouse:
mx, my := e.Position()
switch e.Buttons() {
case tcell.Button1:
if my == t.Y && mx == 0 {
t.Scroll(-4)
return
} else if my == t.Y && mx == t.Width-1 {
t.Scroll(4)
return
}
if len(t.List) > 1 {
ind := t.LocFromVisual(bu... | The `...reset mouse` part doesn't look useful. It is clear from the name that `ResetMouse()` resets mouse. | case *tcell.EventResize:
t.Resize()
case *tcell.EventMouse:
mx, my := e.Position()
switch e.Buttons() {
case tcell.Button1:
if my == t.Y && mx == 0 {
t.Scroll(-4)
return
} else if my == t.Y && mx == t.Width-1 {
t.Scroll(4)
return
}
if len(t.List) > 1 {
ind := t.LocFromVisual(bu... | @@ -124,6 +124,11 @@ func (t *TabList) HandleEvent(event tcell.Event) {
return
}
}
+ case tcell.ButtonNone:
+ if t.List[t.Active()].release {
+ // Mouse release received, while already released...reset mouse | internal/action/tab.go | 26 | Go | 0.571 | suggestion | 106 | 51 | 51 | false | Fix lost mouse release events in case the pane becomes inactive | 3,271 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
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
... | This comment doesn't look useful, it doesn't explain anything that is not already clear from the code. |
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
... | @@ -172,6 +177,11 @@ func (t *TabList) SetActive(a int) {
// and the mouse state is still pressed.
func (t *TabList) ResetMouse() {
for _, tab := range t.List {
+ // Check for unreleased tabs which are resizing and reset them. | internal/action/tab.go | 26 | Go | 0.429 | suggestion | 102 | 51 | 51 | false | Fix lost mouse release events in case the pane becomes inactive | 3,271 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
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... | And this comment doesn't look very useful either...
Let's add comments when they actually explain something non-obvious, otherwise they just consume space. | 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 sit... | @@ -172,6 +177,11 @@ func (t *TabList) SetActive(a int) {
// and the mouse state is still pressed.
func (t *TabList) ResetMouse() {
for _, tab := range t.List {
+ // Check for unreleased tabs which are resizing and reset them.
+ if !tab.release && tab.resizing != nil {
+ tab.resizing = nil
+ }
+
tab.release... | internal/action/tab.go | 26 | Go | 0.429 | suggestion | 158 | 51 | 51 | false | Fix lost mouse release events in case the pane becomes inactive | 3,271 | zyedidia/micro | 13,805 | Go | dmaluka | JoeKar |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.