feat: 更新插入命令以支持尾部偏移标记和相关文档

This commit is contained in:
2025-10-31 15:29:12 +08:00
parent f0414ec32b
commit 843c51e347
9 changed files with 178 additions and 16 deletions

View File

@@ -3,6 +3,7 @@ package insert
import (
"errors"
"fmt"
"strings"
"unicode/utf8"
)
@@ -11,8 +12,12 @@ type Position struct {
Index int // zero-based index where insertion should occur
}
// ResolvePosition interprets a position token (`^`, `$`, positive, negative) against the stem length.
// ResolvePosition interprets a position token (`^`, `$`, forward indexes, suffix offsets like `N$`, or legacy negative values) against the stem length.
func ResolvePosition(token string, stemLength int) (Position, error) {
if token == "" {
return Position{}, errors.New("position token cannot be empty")
}
switch token {
case "^":
return Position{Index: 0}, nil
@@ -20,8 +25,40 @@ func ResolvePosition(token string, stemLength int) (Position, error) {
return Position{Index: stemLength}, nil
}
if token == "" {
return Position{}, errors.New("position token cannot be empty")
if strings.HasPrefix(token, "^") {
trimmed := token[1:]
if trimmed == "" {
return Position{Index: 0}, nil
}
value, err := parseInt(trimmed)
if err != nil {
return Position{}, fmt.Errorf("invalid position token %q: %w", token, err)
}
if value < 0 {
return Position{}, fmt.Errorf("invalid position token %q: cannot be negative", token)
}
if value > stemLength {
return Position{}, fmt.Errorf("position %d out of range for %d-character stem", value, stemLength)
}
return Position{Index: value}, nil
}
if strings.HasSuffix(token, "$") {
trimmed := token[:len(token)-1]
if trimmed == "" {
return Position{Index: stemLength}, nil
}
value, err := parseInt(trimmed)
if err != nil {
return Position{}, fmt.Errorf("invalid position token %q: %w", token, err)
}
if value < 0 {
return Position{}, fmt.Errorf("invalid position token %q: cannot be negative", token)
}
if value > stemLength {
return Position{}, fmt.Errorf("position %d out of range for %d-character stem", value, stemLength)
}
return Position{Index: stemLength - value}, nil
}
// Try parsing as integer (positive or negative).