chore: import official kitty sources from upstream
Bring the kovidgoyal/kitty codebase in as the base of FWS-Kitty, vendored at upstream commit 91fb38a without its git history.
This commit is contained in:
commit
7e7d249099
1134 files changed
+433629
No files matched your search
Whitespace-only changes.
@@ -0,0 +1,90 @@
|
||||
// License: GPLv3 Copyright: 2026, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package hints
|
||||
|
||||
// hints_to_skip calculates how many hints to skip based on the given n and
|
||||
// alphabet size so that the next n hints generated by expanding the prefix tree
|
||||
// of an alphabet of size alphabetSize will be prefix-free.
|
||||
//
|
||||
// The result is 1-based, meaning that the first hint to be skipped is the first
|
||||
// non-empty hint.
|
||||
//
|
||||
// For example, if alphabet was "abc" and n was 5, the first non-empty hints
|
||||
// from that alphabet would be: "a", "b", "c", "aa", "ab", "ac", ...
|
||||
// the result of hints_to_skip would be 1, and this would mean that if you skip
|
||||
// "a" from the list above, the next 5 hints are prefix-free:
|
||||
// "b", "c", "aa", "ab", "ac".
|
||||
//
|
||||
// See issue #10195 for an informal proof on why this function works.
|
||||
func hints_to_skip(n int, alphabetSize int) int {
|
||||
if n < 2 {
|
||||
n = 2
|
||||
}
|
||||
return (n - 2) / (alphabetSize - 1)
|
||||
}
|
||||
|
||||
// encode_hint generates the hint corresponding to the given index in the
|
||||
// breadth-first traversal of the prefix tree generated by the given alphabet.
|
||||
//
|
||||
// For example, given the alphabet "abc", the hints would be generated in
|
||||
// the following order:
|
||||
// 0. "a"
|
||||
// 1. "b"
|
||||
// 2. "c"
|
||||
// 3. "aa"
|
||||
// 4. "ab"
|
||||
// 5. "ac"
|
||||
// 6. "ba"
|
||||
// 7. "bb"
|
||||
// 8. "bc"
|
||||
// 9. "ca"
|
||||
// 10. "cb"
|
||||
// 11. "cc"
|
||||
// 12. "aaa"
|
||||
// ...
|
||||
//
|
||||
// Indices are 0-based on non-empty hints; index=0 the hint of length 1 with
|
||||
// the first character of the alphabet.
|
||||
func encode_hint(num int, alphabet string) (res string) {
|
||||
l := len(alphabet)
|
||||
|
||||
for num >= 0 {
|
||||
mod := num % l
|
||||
res = string(alphabet[mod]) + res
|
||||
num /= l
|
||||
num -= 1
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func rune_to_index_map(alphabet string) *map[rune]int {
|
||||
runeToIndexMap := make(map[rune]int)
|
||||
for index, char := range alphabet {
|
||||
runeToIndexMap[char] = index
|
||||
}
|
||||
return &runeToIndexMap
|
||||
}
|
||||
|
||||
// decode_hint converts a hint to its corresponding index as it would appear in
|
||||
// the breadth-first traversal of the prefix tree generated by the given
|
||||
// alphabet.
|
||||
//
|
||||
// For example, given the alphabet "abc", the hints would be generated in
|
||||
// the following order:
|
||||
// 0. "a"
|
||||
// 1. "b"
|
||||
// 2. "c"
|
||||
// 3. "aa"
|
||||
// 4. "ab"
|
||||
// ...
|
||||
//
|
||||
// hint is expected to be non-empty.
|
||||
func decode_hint(hint string, char_to_index *map[rune]int) (res int) {
|
||||
base := len(*char_to_index)
|
||||
|
||||
for _, c := range hint {
|
||||
res = res*base + ((*char_to_index)[c] + 1)
|
||||
}
|
||||
return res - 1
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
// License: GPLv3 Copyright: 2026, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package hints
|
||||
|
||||
import (
|
||||
"math"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/kovidgoyal/kitty"
|
||||
)
|
||||
|
||||
func TestPrefixFreeHints(t *testing.T) {
|
||||
// Test hints_to_skip
|
||||
testsToSkip := []struct {
|
||||
n, alphabetSize, expected int
|
||||
}{
|
||||
{5, 3, 1},
|
||||
{6, 3, 2},
|
||||
{4, 3, 1},
|
||||
{3, 3, 0},
|
||||
{2, 3, 0},
|
||||
{1, 3, 0},
|
||||
{0, 3, 0},
|
||||
}
|
||||
for _, tc := range testsToSkip {
|
||||
actual := hints_to_skip(tc.n, tc.alphabetSize)
|
||||
if actual != tc.expected {
|
||||
t.Errorf("hints_to_skip(%d, %d) = %d, expected %d", tc.n, tc.alphabetSize, actual, tc.expected)
|
||||
}
|
||||
}
|
||||
|
||||
// Test prefix-free property verification
|
||||
alphabets := []string{"abc", "0123456789"}
|
||||
for _, alph := range alphabets {
|
||||
l := len(alph)
|
||||
for n := 1; n <= 10; n++ {
|
||||
total_hints := int(math.Pow(float64(2), float64(n)))
|
||||
skip := hints_to_skip(total_hints, l)
|
||||
hints := make([]string, total_hints)
|
||||
for i := range total_hints {
|
||||
hints[i] = encode_hint(skip+1+i, alph)
|
||||
}
|
||||
// Verify that no hint is a prefix of another hint
|
||||
for i := range total_hints {
|
||||
for j := range total_hints {
|
||||
if i == j {
|
||||
continue
|
||||
}
|
||||
if strings.HasPrefix(hints[j], hints[i]) {
|
||||
t.Errorf("For alphabet %q and n=%d: %q is a prefix of %q (skip=%d)", alph, total_hints, hints[i], hints[j], skip)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// HintsOffset + PrefixFree Test case 1: HintsOffset is smaller than dynamic
|
||||
// offset (dynamic offset wins)
|
||||
//
|
||||
// With 4 matches, and alphabet size 3:
|
||||
// hints_to_skip(4, 3) = 1.
|
||||
// HintsOffset = 0.
|
||||
// Effective offset = max(0, 1) = 1.
|
||||
// Ascending = true.
|
||||
// Match 0: 0 + 1 + 1 = 2 -> "b"
|
||||
// Match 1: 1 + 1 + 1 = 3 -> "c"
|
||||
// Match 2: 2 + 1 + 1 = 4 -> "aa"
|
||||
// Match 3: 3 + 1 + 1 = 5 -> "ab"
|
||||
opts1 := &Options{
|
||||
Type: "url",
|
||||
UrlPrefixes: "default",
|
||||
Regex: kitty.HintsDefaultRegex,
|
||||
PrefixFree: true,
|
||||
Alphabet: "abc",
|
||||
HintsOffset: 0,
|
||||
Ascending: false, // default
|
||||
}
|
||||
_, marks1, _, err := find_marks("http://a.com http://b.com http://c.com http://d.com", opts1)
|
||||
if err != nil {
|
||||
t.Fatalf("find_marks failed: %v", err)
|
||||
}
|
||||
expectedCodes1 := []string{"ab", "aa", "c", "b"}
|
||||
for i, m := range marks1 {
|
||||
hint := encode_hint(m.Index, opts1.Alphabet)
|
||||
if hint != expectedCodes1[i] {
|
||||
t.Errorf("Case 1 - Match %d (Index %d): got hint %q, expected %q", i, m.Index, hint, expectedCodes1[i])
|
||||
}
|
||||
}
|
||||
|
||||
// HintsOffset + PrefixFree Test case 2: HintsOffset is larger than dynamic
|
||||
// offset (HintsOffset wins)
|
||||
//
|
||||
// With 4 matches, and alphabet size 3:
|
||||
// hints_to_skip(4, 3) = 1.
|
||||
// HintsOffset = 3.
|
||||
// Effective offset = max(3, 1) = 3.
|
||||
// Ascending = true.
|
||||
// Match 0: 0 + 3 + 1 = 4 -> "aa"
|
||||
// Match 1: 1 + 3 + 1 = 5 -> "ab"
|
||||
// Match 2: 2 + 3 + 1 = 6 -> "ac"
|
||||
// Match 3: 3 + 3 + 1 = 7 -> "ba"
|
||||
opts2 := &Options{
|
||||
Type: "url",
|
||||
UrlPrefixes: "default",
|
||||
Regex: kitty.HintsDefaultRegex,
|
||||
PrefixFree: true,
|
||||
Alphabet: "abc",
|
||||
HintsOffset: 3,
|
||||
Ascending: true,
|
||||
}
|
||||
_, marks2, _, err := find_marks("http://a.com http://b.com http://c.com http://d.com", opts2)
|
||||
if err != nil {
|
||||
t.Fatalf("find_marks failed: %v", err)
|
||||
}
|
||||
expectedCodes2 := []string{"aa", "ab", "ac", "ba"}
|
||||
for i, m := range marks2 {
|
||||
hint := encode_hint(m.Index, opts2.Alphabet)
|
||||
if hint != expectedCodes2[i] {
|
||||
t.Errorf("Case 2 - Match %d (Index %d): got hint %q, expected %q", i, m.Index, hint, expectedCodes2[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEncodeDecodeHint(t *testing.T) {
|
||||
// enchode_hint sample tests
|
||||
tests := []struct {
|
||||
num int
|
||||
alphabet string
|
||||
expected string
|
||||
}{
|
||||
{0, "abc", "a"},
|
||||
{1, "abc", "b"},
|
||||
{2, "abc", "c"},
|
||||
{3, "abc", "aa"},
|
||||
{11, "abc", "cc"},
|
||||
{12, "abc", "aaa"},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
actual := encode_hint(tc.num, tc.alphabet)
|
||||
if actual != tc.expected {
|
||||
t.Errorf("encode_hint(%d, %q) = %q, expected %q", tc.num, tc.alphabet, actual, tc.expected)
|
||||
}
|
||||
}
|
||||
|
||||
// decode_hint should reverse encode_hint (round-trip test)
|
||||
for _, alph := range []string{"abc", "0123456789", DEFAULT_HINT_ALPHABET} {
|
||||
char_to_index := rune_to_index_map(alph)
|
||||
for num := range 200 {
|
||||
hint := encode_hint(num, alph)
|
||||
decoded := decode_hint(hint, char_to_index)
|
||||
if decoded != num {
|
||||
t.Errorf("decode_hint(encode_hint(%d, %q)) = %d, expected %d", num, alph, decoded, num)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,377 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package hints
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/cli"
|
||||
"github.com/kovidgoyal/kitty/tools/tty"
|
||||
"github.com/kovidgoyal/kitty/tools/tui"
|
||||
"github.com/kovidgoyal/kitty/tools/tui/loop"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
"github.com/kovidgoyal/kitty/tools/utils/style"
|
||||
"github.com/kovidgoyal/kitty/tools/wcswidth"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func convert_text(text string, cols int) string {
|
||||
lines := make([]string, 0, 64)
|
||||
empty_line := strings.Repeat("\x00", cols) + "\n"
|
||||
s1 := utils.NewLineScanner(text)
|
||||
for s1.Scan() {
|
||||
full_line := s1.Text()
|
||||
if full_line == "" {
|
||||
lines = append(lines, empty_line)
|
||||
continue
|
||||
}
|
||||
if strings.TrimRight(full_line, "\r") == "" {
|
||||
for range len(full_line) {
|
||||
lines = append(lines, empty_line)
|
||||
}
|
||||
continue
|
||||
}
|
||||
appended := false
|
||||
s2 := utils.NewSeparatorScanner(full_line, "\r")
|
||||
for s2.Scan() {
|
||||
line := s2.Text()
|
||||
if line != "" {
|
||||
line_sz := wcswidth.Stringwidth(line)
|
||||
extra := cols - line_sz
|
||||
if extra > 0 {
|
||||
line += strings.Repeat("\x00", extra)
|
||||
}
|
||||
lines = append(lines, line)
|
||||
lines = append(lines, "\r")
|
||||
appended = true
|
||||
}
|
||||
}
|
||||
if appended {
|
||||
lines[len(lines)-1] = "\n"
|
||||
}
|
||||
}
|
||||
ans := strings.Join(lines, "")
|
||||
return strings.TrimRight(ans, "\r\n")
|
||||
}
|
||||
|
||||
func parse_input(text string) string {
|
||||
cols, err := strconv.Atoi(os.Getenv("OVERLAID_WINDOW_COLS"))
|
||||
if err == nil {
|
||||
return convert_text(text, cols)
|
||||
}
|
||||
term, err := tty.OpenControllingTerm()
|
||||
if err == nil {
|
||||
sz, err := term.GetSize()
|
||||
term.Close()
|
||||
if err == nil {
|
||||
return convert_text(text, int(sz.Col))
|
||||
}
|
||||
}
|
||||
return convert_text(text, 80)
|
||||
}
|
||||
|
||||
type Result struct {
|
||||
Match []string `json:"match"`
|
||||
Programs []string `json:"programs"`
|
||||
Multiple_joiner string `json:"multiple_joiner"`
|
||||
Customize_processing string `json:"customize_processing"`
|
||||
Type string `json:"type"`
|
||||
Groupdicts []map[string]any `json:"groupdicts"`
|
||||
Extra_cli_args []string `json:"extra_cli_args"`
|
||||
Linenum_action string `json:"linenum_action"`
|
||||
Cwd string `json:"cwd"`
|
||||
}
|
||||
|
||||
func as_rgb(c uint32) [3]float32 {
|
||||
return [3]float32{float32((c>>16)&255) / 255.0, float32((c>>8)&255) / 255.0, float32(c&255) / 255.0}
|
||||
}
|
||||
|
||||
func hints_text_color(confval string) (ans string) {
|
||||
ans = confval
|
||||
if ans == "auto" {
|
||||
ans = "bright-gray"
|
||||
if bc, err := tui.ReadBasicColors(); err == nil {
|
||||
bg := as_rgb(bc.Background)
|
||||
c15 := as_rgb(bc.Color15)
|
||||
c8 := as_rgb(bc.Color8)
|
||||
if utils.RGBContrast(bg[0], bg[1], bg[2], c8[0], c8[1], c8[2]) > utils.RGBContrast(bg[0], bg[1], bg[2], c15[0], c15[1], c15[2]) {
|
||||
ans = "bright-black"
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func main(_ *cli.Command, o *Options, args []string) (rc int, err error) {
|
||||
o.HintsTextColor = hints_text_color(o.HintsTextColor)
|
||||
output := tui.KittenOutputSerializer()
|
||||
if tty.IsTerminal(os.Stdin.Fd()) {
|
||||
return 1, fmt.Errorf("You must pass the text to be hinted on STDIN")
|
||||
}
|
||||
stdin, err := io.ReadAll(os.Stdin)
|
||||
if err != nil {
|
||||
return 1, fmt.Errorf("Failed to read from STDIN with error: %w", err)
|
||||
}
|
||||
if len(args) > 0 && o.CustomizeProcessing == "" && o.Type != "linenum" {
|
||||
return 1, fmt.Errorf("Extra command line arguments present: %s", strings.Join(args, " "))
|
||||
}
|
||||
input_text := parse_input(utils.UnsafeBytesToString(stdin))
|
||||
text, all_marks, index_map, err := find_marks(input_text, o, os.Args[2:]...)
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
|
||||
result := Result{
|
||||
Programs: o.Program, Multiple_joiner: o.MultipleJoiner, Customize_processing: o.CustomizeProcessing, Type: o.Type,
|
||||
Extra_cli_args: args, Linenum_action: o.LinenumAction,
|
||||
}
|
||||
result.Cwd, _ = os.Getwd()
|
||||
alphabet := o.Alphabet
|
||||
if alphabet == "" {
|
||||
alphabet = DEFAULT_HINT_ALPHABET
|
||||
}
|
||||
ignore_mark_indices := utils.NewSet[int](8)
|
||||
window_title := o.WindowTitle
|
||||
if window_title == "" {
|
||||
switch o.Type {
|
||||
case "url":
|
||||
window_title = "Choose URL"
|
||||
default:
|
||||
window_title = "Choose text"
|
||||
}
|
||||
}
|
||||
current_text := ""
|
||||
current_input := ""
|
||||
match_suffix := ""
|
||||
switch o.AddTrailingSpace {
|
||||
case "always":
|
||||
match_suffix = " "
|
||||
case "never":
|
||||
default:
|
||||
if o.Multiple {
|
||||
match_suffix = " "
|
||||
}
|
||||
}
|
||||
chosen := []*Mark{}
|
||||
lp, err := loop.New(loop.NoAlternateScreen) // no alternate screen reduces flicker on exit
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
fctx := style.Context{AllowEscapeCodes: true}
|
||||
faint := fctx.SprintFunc("dim")
|
||||
hint_style := fctx.SprintFunc(fmt.Sprintf("fg=%s bg=%s bold", o.HintsForegroundColor, o.HintsBackgroundColor))
|
||||
text_style := fctx.SprintFunc(fmt.Sprintf("fg=%s bg=%s bold", o.HintsTextColor, o.HintsTextBackgroundColor))
|
||||
|
||||
highlight_mark := func(m *Mark, mark_text string) string {
|
||||
hint := encode_hint(m.Index, alphabet)
|
||||
if current_input != "" && !strings.HasPrefix(hint, current_input) {
|
||||
return faint(mark_text)
|
||||
}
|
||||
hint = hint[len(current_input):]
|
||||
if hint == "" {
|
||||
hint = " "
|
||||
}
|
||||
hint_runes := len(hint)
|
||||
runes := []rune(mark_text)
|
||||
if len(runes) <= hint_runes {
|
||||
mark_text = ""
|
||||
} else {
|
||||
replaced_text := string(runes[:hint_runes])
|
||||
replaced_text = strings.ReplaceAll(replaced_text, "\r", "\n")
|
||||
if strings.Contains(replaced_text, "\n") {
|
||||
buf := strings.Builder{}
|
||||
buf.Grow(2 * len(hint))
|
||||
h := hint
|
||||
parts := strings.Split(replaced_text, "\n")
|
||||
for i, x := range parts {
|
||||
if x != "" {
|
||||
buf.WriteString(h[:len(x)])
|
||||
h = h[len(x):]
|
||||
}
|
||||
if i != len(parts)-1 {
|
||||
buf.WriteString("\n")
|
||||
}
|
||||
}
|
||||
if h != "" {
|
||||
buf.WriteString(h)
|
||||
}
|
||||
hint = buf.String()
|
||||
}
|
||||
mark_text = string(runes[hint_runes:])
|
||||
}
|
||||
ans := hint_style(hint) + text_style(mark_text)
|
||||
return fmt.Sprintf("\x1b]8;;mark:%d\a%s\x1b]8;;\a", m.Index, ans)
|
||||
}
|
||||
|
||||
render := func() string {
|
||||
ans := text
|
||||
for i := len(all_marks) - 1; i >= 0; i-- {
|
||||
mark := &all_marks[i]
|
||||
if ignore_mark_indices.Has(mark.Index) {
|
||||
continue
|
||||
}
|
||||
mtext := highlight_mark(mark, ans[mark.Start:mark.End])
|
||||
ans = ans[:mark.Start] + mtext + ans[mark.End:]
|
||||
}
|
||||
ans = strings.ReplaceAll(ans, "\x00", "")
|
||||
return strings.TrimRightFunc(strings.NewReplacer("\r", "\r\n", "\n", "\r\n").Replace(ans), unicode.IsSpace)
|
||||
}
|
||||
|
||||
draw_screen := func() {
|
||||
lp.StartAtomicUpdate()
|
||||
defer lp.EndAtomicUpdate()
|
||||
if current_text == "" {
|
||||
current_text = render()
|
||||
}
|
||||
lp.ClearScreen()
|
||||
lp.QueueWriteString(current_text)
|
||||
}
|
||||
reset := func() {
|
||||
current_input = ""
|
||||
current_text = ""
|
||||
}
|
||||
|
||||
lp.OnInitialize = func() (string, error) {
|
||||
lp.SetCursorVisible(false)
|
||||
lp.SetWindowTitle(window_title)
|
||||
lp.AllowLineWrapping(false)
|
||||
draw_screen()
|
||||
lp.SendOverlayReady()
|
||||
return "", nil
|
||||
}
|
||||
lp.OnFinalize = func() string {
|
||||
lp.SetCursorVisible(true)
|
||||
return ""
|
||||
}
|
||||
lp.OnResize = func(old_size, new_size loop.ScreenSize) error {
|
||||
draw_screen()
|
||||
return nil
|
||||
}
|
||||
lp.OnRCResponse = func(data []byte) error {
|
||||
var r struct {
|
||||
Type string
|
||||
Mark int
|
||||
}
|
||||
if err := json.Unmarshal(data, &r); err != nil {
|
||||
return err
|
||||
}
|
||||
if r.Type == "mark_activated" {
|
||||
if m, ok := index_map[r.Mark]; ok {
|
||||
chosen = append(chosen, m)
|
||||
if o.Multiple {
|
||||
ignore_mark_indices.Add(m.Index)
|
||||
reset()
|
||||
} else {
|
||||
lp.Quit(0)
|
||||
return nil
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
lp.OnText = func(text string, _, _ bool) error {
|
||||
changed := false
|
||||
for _, ch := range text {
|
||||
if strings.ContainsRune(alphabet, ch) {
|
||||
current_input += string(ch)
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
if changed {
|
||||
matches := []*Mark{}
|
||||
for idx, m := range index_map {
|
||||
if eh := encode_hint(idx, alphabet); strings.HasPrefix(eh, current_input) {
|
||||
matches = append(matches, m)
|
||||
}
|
||||
}
|
||||
if len(matches) == 1 {
|
||||
chosen = append(chosen, matches[0])
|
||||
if o.Multiple {
|
||||
ignore_mark_indices.Add(matches[0].Index)
|
||||
reset()
|
||||
} else {
|
||||
lp.Quit(0)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
current_text = ""
|
||||
draw_screen()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
lp.OnKeyEvent = func(ev *loop.KeyEvent) error {
|
||||
if ev.MatchesPressOrRepeat("backspace") {
|
||||
ev.Handled = true
|
||||
r := []rune(current_input)
|
||||
if len(r) > 0 {
|
||||
r = r[:len(r)-1]
|
||||
current_input = string(r)
|
||||
current_text = ""
|
||||
}
|
||||
draw_screen()
|
||||
} else if ev.MatchesPressOrRepeat("enter") || ev.MatchesPressOrRepeat("space") {
|
||||
ev.Handled = true
|
||||
if current_input != "" {
|
||||
char_to_index := rune_to_index_map(alphabet)
|
||||
idx := decode_hint(current_input, char_to_index)
|
||||
if m := index_map[idx]; m != nil {
|
||||
chosen = append(chosen, m)
|
||||
ignore_mark_indices.Add(idx)
|
||||
if o.Multiple {
|
||||
reset()
|
||||
draw_screen()
|
||||
} else {
|
||||
lp.Quit(0)
|
||||
}
|
||||
} else {
|
||||
current_input = ""
|
||||
current_text = ""
|
||||
draw_screen()
|
||||
}
|
||||
}
|
||||
} else if ev.MatchesPressOrRepeat("esc") {
|
||||
if o.Multiple {
|
||||
lp.Quit(0)
|
||||
} else {
|
||||
lp.Quit(1)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
err = lp.Run()
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
ds := lp.DeathSignalName()
|
||||
if ds != "" {
|
||||
fmt.Println("Killed by signal: ", ds)
|
||||
lp.KillIfSignalled()
|
||||
return 1, nil
|
||||
}
|
||||
if lp.ExitCode() != 0 {
|
||||
return lp.ExitCode(), nil
|
||||
}
|
||||
result.Match = make([]string, len(chosen))
|
||||
result.Groupdicts = make([]map[string]any, len(chosen))
|
||||
for i, m := range chosen {
|
||||
result.Match[i] = m.Text + match_suffix
|
||||
result.Groupdicts[i] = m.Groupdict
|
||||
}
|
||||
fmt.Println(output(result))
|
||||
return
|
||||
}
|
||||
|
||||
func EntryPoint(parent *cli.Command) {
|
||||
create_cmd(parent, main)
|
||||
}
|
||||
@@ -0,0 +1,444 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
import sys
|
||||
from collections.abc import Sequence
|
||||
from functools import lru_cache
|
||||
from typing import Any
|
||||
|
||||
from kitty.cli_stub import HintsCLIOptions
|
||||
from kitty.clipboard import set_clipboard_string, set_primary_selection
|
||||
from kitty.constants import website_url
|
||||
from kitty.fast_data_types import get_options
|
||||
from kitty.typing_compat import BossType, WindowType
|
||||
from kitty.utils import get_editor, resolve_custom_file
|
||||
|
||||
from ..tui.handler import result_handler
|
||||
|
||||
DEFAULT_REGEX = r'(?m)^\s*(.+?)\s*$'
|
||||
|
||||
|
||||
def load_custom_processor(customize_processing: str) -> Any:
|
||||
if customize_processing.startswith('::import::'):
|
||||
import importlib
|
||||
|
||||
m = importlib.import_module(customize_processing[len('::import::') :])
|
||||
return {k: getattr(m, k) for k in dir(m)}
|
||||
if customize_processing == '::linenum::':
|
||||
return {'handle_result': linenum_handle_result}
|
||||
custom_path = resolve_custom_file(customize_processing)
|
||||
import runpy
|
||||
|
||||
return runpy.run_path(custom_path, run_name='__main__')
|
||||
|
||||
|
||||
class Mark:
|
||||
__slots__ = ('index', 'start', 'end', 'text', 'is_hyperlink', 'group_id', 'groupdict')
|
||||
|
||||
def __init__(self, index: int, start: int, end: int, text: str, groupdict: Any, is_hyperlink: bool = False, group_id: str | None = None):
|
||||
self.index, self.start, self.end = index, start, end
|
||||
self.text = text
|
||||
self.groupdict = groupdict
|
||||
self.is_hyperlink = is_hyperlink
|
||||
self.group_id = group_id
|
||||
|
||||
def as_dict(self) -> dict[str, Any]:
|
||||
return {
|
||||
'index': self.index,
|
||||
'start': self.start,
|
||||
'end': self.end,
|
||||
'text': self.text,
|
||||
'groupdict': {str(k): v for k, v in (self.groupdict or {}).items()},
|
||||
'group_id': self.group_id or '',
|
||||
'is_hyperlink': self.is_hyperlink,
|
||||
}
|
||||
|
||||
|
||||
def parse_hints_args(args: list[str]) -> tuple[HintsCLIOptions, list[str]]:
|
||||
from kitty.cli import parse_args
|
||||
|
||||
return parse_args(args, OPTIONS, usage, help_text, 'kitty +kitten hints', result_class=HintsCLIOptions)
|
||||
|
||||
|
||||
def custom_marking() -> None:
|
||||
import json
|
||||
|
||||
text = sys.stdin.read()
|
||||
sys.stdin.close()
|
||||
opts, extra_cli_args = parse_hints_args(sys.argv[1:])
|
||||
m = load_custom_processor(opts.customize_processing or '::impossible::')
|
||||
if 'mark' not in m:
|
||||
raise SystemExit(2)
|
||||
all_marks = tuple(x.as_dict() for x in m['mark'](text, opts, Mark, extra_cli_args))
|
||||
sys.stdout.write(json.dumps(all_marks))
|
||||
raise SystemExit(0)
|
||||
|
||||
|
||||
OPTIONS = r"""
|
||||
--program
|
||||
type=list
|
||||
What program to use to open matched text. Defaults to the default open program
|
||||
for the operating system. Various special values are supported:
|
||||
|
||||
:code:`-`
|
||||
paste the match into the terminal window.
|
||||
|
||||
:code:`@`
|
||||
copy the match to the clipboard
|
||||
|
||||
:code:`*`
|
||||
copy the match to the primary selection (on systems that support primary selections)
|
||||
|
||||
:code:`@NAME`
|
||||
copy the match to the specified buffer, e.g. :code:`@a`
|
||||
|
||||
:code:`default`
|
||||
run the default open program. Note that when using the hyperlink :code:`--type`
|
||||
the default is to use the kitty :doc:`hyperlink handling </open_actions>` facilities.
|
||||
|
||||
:code:`launch`
|
||||
run :doc:`/launch` to open the program in a new kitty tab, window, overlay, etc.
|
||||
For example::
|
||||
|
||||
--program "launch --type=tab vim"
|
||||
|
||||
Can be specified multiple times to run multiple programs.
|
||||
|
||||
|
||||
--type
|
||||
default=url
|
||||
choices=url,regex,path,line,hash,word,linenum,hyperlink,ip
|
||||
The type of text to search for. A value of :code:`linenum` is special, it looks
|
||||
for error messages using the pattern specified with :option:`--regex`, which
|
||||
must have the named groups: :code:`path` and :code:`line`. If not specified,
|
||||
will look for :code:`path:line`. The :option:`--linenum-action` option
|
||||
controls where to display the selected error message, other options are ignored.
|
||||
|
||||
|
||||
--regex
|
||||
default={default_regex}
|
||||
The regular expression to use when option :option:`--type` is set to
|
||||
:code:`regex`, in Perl 5 syntax. If you specify a numbered group in the regular
|
||||
expression, only the group will be matched. This allows you to match text
|
||||
ignoring a prefix/suffix, as needed. The default expression matches lines. To
|
||||
match text over multiple lines, things get a little tricky, as line endings
|
||||
are a sequence of zero or more null bytes followed by either a carriage return
|
||||
or a newline character. To have a pattern match over line endings you will need to
|
||||
match the character set ``[\0\r\n]``. The newlines and null bytes are automatically
|
||||
stripped from the returned text. If you specify named groups and a
|
||||
:option:`--program`, then the program will be passed arguments corresponding
|
||||
to each named group of the form :code:`key=value`.
|
||||
|
||||
|
||||
--linenum-action
|
||||
default=self
|
||||
type=choice
|
||||
choices=self,window,tab,os_window,background,remote-control
|
||||
Where to perform the action on matched errors. :code:`self` means the current
|
||||
window, :code:`window` a new kitty window, :code:`tab` a new tab,
|
||||
:code:`os_window` a new OS window and :code:`background` run in the background.
|
||||
:code:`remote-control` is like background but the program can use kitty remote control
|
||||
without needing to turn on remote control globally.
|
||||
The actual action is whatever arguments are provided to the kitten, for
|
||||
example:
|
||||
:code:`kitten hints --type=linenum --linenum-action=tab vim +{line} {path}`
|
||||
will open the matched path at the matched line number in vim in
|
||||
a new kitty tab. Note that in order to use :option:`--program` to copy or paste
|
||||
the provided arguments, you need to use the special value :code:`self`.
|
||||
|
||||
|
||||
--url-prefixes
|
||||
default=default
|
||||
Comma separated list of recognized URL prefixes. Defaults to the list of
|
||||
prefixes defined by the :opt:`url_prefixes` option in :file:`kitty.conf`.
|
||||
|
||||
|
||||
--url-excluded-characters
|
||||
default=default
|
||||
Characters to exclude when matching URLs. Defaults to the list of characters
|
||||
defined by the :opt:`url_excluded_characters` option in :file:`kitty.conf`.
|
||||
The syntax for this option is the same as for :opt:`url_excluded_characters`.
|
||||
|
||||
|
||||
--word-characters
|
||||
Characters to consider as part of a word. In addition, all characters marked as
|
||||
alphanumeric in the Unicode database will be considered as word characters.
|
||||
Defaults to the :opt:`select_by_word_characters` option from :file:`kitty.conf`.
|
||||
|
||||
|
||||
--minimum-match-length
|
||||
default=3
|
||||
type=int
|
||||
The minimum number of characters to consider a match.
|
||||
|
||||
|
||||
--multiple
|
||||
type=bool-set
|
||||
Select multiple matches and perform the action on all of them together at the
|
||||
end. In this mode, press :kbd:`Esc` to finish selecting.
|
||||
|
||||
|
||||
--multiple-joiner
|
||||
default=auto
|
||||
String for joining multiple selections when copying to the clipboard or
|
||||
inserting into the terminal. The special values are: :code:`space` - a space
|
||||
character, :code:`newline` - a newline, :code:`empty` - an empty joiner,
|
||||
:code:`json` - a JSON serialized list, :code:`auto` - an automatic choice, based
|
||||
on the type of text being selected. In addition, integers are interpreted as
|
||||
zero-based indices into the list of selections. You can use :code:`0` for the
|
||||
first selection and :code:`-1` for the last.
|
||||
|
||||
|
||||
--add-trailing-space
|
||||
default=auto
|
||||
choices=auto,always,never
|
||||
Add trailing space after matched text. Defaults to :code:`auto`, which adds the
|
||||
space when used together with :option:`--multiple`.
|
||||
|
||||
|
||||
--hints-offset
|
||||
default=1
|
||||
type=int
|
||||
The offset (from zero) at which to start hint numbering. Note that only numbers
|
||||
greater than or equal to zero are respected.
|
||||
|
||||
|
||||
--prefix-free
|
||||
type=bool-set
|
||||
Generate hints such that no hint is a prefix of another. For example, with
|
||||
alphabet "abc" and 4 matches, hints are "b", "c", "aa", "ab", instead of "a",
|
||||
"b", "c", "aa" (where "a" prefixes "aa"). This works by applying a dynamic
|
||||
offset large enough so that the hints are prefix-free. When combined with a
|
||||
:option:`--hints-offset` greater than 0, the effective offset is whichever is
|
||||
larger.
|
||||
|
||||
|
||||
--alphabet
|
||||
The list of characters to use for hints. The default is to use numbers and
|
||||
lowercase English alphabets. Specify your preference as a string of characters.
|
||||
Note that you need to specify the :option:`--hints-offset` as zero to use the
|
||||
first character to highlight the first match, otherwise it will start with the
|
||||
second character by default.
|
||||
|
||||
|
||||
--ascending
|
||||
type=bool-set
|
||||
Make the hints increase from top to bottom, instead of decreasing from top to
|
||||
bottom.
|
||||
|
||||
|
||||
--hints-foreground-color
|
||||
default=black
|
||||
type=str
|
||||
The foreground color for hints. You can use color names or hex values. For the eight basic
|
||||
named terminal colors you can also use the :code:`bright-` prefix to get the bright variant of the
|
||||
color.
|
||||
|
||||
|
||||
--hints-background-color
|
||||
default=green
|
||||
type=str
|
||||
The background color for hints. You can use color names or hex values. For the eight basic
|
||||
named terminal colors you can also use the :code:`bright-` prefix to get the bright variant of the
|
||||
color.
|
||||
|
||||
|
||||
--hints-text-color
|
||||
default=auto
|
||||
type=str
|
||||
The foreground color for text pointed to by the hints (excluding the hint label itself). You can use
|
||||
color names or hex values. For the eight basic named terminal colors you can also use the
|
||||
:code:`bright-` prefix to get the bright variant of the color. The default is to pick a suitable
|
||||
color automatically.
|
||||
|
||||
|
||||
--hints-text-background-color
|
||||
default=auto
|
||||
type=str
|
||||
The background color for text pointed to by the hints (excluding the hint label itself). You can use
|
||||
color names or hex values. For the eight basic named terminal colors you can also use the
|
||||
:code:`bright-` prefix to get the bright variant of the color. The default is to pick a suitable
|
||||
color automatically.
|
||||
|
||||
|
||||
--customize-processing
|
||||
Name of a python file in the kitty config directory which will be imported to
|
||||
provide custom implementations for pattern finding and performing actions
|
||||
on selected matches. You can also specify absolute paths to load the script from
|
||||
elsewhere. See {hints_url} for details.
|
||||
|
||||
|
||||
--window-title
|
||||
The title for the hints window, default title is based on the type of text being
|
||||
hinted.
|
||||
""".format(
|
||||
default_regex=DEFAULT_REGEX,
|
||||
line='{{line}}',
|
||||
path='{{path}}',
|
||||
hints_url=website_url('kittens/hints'),
|
||||
).format
|
||||
help_text = 'Select text from the screen using the keyboard. Defaults to searching for URLs.'
|
||||
usage = ''
|
||||
|
||||
|
||||
def main(args: list[str]) -> dict[str, Any] | None:
|
||||
raise SystemExit('Should be run as kitten hints')
|
||||
|
||||
|
||||
def linenum_process_result(data: dict[str, Any]) -> tuple[str, int]:
|
||||
for match, g in zip(data['match'], data['groupdicts']):
|
||||
path, line = g['path'], g['line']
|
||||
if path and line:
|
||||
return path, int(line)
|
||||
return '', -1
|
||||
|
||||
|
||||
def linenum_handle_result(args: list[str], data: dict[str, Any], target_window_id: int, boss: BossType, extra_cli_args: Sequence[str], *a: Any) -> None:
|
||||
path, line = linenum_process_result(data)
|
||||
if not path:
|
||||
return
|
||||
|
||||
if extra_cli_args:
|
||||
cmd = [x.format(path=path, line=line) for x in extra_cli_args]
|
||||
else:
|
||||
cmd = get_editor(path_to_edit=path, line_number=line)
|
||||
w = boss.window_id_map.get(target_window_id)
|
||||
action = data['linenum_action']
|
||||
|
||||
if action == 'self':
|
||||
if w is not None:
|
||||
|
||||
def is_copy_action(s: str) -> bool:
|
||||
return s in ('-', '@', '*') or s.startswith('@')
|
||||
|
||||
programs = list(filter(is_copy_action, data['programs'] or []))
|
||||
# keep for backward compatibility, previously option `--program` does not need to be specified to perform copy actions
|
||||
if is_copy_action(cmd[0]):
|
||||
programs.append(cmd.pop(0))
|
||||
if programs:
|
||||
text = ' '.join(cmd)
|
||||
for program in programs:
|
||||
if program == '-':
|
||||
w.paste_bytes(text)
|
||||
elif program == '@':
|
||||
set_clipboard_string(text)
|
||||
boss.handle_clipboard_loss('clipboard')
|
||||
elif program == '*':
|
||||
set_primary_selection(text)
|
||||
boss.handle_clipboard_loss('primary')
|
||||
elif program.startswith('@'):
|
||||
boss.set_clipboard_buffer(program[1:], text)
|
||||
else:
|
||||
import shlex
|
||||
|
||||
text = shlex.join(cmd)
|
||||
w.paste_bytes(f'{text}\r')
|
||||
elif action == 'background':
|
||||
boss.run_background_process(cmd, cwd=data['cwd'], allow_remote_control=False)
|
||||
elif action == 'remote-control':
|
||||
boss.run_background_process(cmd, cwd=data['cwd'], allow_remote_control=True)
|
||||
else:
|
||||
getattr(boss, {'window': 'new_window_with_cwd', 'tab': 'new_tab_with_cwd', 'os_window': 'new_os_window_with_cwd'}[action])(*cmd)
|
||||
|
||||
|
||||
def on_mark_clicked(boss: BossType, window: WindowType, url: str, hyperlink_id: int, cwd: str) -> bool:
|
||||
if url.startswith('mark:'):
|
||||
window.send_cmd_response({'Type': 'mark_activated', 'Mark': int(url[5:])})
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
@result_handler(type_of_input='screen-ansi', has_ready_notification=True, open_url_handler=on_mark_clicked)
|
||||
def handle_result(args: list[str], data: dict[str, Any], target_window_id: int, boss: BossType) -> None:
|
||||
cp = data['customize_processing']
|
||||
if data['type'] == 'linenum':
|
||||
cp = '::linenum::'
|
||||
if cp:
|
||||
m = load_custom_processor(cp)
|
||||
if 'handle_result' in m:
|
||||
m['handle_result'](args, data, target_window_id, boss, data['extra_cli_args'])
|
||||
return None
|
||||
|
||||
programs = data['programs'] or ('default',)
|
||||
matches: list[str] = []
|
||||
groupdicts = []
|
||||
for m, g in zip(data['match'], data['groupdicts']):
|
||||
if m:
|
||||
matches.append(m)
|
||||
groupdicts.append(g)
|
||||
if not matches:
|
||||
return
|
||||
joiner = data['multiple_joiner']
|
||||
try:
|
||||
is_int: int | None = int(joiner)
|
||||
except Exception:
|
||||
is_int = None
|
||||
text_type = data['type']
|
||||
|
||||
@lru_cache
|
||||
def joined_text() -> str:
|
||||
if is_int is not None:
|
||||
try:
|
||||
return matches[is_int]
|
||||
except IndexError:
|
||||
return matches[-1]
|
||||
if joiner == 'json':
|
||||
import json
|
||||
|
||||
return json.dumps(matches, ensure_ascii=False, indent='\t')
|
||||
if joiner == 'auto':
|
||||
q = '\n\r' if text_type in ('line', 'url') else ' '
|
||||
else:
|
||||
q = {'newline': '\n\r', 'space': ' '}.get(joiner, '')
|
||||
return q.join(matches)
|
||||
|
||||
for program in programs:
|
||||
if program == '-':
|
||||
w = boss.window_id_map.get(target_window_id)
|
||||
if w is not None:
|
||||
w.paste_text(joined_text())
|
||||
elif program == '*':
|
||||
set_primary_selection(joined_text())
|
||||
elif program.startswith('@'):
|
||||
if program == '@':
|
||||
set_clipboard_string(joined_text())
|
||||
else:
|
||||
boss.set_clipboard_buffer(program[1:], joined_text())
|
||||
else:
|
||||
from kitty.conf.utils import to_cmdline
|
||||
|
||||
cwd = data['cwd']
|
||||
is_default_program = program == 'default'
|
||||
program = get_options().open_url_with if is_default_program else program
|
||||
if text_type == 'hyperlink' and is_default_program:
|
||||
w = boss.window_id_map.get(target_window_id)
|
||||
for m in matches:
|
||||
if w is not None:
|
||||
w.open_url(m, hyperlink_id=1, cwd=cwd)
|
||||
else:
|
||||
launch_args = []
|
||||
if isinstance(program, str) and program.startswith('launch '):
|
||||
launch_args = to_cmdline(program)
|
||||
launch_args.insert(1, '--cwd=' + cwd)
|
||||
for m, groupdict in zip(matches, groupdicts):
|
||||
if groupdict:
|
||||
m = []
|
||||
for k, v in groupdict.items():
|
||||
m.append('{}={}'.format(k, v or ''))
|
||||
if launch_args:
|
||||
w = boss.window_id_map.get(target_window_id)
|
||||
boss.call_remote_control(self_window=w, args=tuple(launch_args + ([m] if isinstance(m, str) else m)))
|
||||
else:
|
||||
boss.open_url(m, program, cwd=cwd)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
# Run with kitty +kitten hints
|
||||
main(sys.argv)
|
||||
elif __name__ == '__doc__':
|
||||
cd = sys.cli_docs # type: ignore
|
||||
cd['usage'] = usage
|
||||
cd['short_desc'] = 'Select text from screen with keyboard'
|
||||
cd['options'] = OPTIONS
|
||||
cd['help_text'] = help_text
|
||||
# }}}
|
||||
@@ -0,0 +1,796 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package hints
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os/exec"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/dlclark/regexp2"
|
||||
"github.com/dlclark/regexp2/syntax"
|
||||
"github.com/seancfoley/ipaddress-go/ipaddr"
|
||||
|
||||
"github.com/kovidgoyal/kitty"
|
||||
"github.com/kovidgoyal/kitty/tools/config"
|
||||
"github.com/kovidgoyal/kitty/tools/tty"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
const (
|
||||
DEFAULT_HINT_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz"
|
||||
FILE_EXTENSION = `\.(?:[a-zA-Z0-9]{2,7}|[ahcmo])(?:\b|[^.])`
|
||||
)
|
||||
|
||||
func path_regex() string {
|
||||
return fmt.Sprintf(`(?:\S*?/[\r\S]+)|(?:\S[\r\S]*%s)\b`, FILE_EXTENSION)
|
||||
}
|
||||
|
||||
func default_linenum_regex() string {
|
||||
return fmt.Sprintf(`(?P<path>%s):(?P<line>\d+)`, path_regex())
|
||||
}
|
||||
|
||||
type Mark struct {
|
||||
Index int `json:"index"`
|
||||
Start int `json:"start"`
|
||||
End int `json:"end"`
|
||||
Text string `json:"text"`
|
||||
Group_id string `json:"group_id"`
|
||||
Is_hyperlink bool `json:"is_hyperlink"`
|
||||
Groupdict map[string]any `json:"groupdict"`
|
||||
}
|
||||
|
||||
func process_escape_codes(text string) (ans string, hyperlinks []Mark) {
|
||||
removed_size, idx := 0, 0
|
||||
active_hyperlink_url := ""
|
||||
active_hyperlink_id := ""
|
||||
active_hyperlink_start_offset := 0
|
||||
|
||||
add_hyperlink := func(end int) {
|
||||
hyperlinks = append(hyperlinks, Mark{
|
||||
Index: idx, Start: active_hyperlink_start_offset, End: end, Text: active_hyperlink_url, Is_hyperlink: true, Group_id: active_hyperlink_id})
|
||||
active_hyperlink_url, active_hyperlink_id = "", ""
|
||||
active_hyperlink_start_offset = 0
|
||||
idx++
|
||||
}
|
||||
|
||||
ans = utils.ReplaceAll(utils.MustCompile("\x1b(?:\\[[0-9;:]*?m|\\].*?\x1b\\\\)"), text, func(raw string, groupdict map[string]utils.SubMatch) string {
|
||||
if !strings.HasPrefix(raw, "\x1b]8") {
|
||||
removed_size += len(raw)
|
||||
return ""
|
||||
}
|
||||
start := groupdict[""].Start - removed_size
|
||||
removed_size += len(raw)
|
||||
if active_hyperlink_url != "" {
|
||||
add_hyperlink(start)
|
||||
}
|
||||
raw = raw[4 : len(raw)-2]
|
||||
if metadata, url, found := strings.Cut(raw, ";"); found && url != "" {
|
||||
active_hyperlink_url = url
|
||||
active_hyperlink_start_offset = start
|
||||
if metadata != "" {
|
||||
for entry := range strings.SplitSeq(metadata, ":") {
|
||||
if strings.HasPrefix(entry, "id=") && len(entry) > 3 {
|
||||
active_hyperlink_id = entry[3:]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
})
|
||||
if active_hyperlink_url != "" {
|
||||
add_hyperlink(len(ans))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
type PostProcessorFunc = func(string, int, int) (int, int)
|
||||
type GroupProcessorFunc = func(map[string]string)
|
||||
|
||||
func is_punctuation(b string) bool {
|
||||
switch b {
|
||||
case ",", ".", "?", "!":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func closing_bracket_for(ch string) string {
|
||||
switch ch {
|
||||
case "(":
|
||||
return ")"
|
||||
case "[":
|
||||
return "]"
|
||||
case "{":
|
||||
return "}"
|
||||
case "<":
|
||||
return ">"
|
||||
case "*":
|
||||
return "*"
|
||||
case `"`:
|
||||
return `"`
|
||||
case "'":
|
||||
return "'"
|
||||
case "“":
|
||||
return "”"
|
||||
case "‘":
|
||||
return "’"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func char_at(s string, i int) string {
|
||||
ans, _ := utf8.DecodeRuneInString(s[i:])
|
||||
if ans == utf8.RuneError {
|
||||
return ""
|
||||
}
|
||||
return string(ans)
|
||||
}
|
||||
|
||||
func char_before(s string, i int) string {
|
||||
ans, _ := utf8.DecodeLastRuneInString(s[:i])
|
||||
if ans == utf8.RuneError {
|
||||
return ""
|
||||
}
|
||||
return string(ans)
|
||||
}
|
||||
|
||||
func matching_remover(openers ...string) PostProcessorFunc {
|
||||
return func(text string, s, e int) (int, int) {
|
||||
if s < e && e <= len(text) {
|
||||
before := char_at(text, s)
|
||||
if slices.Index(openers, before) > -1 {
|
||||
q := closing_bracket_for(before)
|
||||
if s+len(before) <= e-len(q) && char_before(text, e) == q {
|
||||
s += len(before)
|
||||
e -= len(q)
|
||||
} else if char_at(text, e) == q {
|
||||
s += len(before)
|
||||
}
|
||||
}
|
||||
}
|
||||
return s, e
|
||||
}
|
||||
}
|
||||
|
||||
func linenum_group_processor(gd map[string]string) {
|
||||
pat := utils.MustCompile(`:\d+$`)
|
||||
gd[`path`] = pat.ReplaceAllStringFunc(gd["path"], func(m string) string {
|
||||
gd["line"] = m[1:]
|
||||
return ``
|
||||
})
|
||||
gd[`path`] = utils.Expanduser(gd[`path`])
|
||||
}
|
||||
|
||||
var PostProcessorMap = sync.OnceValue(func() map[string]PostProcessorFunc {
|
||||
return map[string]PostProcessorFunc{
|
||||
"url": func(text string, s, e int) (int, int) {
|
||||
if s > 4 && text[s-5:s] == "link:" { // asciidoc URLs
|
||||
url := text[s:e]
|
||||
idx := strings.LastIndex(url, "[")
|
||||
if idx > -1 {
|
||||
e -= len(url) - idx
|
||||
}
|
||||
}
|
||||
for e > 1 && is_punctuation(char_before(text, e)) { // remove trailing punctuation
|
||||
e--
|
||||
}
|
||||
// truncate url at closing bracket/quote
|
||||
if s > 0 && e <= len(text) {
|
||||
if q := closing_bracket_for(char_before(text, s)); q != "" {
|
||||
idx := strings.Index(text[s:], q)
|
||||
if idx > 0 {
|
||||
e = s + idx
|
||||
}
|
||||
}
|
||||
}
|
||||
// reStructuredText URLs
|
||||
if e > 3 && text[e-2:e] == "`_" {
|
||||
e -= 2
|
||||
}
|
||||
return s, e
|
||||
},
|
||||
|
||||
"brackets": matching_remover("(", "{", "[", "<"),
|
||||
"quotes": matching_remover("'", `"`, "“", "‘"),
|
||||
"ip": func(text string, s, e int) (int, int) {
|
||||
addr := ipaddr.NewHostName(text[s:e])
|
||||
if !addr.IsAddress() {
|
||||
return -1, -1
|
||||
}
|
||||
return s, e
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
type KittyOpts struct {
|
||||
Url_prefixes *utils.Set[string]
|
||||
Url_excluded_characters string
|
||||
Select_by_word_characters string
|
||||
}
|
||||
|
||||
func read_relevant_kitty_opts() KittyOpts {
|
||||
ans := KittyOpts{
|
||||
Select_by_word_characters: kitty.KittyConfigDefaults.Select_by_word_characters,
|
||||
Url_excluded_characters: kitty.KittyConfigDefaults.Url_excluded_characters}
|
||||
handle_line := func(key, val string) error {
|
||||
switch key {
|
||||
case "url_prefixes":
|
||||
ans.Url_prefixes = utils.NewSetWithItems(strings.Split(val, " ")...)
|
||||
case "select_by_word_characters":
|
||||
ans.Select_by_word_characters = strings.TrimSpace(val)
|
||||
case "url_excluded_characters":
|
||||
if s, err := config.StringLiteral(val); err == nil {
|
||||
ans.Url_excluded_characters = s
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
config.ReadKittyConfig(handle_line)
|
||||
if ans.Url_prefixes == nil {
|
||||
ans.Url_prefixes = utils.NewSetWithItems(kitty.KittyConfigDefaults.Url_prefixes...)
|
||||
}
|
||||
return ans
|
||||
}
|
||||
|
||||
var RelevantKittyOpts = sync.OnceValue(func() KittyOpts {
|
||||
return read_relevant_kitty_opts()
|
||||
})
|
||||
|
||||
var debugprintln = tty.DebugPrintln
|
||||
var _ = debugprintln
|
||||
|
||||
func url_excluded_characters_as_ranges_for_regex(extra_excluded string) string {
|
||||
// See https://url.spec.whatwg.org/#url-code-points
|
||||
ans := strings.Builder{}
|
||||
ans.Grow(4096)
|
||||
type cr struct{ start, end rune }
|
||||
ranges := []cr{}
|
||||
r := func(start rune, end ...rune) {
|
||||
if len(end) == 0 {
|
||||
ranges = append(ranges, cr{start, start})
|
||||
} else {
|
||||
ranges = append(ranges, cr{start, end[0]})
|
||||
}
|
||||
}
|
||||
if !strings.Contains(extra_excluded, "\n") {
|
||||
r('\n')
|
||||
}
|
||||
if !strings.Contains(extra_excluded, "\r") {
|
||||
r('\r')
|
||||
}
|
||||
r('!')
|
||||
r('$')
|
||||
r('&')
|
||||
r('#')
|
||||
r('\'')
|
||||
r('/')
|
||||
r(':')
|
||||
r(';')
|
||||
r('@')
|
||||
r('_')
|
||||
r('~')
|
||||
r('(')
|
||||
r(')')
|
||||
r('*')
|
||||
r('+')
|
||||
r(',')
|
||||
r('-')
|
||||
r('.')
|
||||
r('=')
|
||||
r('?')
|
||||
r('%')
|
||||
r('a', 'z')
|
||||
r('A', 'Z')
|
||||
r('0', '9')
|
||||
slices.SortFunc(ranges, func(a, b cr) int { return int(a.start - b.start) })
|
||||
var prev rune = -1
|
||||
for _, cr := range ranges {
|
||||
if cr.start-1 > prev+1 {
|
||||
ans.WriteString(regexp.QuoteMeta(string(prev + 1)))
|
||||
ans.WriteRune('-')
|
||||
ans.WriteString(regexp.QuoteMeta(string(cr.start - 1)))
|
||||
}
|
||||
prev = cr.end
|
||||
}
|
||||
ans.WriteString(regexp.QuoteMeta(string(ranges[len(ranges)-1].end + 1)))
|
||||
ans.WriteRune('-')
|
||||
ans.WriteRune(0x9f)
|
||||
ans.WriteString(`\x{d800}-\x{dfff}`)
|
||||
ans.WriteString(`\x{fdd0}-\x{fdef}`)
|
||||
w := func(x rune) { ans.WriteRune(x) }
|
||||
|
||||
w(0xFFFE)
|
||||
w(0xFFFF)
|
||||
w(0x1FFFE)
|
||||
w(0x1FFFF)
|
||||
w(0x2FFFE)
|
||||
w(0x2FFFF)
|
||||
w(0x3FFFE)
|
||||
w(0x3FFFF)
|
||||
w(0x4FFFE)
|
||||
w(0x4FFFF)
|
||||
w(0x5FFFE)
|
||||
w(0x5FFFF)
|
||||
w(0x6FFFE)
|
||||
w(0x6FFFF)
|
||||
w(0x7FFFE)
|
||||
w(0x7FFFF)
|
||||
w(0x8FFFE)
|
||||
w(0x8FFFF)
|
||||
w(0x9FFFE)
|
||||
w(0x9FFFF)
|
||||
w(0xAFFFE)
|
||||
w(0xAFFFF)
|
||||
w(0xBFFFE)
|
||||
w(0xBFFFF)
|
||||
w(0xCFFFE)
|
||||
w(0xCFFFF)
|
||||
w(0xDFFFE)
|
||||
w(0xDFFFF)
|
||||
w(0xEFFFE)
|
||||
w(0xEFFFF)
|
||||
w(0xFFFFE)
|
||||
w(0xFFFFF)
|
||||
|
||||
if strings.Contains(extra_excluded, "-") {
|
||||
extra_excluded = strings.ReplaceAll(extra_excluded, "-", "")
|
||||
extra_excluded = regexp.QuoteMeta(extra_excluded) + "-"
|
||||
} else {
|
||||
extra_excluded = regexp.QuoteMeta(extra_excluded)
|
||||
}
|
||||
ans.WriteString(extra_excluded)
|
||||
return ans.String()
|
||||
|
||||
}
|
||||
|
||||
func functions_for(opts *Options) (pattern string, post_processors []PostProcessorFunc, group_processors []GroupProcessorFunc, err error) {
|
||||
switch opts.Type {
|
||||
case "url":
|
||||
var url_prefixes *utils.Set[string]
|
||||
if opts.UrlPrefixes == "default" {
|
||||
url_prefixes = RelevantKittyOpts().Url_prefixes
|
||||
} else {
|
||||
url_prefixes = utils.NewSetWithItems(strings.Split(opts.UrlPrefixes, ",")...)
|
||||
}
|
||||
url_excluded_characters := RelevantKittyOpts().Url_excluded_characters
|
||||
if opts.UrlExcludedCharacters != "default" {
|
||||
if url_excluded_characters, err = config.StringLiteral(opts.UrlExcludedCharacters); err != nil {
|
||||
err = fmt.Errorf("Failed to parse --url-excluded-characters value: %#v with error: %w", opts.UrlExcludedCharacters, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
pattern = fmt.Sprintf(`(?:%s)://[^%s]{3,}`, strings.Join(url_prefixes.AsSlice(), "|"), url_excluded_characters_as_ranges_for_regex(url_excluded_characters))
|
||||
post_processors = append(post_processors, PostProcessorMap()["url"])
|
||||
case "path":
|
||||
pattern = path_regex()
|
||||
post_processors = append(post_processors, PostProcessorMap()["brackets"], PostProcessorMap()["quotes"])
|
||||
case "line":
|
||||
pattern = "(?m)^\\s*(.+)[\\s\x00]*$"
|
||||
case "hash":
|
||||
pattern = "[0-9a-f][0-9a-f\r]{6,127}"
|
||||
case "ip":
|
||||
pattern = (
|
||||
// IPv4 with no validation
|
||||
`((?:\d{1,3}\.){3}\d{1,3}` + "|" +
|
||||
// IPv6 with no validation
|
||||
`(?:[a-fA-F0-9]{0,4}:){2,7}[a-fA-F0-9]{0,4})`)
|
||||
post_processors = append(post_processors, PostProcessorMap()["ip"])
|
||||
default:
|
||||
pattern = opts.Regex
|
||||
if opts.Type == "linenum" {
|
||||
if pattern == kitty.HintsDefaultRegex {
|
||||
pattern = default_linenum_regex()
|
||||
}
|
||||
post_processors = append(post_processors, PostProcessorMap()["brackets"], PostProcessorMap()["quotes"])
|
||||
group_processors = append(group_processors, linenum_group_processor)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
type Capture struct {
|
||||
Text string
|
||||
Text_as_runes []rune
|
||||
Byte_Offsets struct {
|
||||
Start, End int
|
||||
}
|
||||
Rune_Offsets struct {
|
||||
Start, End int
|
||||
}
|
||||
}
|
||||
|
||||
func (self Capture) String() string {
|
||||
return fmt.Sprintf("Capture(start=%d, end=%d, %#v)", self.Byte_Offsets.Start, self.Byte_Offsets.End, self.Text)
|
||||
}
|
||||
|
||||
type Group struct {
|
||||
Name string
|
||||
IsNamed bool
|
||||
Captures []Capture
|
||||
}
|
||||
|
||||
func (self Group) LastCapture() Capture {
|
||||
if len(self.Captures) == 0 {
|
||||
return Capture{}
|
||||
}
|
||||
return self.Captures[len(self.Captures)-1]
|
||||
}
|
||||
|
||||
func (self Group) String() string {
|
||||
return fmt.Sprintf("Group(name=%#v, captures=%v)", self.Name, self.Captures)
|
||||
}
|
||||
|
||||
type Match struct {
|
||||
Groups []Group
|
||||
}
|
||||
|
||||
func (self Match) HasNamedGroups() bool {
|
||||
for _, g := range self.Groups {
|
||||
if g.IsNamed {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func find_all_matches(re *regexp2.Regexp, text string) (ans []Match, err error) {
|
||||
m, err := re.FindStringMatch(text)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
rune_to_bytes := utils.RuneOffsetsToByteOffsets(text)
|
||||
get_byte_offset_map := func(groups []regexp2.Group) (ans map[int]int, err error) {
|
||||
ans = make(map[int]int, len(groups)*2)
|
||||
rune_offsets := make([]int, 0, len(groups)*2)
|
||||
for _, g := range groups {
|
||||
for _, c := range g.Captures {
|
||||
if _, found := ans[c.Index]; !found {
|
||||
rune_offsets = append(rune_offsets, c.Index)
|
||||
ans[c.Index] = -1
|
||||
}
|
||||
end := c.Index + c.Length
|
||||
if _, found := ans[end]; !found {
|
||||
rune_offsets = append(rune_offsets, end)
|
||||
ans[end] = -1
|
||||
}
|
||||
}
|
||||
}
|
||||
slices.Sort(rune_offsets)
|
||||
for _, pos := range rune_offsets {
|
||||
if ans[pos] = rune_to_bytes(pos); ans[pos] < 0 {
|
||||
return nil, fmt.Errorf("Matches are not monotonic cannot map rune offsets to byte offsets")
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
for m != nil {
|
||||
groups := m.Groups()
|
||||
bom, err := get_byte_offset_map(groups)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
match := Match{Groups: make([]Group, len(groups))}
|
||||
for i, g := range m.Groups() {
|
||||
match.Groups[i].Name = g.Name
|
||||
match.Groups[i].IsNamed = g.Name != "" && g.Name != strconv.Itoa(i)
|
||||
for _, c := range g.Captures {
|
||||
cn := Capture{Text: c.String(), Text_as_runes: c.Runes()}
|
||||
cn.Rune_Offsets.End = c.Index + c.Length
|
||||
cn.Rune_Offsets.Start = c.Index
|
||||
cn.Byte_Offsets.Start, cn.Byte_Offsets.End = bom[c.Index], bom[cn.Rune_Offsets.End]
|
||||
match.Groups[i].Captures = append(match.Groups[i].Captures, cn)
|
||||
}
|
||||
}
|
||||
ans = append(ans, match)
|
||||
m, _ = re.FindNextMatch(m)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Go's regexp only considers ASCII characters when matching \b whereas regexp2
|
||||
// uses Unicode word characters. So replace every non-ASCII rune with a single
|
||||
// ASCII byte that is a word character iff the rune is one, and return the byte
|
||||
// offsets of the runes in text, to map match offsets back.
|
||||
func ascii_word_proxy(text string) (proxy string, byte_offsets []int) {
|
||||
if !slices.ContainsFunc(utils.UnsafeStringToBytes(text), func(b byte) bool { return b >= utf8.RuneSelf }) {
|
||||
return text, nil
|
||||
}
|
||||
buf := make([]byte, 0, len(text))
|
||||
byte_offsets = make([]int, 0, len(text)+1)
|
||||
for i, r := range text {
|
||||
byte_offsets = append(byte_offsets, i)
|
||||
switch {
|
||||
case r < utf8.RuneSelf:
|
||||
buf = append(buf, byte(r))
|
||||
case syntax.IsWordChar(r):
|
||||
buf = append(buf, '_')
|
||||
default:
|
||||
buf = append(buf, 0x7f)
|
||||
}
|
||||
}
|
||||
return string(buf), append(byte_offsets, len(text))
|
||||
}
|
||||
|
||||
func find_all_matches_stdlib(re *regexp.Regexp, text string, unicode_word_boundaries bool) (ans []Match) {
|
||||
haystack, byte_offsets := text, []int(nil)
|
||||
if unicode_word_boundaries {
|
||||
haystack, byte_offsets = ascii_word_proxy(text)
|
||||
}
|
||||
names := re.SubexpNames()
|
||||
for _, loc := range re.FindAllStringSubmatchIndex(haystack, -1) {
|
||||
match := Match{Groups: make([]Group, len(names))}
|
||||
for i, name := range names {
|
||||
match.Groups[i] = Group{Name: name, IsNamed: name != ""}
|
||||
if s, e := loc[2*i], loc[2*i+1]; s > -1 {
|
||||
if byte_offsets != nil {
|
||||
s, e = byte_offsets[s], byte_offsets[e]
|
||||
}
|
||||
c := Capture{Text: text[s:e]}
|
||||
c.Byte_Offsets.Start, c.Byte_Offsets.End = s, e
|
||||
match.Groups[i].Captures = []Capture{c}
|
||||
}
|
||||
}
|
||||
ans = append(ans, match)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func mark(all_matches []Match, post_processors []PostProcessorFunc, group_processors []GroupProcessorFunc, text string, opts *Options) (ans []Mark) {
|
||||
sanitize_pat := regexp.MustCompile("[\r\n\x00]")
|
||||
for i, m := range all_matches {
|
||||
full_capture := m.Groups[0].LastCapture()
|
||||
match_start, match_end := full_capture.Byte_Offsets.Start, full_capture.Byte_Offsets.End
|
||||
for match_end > match_start+1 && text[match_end-1] == 0 {
|
||||
match_end--
|
||||
}
|
||||
full_match := text[match_start:match_end]
|
||||
if len([]rune(full_match)) < opts.MinimumMatchLength {
|
||||
continue
|
||||
}
|
||||
for _, f := range post_processors {
|
||||
match_start, match_end = f(text, match_start, match_end)
|
||||
if match_start < 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
if match_start < 0 {
|
||||
continue
|
||||
}
|
||||
full_match = sanitize_pat.ReplaceAllLiteralString(text[match_start:match_end], "")
|
||||
gd := make(map[string]string, len(m.Groups))
|
||||
for idx, g := range m.Groups {
|
||||
if idx > 0 && g.IsNamed {
|
||||
c := g.LastCapture()
|
||||
if s, e := c.Byte_Offsets.Start, c.Byte_Offsets.End; s > -1 && e > -1 {
|
||||
s = max(s, match_start)
|
||||
e = min(e, match_end)
|
||||
gd[g.Name] = sanitize_pat.ReplaceAllLiteralString(text[s:e], "")
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, f := range group_processors {
|
||||
f(gd)
|
||||
}
|
||||
gd2 := make(map[string]any, len(gd))
|
||||
for k, v := range gd {
|
||||
gd2[k] = v
|
||||
}
|
||||
if opts.Type == "regex" && len(m.Groups) > 1 && !m.HasNamedGroups() {
|
||||
cp := m.Groups[1].LastCapture()
|
||||
ms, me := cp.Byte_Offsets.Start, cp.Byte_Offsets.End
|
||||
match_start = max(match_start, ms)
|
||||
match_end = min(match_end, me)
|
||||
full_match = sanitize_pat.ReplaceAllLiteralString(text[match_start:match_end], "")
|
||||
}
|
||||
if full_match != "" {
|
||||
ans = append(ans, Mark{
|
||||
Index: i, Start: match_start, End: match_end, Text: full_match, Groupdict: gd2,
|
||||
})
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
type ErrNoMatches struct{ Type, Pattern string }
|
||||
|
||||
func is_word_char(ch rune, current_chars []rune) bool {
|
||||
return unicode.IsLetter(ch) || unicode.IsNumber(ch) || (unicode.IsMark(ch) && len(current_chars) > 0 && unicode.IsLetter(current_chars[len(current_chars)-1]))
|
||||
}
|
||||
|
||||
func mark_words(text string, opts *Options) (ans []Mark) {
|
||||
left := text
|
||||
var current_run struct {
|
||||
chars []rune
|
||||
start, size int
|
||||
}
|
||||
chars := opts.WordCharacters
|
||||
if chars == "" {
|
||||
chars = RelevantKittyOpts().Select_by_word_characters
|
||||
}
|
||||
allowed_chars := make(map[rune]bool, len(chars))
|
||||
for _, ch := range chars {
|
||||
allowed_chars[ch] = true
|
||||
}
|
||||
pos := 0
|
||||
post_processors := []PostProcessorFunc{PostProcessorMap()["brackets"], PostProcessorMap()["quotes"]}
|
||||
|
||||
commit_run := func() {
|
||||
if len(current_run.chars) >= opts.MinimumMatchLength {
|
||||
match_start, match_end := current_run.start, current_run.start+current_run.size
|
||||
for _, f := range post_processors {
|
||||
match_start, match_end = f(text, match_start, match_end)
|
||||
if match_start < 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
if match_start > -1 && match_end > match_start {
|
||||
full_match := text[match_start:match_end]
|
||||
if len([]rune(full_match)) >= opts.MinimumMatchLength {
|
||||
ans = append(ans, Mark{
|
||||
Index: len(ans), Start: match_start, End: match_end, Text: full_match,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
current_run.chars = nil
|
||||
current_run.start = 0
|
||||
current_run.size = 0
|
||||
}
|
||||
|
||||
for {
|
||||
ch, size := utf8.DecodeRuneInString(left)
|
||||
if ch == utf8.RuneError {
|
||||
break
|
||||
}
|
||||
if allowed_chars[ch] || is_word_char(ch, current_run.chars) {
|
||||
if len(current_run.chars) == 0 {
|
||||
current_run.start = pos
|
||||
}
|
||||
current_run.chars = append(current_run.chars, ch)
|
||||
current_run.size += size
|
||||
} else {
|
||||
commit_run()
|
||||
}
|
||||
left = left[size:]
|
||||
pos += size
|
||||
}
|
||||
commit_run()
|
||||
return
|
||||
}
|
||||
|
||||
func adjust_python_offsets(text string, marks []Mark) error {
|
||||
// python returns rune based offsets (unicode chars not utf-8 bytes)
|
||||
adjust := utils.RuneOffsetsToByteOffsets(text)
|
||||
for i := range marks {
|
||||
mark := &marks[i]
|
||||
if mark.End < mark.Start {
|
||||
return fmt.Errorf("The end of a mark must not be before its start")
|
||||
}
|
||||
s, e := adjust(mark.Start), adjust(mark.End)
|
||||
if s < 0 || e < 0 {
|
||||
return fmt.Errorf("Overlapping marks are not supported")
|
||||
}
|
||||
mark.Start, mark.End = s, e
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *ErrNoMatches) Error() string {
|
||||
none_of := "matches"
|
||||
switch self.Type {
|
||||
case "urls":
|
||||
none_of = "URLs"
|
||||
case "hyperlinks":
|
||||
none_of = "hyperlinks"
|
||||
}
|
||||
if self.Pattern != "" {
|
||||
return fmt.Sprintf("No %s found with pattern: %s", none_of, self.Pattern)
|
||||
}
|
||||
return fmt.Sprintf("No %s found", none_of)
|
||||
}
|
||||
|
||||
func find_marks(text string, opts *Options, cli_args ...string) (sanitized_text string, ans []Mark, index_map map[int]*Mark, err error) {
|
||||
sanitized_text, hyperlinks := process_escape_codes(text)
|
||||
used_pattern := ""
|
||||
|
||||
run_basic_matching := func() error {
|
||||
pattern, post_processors, group_processors, err := functions_for(opts)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var matches []Match
|
||||
// the builtin patterns dont need lookarounds, so use the linear time stdlib engine for them
|
||||
if pattern != opts.Regex {
|
||||
r, err := regexp.Compile(pattern)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Failed to compile the regex pattern: %#v with error: %w", pattern, err)
|
||||
}
|
||||
// the proxy text is only valid for patterns that dont reference specific non-ASCII characters
|
||||
matches = find_all_matches_stdlib(r, sanitized_text, opts.Type == "path" || opts.Type == "linenum")
|
||||
} else {
|
||||
r, err := regexp2.Compile(pattern, regexp2.RE2)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Failed to compile the regex pattern: %#v with error: %w", pattern, err)
|
||||
}
|
||||
matches, _ = find_all_matches(r, sanitized_text)
|
||||
}
|
||||
ans = mark(matches, post_processors, group_processors, sanitized_text, opts)
|
||||
used_pattern = pattern
|
||||
return nil
|
||||
}
|
||||
|
||||
if opts.CustomizeProcessing != "" {
|
||||
cmd := exec.Command(utils.KittyExe(), append([]string{"+runpy", "from kittens.hints.main import custom_marking; custom_marking()"}, cli_args...)...)
|
||||
cmd.Stdin = strings.NewReader(sanitized_text)
|
||||
stdout, stderr := bytes.Buffer{}, bytes.Buffer{}
|
||||
cmd.Stdout, cmd.Stderr = &stdout, &stderr
|
||||
err = cmd.Run()
|
||||
if err != nil {
|
||||
var e *exec.ExitError
|
||||
if errors.As(err, &e) && e.ExitCode() == 2 {
|
||||
err = run_basic_matching()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
goto process_answer
|
||||
} else {
|
||||
return "", nil, nil, fmt.Errorf("Failed to run custom processor %#v with error: %w\n%s", opts.CustomizeProcessing, err, stderr.String())
|
||||
}
|
||||
}
|
||||
ans = make([]Mark, 0, 32)
|
||||
err = json.Unmarshal(stdout.Bytes(), &ans)
|
||||
if err != nil {
|
||||
return "", nil, nil, fmt.Errorf("Failed to load output from custom processor %#v with error: %w", opts.CustomizeProcessing, err)
|
||||
}
|
||||
err = adjust_python_offsets(sanitized_text, ans)
|
||||
if err != nil {
|
||||
return "", nil, nil, fmt.Errorf("Custom processor %#v produced invalid mark output with error: %w", opts.CustomizeProcessing, err)
|
||||
}
|
||||
} else if opts.Type == "hyperlink" {
|
||||
ans = hyperlinks
|
||||
} else if opts.Type == "word" {
|
||||
ans = mark_words(sanitized_text, opts)
|
||||
} else {
|
||||
err = run_basic_matching()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
process_answer:
|
||||
if len(ans) == 0 {
|
||||
return "", nil, nil, &ErrNoMatches{Type: opts.Type, Pattern: used_pattern}
|
||||
}
|
||||
largest_index := ans[len(ans)-1].Index
|
||||
offset := max(0, opts.HintsOffset)
|
||||
if opts.PrefixFree {
|
||||
alphabetLength := len(opts.Alphabet)
|
||||
if alphabetLength == 0 {
|
||||
alphabetLength = len(DEFAULT_HINT_ALPHABET)
|
||||
}
|
||||
offset = max(offset, hints_to_skip(len(ans), alphabetLength))
|
||||
}
|
||||
index_map = make(map[int]*Mark, len(ans))
|
||||
for i := range ans {
|
||||
m := &ans[i]
|
||||
if opts.Ascending {
|
||||
m.Index += offset
|
||||
} else {
|
||||
m.Index = largest_index - m.Index + offset
|
||||
}
|
||||
index_map[m.Index] = m
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package hints
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/kovidgoyal/kitty"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func TestHintMarking(t *testing.T) {
|
||||
|
||||
var opts *Options
|
||||
cols := 20
|
||||
cli_args := []string{}
|
||||
|
||||
reset := func() {
|
||||
opts = &Options{Type: "url", UrlPrefixes: "default", Regex: kitty.HintsDefaultRegex}
|
||||
cols = 20
|
||||
cli_args = []string{}
|
||||
}
|
||||
|
||||
r := func(text string, url ...string) (marks []Mark) {
|
||||
ptext := convert_text(text, cols)
|
||||
ptext, marks, _, err := find_marks(ptext, opts, cli_args...)
|
||||
if err != nil {
|
||||
var e *ErrNoMatches
|
||||
if len(url) != 0 || !errors.As(err, &e) {
|
||||
t.Fatalf("%#v failed with error: %s", text, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
actual := utils.Map(func(m Mark) string { return m.Text }, marks)
|
||||
if diff := cmp.Diff(url, actual); diff != "" {
|
||||
t.Fatalf("%#v failed:\n%s", text, diff)
|
||||
}
|
||||
for _, m := range marks {
|
||||
q := strings.NewReplacer("\n", "", "\r", "", "\x00", "").Replace(ptext[m.Start:m.End])
|
||||
if diff := cmp.Diff(m.Text, q); diff != "" {
|
||||
t.Fatalf("Mark start (%d) and end (%d) dont point to correct offset in text for %#v\n%s", m.Start, m.End, text, diff)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
reset()
|
||||
u := `http://test.me/`
|
||||
r(u, u)
|
||||
r(u+"#fragme", u+"#fragme")
|
||||
r(`"`+u+`"`, u)
|
||||
r("("+u+")", u)
|
||||
cols = len(u)
|
||||
r(u+"\nxxx", u+"xxx")
|
||||
cols = 20
|
||||
r("link:"+u+"[xxx]", u)
|
||||
r("`xyz <"+u+">`_.", u)
|
||||
r(`<a href="`+u+`">moo`, u)
|
||||
r("\x1b[mhttp://test.me/1234\n\x1b[mx", "http://test.me/1234")
|
||||
r("\x1b[mhttp://test.me/12345\r\x1b[m6\n\x1b[mx", "http://test.me/123456")
|
||||
r("http://example.com,", "http://example.com")
|
||||
r("http://example.com.", "http://example.com")
|
||||
r("http://example.com!", "http://example.com")
|
||||
r("http://example.com?", "http://example.com")
|
||||
r("“"+u+"”", u)
|
||||
r("‘"+u+"’", u)
|
||||
|
||||
opts.Type = "linenum"
|
||||
m := func(text, path string, line int) {
|
||||
ptext := convert_text(text, cols)
|
||||
_, marks, _, err := find_marks(ptext, opts, cli_args...)
|
||||
if err != nil {
|
||||
t.Fatalf("%#v failed with error: %s", text, err)
|
||||
}
|
||||
gd := map[string]any{"path": path, "line": strconv.Itoa(line)}
|
||||
if diff := cmp.Diff(marks[0].Groupdict, gd); diff != "" {
|
||||
t.Fatalf("%#v failed:\n%s", text, diff)
|
||||
}
|
||||
}
|
||||
m("file.c:23", "file.c", 23)
|
||||
m("file.c:23:32", "file.c", 23)
|
||||
m("file.cpp:23:1", "file.cpp", 23)
|
||||
m("a/file.c:23", "a/file.c", 23)
|
||||
m("a/file.c:23:32", "a/file.c", 23)
|
||||
m("~/file.c:23:32", utils.Expanduser("~/file.c"), 23)
|
||||
|
||||
reset()
|
||||
opts.Type = "path"
|
||||
r("file.c", "file.c")
|
||||
r("file.c.", "file.c")
|
||||
r("file.epub.", "file.epub")
|
||||
r("(file.epub)", "file.epub")
|
||||
r("some/path", "some/path")
|
||||
r("“some/path”", "some/path")
|
||||
r("Saving to: ‘index.html’", "index.html")
|
||||
// a match consisting of only a quote must not result in start > end
|
||||
for _, text := range []string{`"`, `'`, `""`, "“”", "“"} {
|
||||
for _, name := range []string{"quotes", "brackets"} {
|
||||
if s, e := PostProcessorMap()[name](text, 0, len(text)); s > e {
|
||||
t.Fatalf("%s post processor returned start (%d) > end (%d) for %#v", name, s, e, text)
|
||||
}
|
||||
}
|
||||
}
|
||||
// long lines without spaces must not cause quadratic backtracking
|
||||
long_line := strings.Repeat("1,", 20000)
|
||||
r(long_line)
|
||||
r("漢字 "+long_line+" some/path", "some/path")
|
||||
r("漢字"+long_line+"a.txt", "漢字"+long_line+"a.txt")
|
||||
// \b must use Unicode word characters, like regexp2
|
||||
r("config.yaml文件")
|
||||
r("a.txt文 é/b.c", "a.txt文", "é/b.c")
|
||||
opts.Type = "linenum"
|
||||
r(long_line)
|
||||
m(long_line+" a/file.c:23", "a/file.c", 23)
|
||||
|
||||
reset()
|
||||
cols = 60
|
||||
opts.Type = "ip"
|
||||
r(`100.64.0.0`, `100.64.0.0`)
|
||||
r(`2001:0db8:0000:0000:0000:ff00:0042:8329`, `2001:0db8:0000:0000:0000:ff00:0042:8329`)
|
||||
r(`2001:db8:0:0:0:ff00:42:8329`, `2001:db8:0:0:0:ff00:42:8329`)
|
||||
r(`2001:db8::ff00:42:8329`, `2001:db8::ff00:42:8329`)
|
||||
r(`2001:DB8::FF00:42:8329`, `2001:DB8::FF00:42:8329`)
|
||||
r(`0000:0000:0000:0000:0000:0000:0000:0001`, `0000:0000:0000:0000:0000:0000:0000:0001`)
|
||||
r(`2600:1901:0:b2bd::`, `2600:1901:0:b2bd::`) // ifconfig.me
|
||||
r(`::1`, `::1`)
|
||||
r(`255.255.255.256`)
|
||||
r(`:1`)
|
||||
|
||||
reset()
|
||||
opts.Type = "regex"
|
||||
opts.Regex = `(?ms)^[*]?\s(\S+)`
|
||||
r(`* 2b687c2 - test1`, `2b687c2`)
|
||||
opts.Regex = `(?<=got: )sha256.{4}`
|
||||
r(`got: sha256-L8=`, `sha256-L8=`)
|
||||
|
||||
reset()
|
||||
opts.Type = "word"
|
||||
r(`#one (two) 😍 a-1b `, `#one`, `two`, `a-1b`)
|
||||
r("fōtiz час a\u0310b ", `fōtiz`, `час`, "a\u0310b")
|
||||
|
||||
reset()
|
||||
tdir := t.TempDir()
|
||||
simple := filepath.Join(tdir, "simple.py")
|
||||
cli_args = []string{"--customize-processing", simple, "extra1"}
|
||||
os.WriteFile(simple, []byte(`
|
||||
def mark(text, args, Mark, extra_cli_args, *a):
|
||||
import re
|
||||
for idx, m in enumerate(re.finditer(r'\w+', text)):
|
||||
start, end = m.span()
|
||||
mark_text = text[start:end].replace('\n', '').replace('\0', '')
|
||||
yield Mark(idx, start, end, mark_text, {"idx": idx, "args": extra_cli_args})
|
||||
`), 0o600)
|
||||
opts.Type = "regex"
|
||||
opts.CustomizeProcessing = simple
|
||||
marks := r("漢字 b", `漢字`, `b`)
|
||||
if diff := cmp.Diff(marks[0].Groupdict, map[string]any{"idx": float64(0), "args": []any{"extra1"}}); diff != "" {
|
||||
t.Fatalf("Did not get expected groupdict from custom processor:\n%s", diff)
|
||||
}
|
||||
opts.Regex = "b"
|
||||
os.WriteFile(simple, []byte(""), 0o600)
|
||||
r("a b", `b`)
|
||||
}
|
||||
Reference in new issue
Block a user