]> git.lizzy.rs Git - micro.git/blobdiff - cmd/micro/loc.go
Add cd and pwd commands to change the working dir
[micro.git] / cmd / micro / loc.go
index d0bee09fd368bc1c4be5ec971f1b828591235999..263e0fb36ad5df3a3f0d56457d162a2463a976f2 100644 (file)
@@ -28,6 +28,27 @@ func ToCharPos(start Loc, buf *Buffer) int {
        return loc
 }
 
+// InBounds returns whether the given location is a valid character position in the given buffer
+func InBounds(pos Loc, buf *Buffer) bool {
+       if pos.Y < 0 || pos.Y >= buf.NumLines || pos.X < 0 || pos.X > Count(buf.Line(pos.Y)) {
+               return false
+       }
+
+       return true
+}
+
+// ByteOffset is just like ToCharPos except it counts bytes instead of runes
+func ByteOffset(pos Loc, buf *Buffer) int {
+       x, y := pos.X, pos.Y
+       loc := 0
+       for i := 0; i < y; i++ {
+               // + 1 for the newline
+               loc += len(buf.Line(i)) + 1
+       }
+       loc += len(buf.Line(y)[:x])
+       return loc
+}
+
 // Loc stores a location
 type Loc struct {
        X, Y int
@@ -83,6 +104,7 @@ func (l Loc) LessEqual(b Loc) bool {
        return false
 }
 
+// This moves the location one character to the right
 func (l Loc) right(buf *Buffer) Loc {
        if l == buf.End() {
                return Loc{l.X + 1, l.Y}
@@ -95,6 +117,8 @@ func (l Loc) right(buf *Buffer) Loc {
        }
        return res
 }
+
+// This moves the given location one character to the left
 func (l Loc) left(buf *Buffer) Loc {
        if l == buf.Start() {
                return Loc{l.X - 1, l.Y}
@@ -108,6 +132,8 @@ func (l Loc) left(buf *Buffer) Loc {
        return res
 }
 
+// Move moves the cursor n characters to the left or right
+// It moves the cursor left if n is negative
 func (l Loc) Move(n int, buf *Buffer) Loc {
        if n > 0 {
                for i := 0; i < n; i++ {
@@ -116,11 +142,7 @@ func (l Loc) Move(n int, buf *Buffer) Loc {
                return l
        }
        for i := 0; i < Abs(n); i++ {
-               return l.left(buf)
+               l = l.left(buf)
        }
        return l
 }
-
-// func (l Loc) DistanceTo(b Loc, buf *Buffer) int {
-//
-// }