From e698e1acaaa43ee28eadd3109f4488d1e15a1905 Mon Sep 17 00:00:00 2001 From: jinil-ha Date: Mon, 30 Nov 2026 17:59:28 +0900 Subject: [PATCH] Align English search results with Japanese comparison passages --- README.jp.md | 2 +- README.kr.md | 2 +- README.md | 2 +- cmd/tgrep/main_test.go | 65 +++++++++--- internal/cli/cli.go | 6 +- internal/documents/alignment.go | 148 +++++++++++++++++++++++++++ internal/documents/alignment_test.go | 54 ++++++++++ internal/documents/markdown.go | 77 ++++++++++++++ internal/editor/compare.vim | 33 ++++-- internal/editor/editor.go | 5 +- internal/search/search.go | 26 +---- 11 files changed, 367 insertions(+), 53 deletions(-) create mode 100644 internal/documents/alignment.go create mode 100644 internal/documents/alignment_test.go create mode 100644 internal/documents/markdown.go diff --git a/README.jp.md b/README.jp.md index 6b0305c..9974758 100644 --- a/README.jp.md +++ b/README.jp.md @@ -56,7 +56,7 @@ tgrep 'sign in' - 別々に読みたいときは `s` を押し、左キーで原文、右キーで翻訳を選んでスクロールします。もう一度 `s` を押すと、選択中のペインの位置から連動を再開します。 - `Esc` で元の検索結果に戻ります。 -連動中は両方のペインが行番号で揃います。翻訳で行を追加・削除した場合は、対応する文の位置がずれることがあります。 +英語の原文と日本語訳を比較するときは、検索結果の直前にある共通のアンカーか対応する Markdown 見出しを基準に、段落の順番と段落内の行番号を合わせます。対応するアンカーや見出しがなければ、文書の先頭から数えます。原文で見つかった行が日本語の段落の長さを超える場合は、その段落の最終行を表示します。連動スクロールでは、最初に合わせた行番号の差を保ちます。 ## 翻訳を直接編集する diff --git a/README.kr.md b/README.kr.md index 201eb91..2d635f5 100644 --- a/README.kr.md +++ b/README.kr.md @@ -56,7 +56,7 @@ tgrep 'sign in' - 따로 읽으려면 `s`를 누르고 `←`로 원문, `→`로 번역을 선택해 스크롤합니다. `s`를 다시 누르면 선택한 패널의 위치에서 연동을 재개합니다. - `Esc`를 누르면 같은 검색 결과로 돌아옵니다. -연동 모드에서는 두 패널이 줄 번호를 기준으로 맞춰집니다. 번역에서 줄을 추가하거나 삭제했다면 같은 문장이 다른 줄에 있을 수 있습니다. +영어 원문과 일본어 번역을 비교할 때는 검색 결과 앞에서 가장 가까운 공통 앵커나 대응하는 마크다운 제목을 찾아 문단 순서와 문단 안의 줄 번호를 맞춥니다. 기준이 될 앵커나 제목이 없으면 문서 처음부터 셉니다. 원문에서 찾은 줄이 일본어 문단의 길이를 넘으면 그 문단의 마지막 줄을 표시합니다. 연동 스크롤은 처음 맞춘 두 줄의 간격을 유지합니다. ## 바로 편집하기 diff --git a/README.md b/README.md index aa4d81c..831e9bf 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,7 @@ When the comparison opens, matching text is highlighted in both panes using the - To scroll independently, press `s`, then select the source with Left or the translation with Right. Press `s` again to link both panes at the active pane’s position. - Press `Esc` to return to the same search result. -Linked scrolling aligns the panes by line number. Adding or removing lines in a translation can put corresponding passages on different rows. +For English–Japanese comparisons, tgrep finds the nearest preceding shared anchor or corresponding Markdown heading, then counts paragraphs and lines from there. With no matching anchor or heading, it counts from the start of the document. If the match falls beyond the end of the Japanese paragraph, the cursor lands on its last line. Linked scrolling keeps the initial line offset between panes. ## Edit a translation diff --git a/cmd/tgrep/main_test.go b/cmd/tgrep/main_test.go index 4d01dcf..6c9509a 100644 --- a/cmd/tgrep/main_test.go +++ b/cmd/tgrep/main_test.go @@ -112,7 +112,8 @@ TGREP_ENTER_ACTION=edit } } -func TestComparisonInVim(t *testing.T) { +func checkComparison(t *testing.T, root, check string, env, args []string) { + t.Helper() vim, err := exec.LookPath("vim") if err != nil { t.Skip("vim unavailable") @@ -121,15 +122,24 @@ func TestComparisonInVim(t *testing.T) { if err != nil { t.Fatal(err) } + // Let Vim open the real embedded script with the comparison's arguments, + // then inspect its windows after startup without requiring a terminal. + writeFile(t, filepath.Join(root, "bin/vim"), "#!/bin/sh\nexec \"$REAL_VIM\" -es --cmd 'autocmd VimEnter * execute \"source \" . fnameescape($HOME . \"/check.vim\")' \"$@\"\n", 0755) + writeFile(t, filepath.Join(root, "check.vim"), check+"\ncall writefile(v:errors, $HOME . '/errors')\nqa!\n", 0644) + _, log, code := invoke(t, root, append(env, "REAL_VIM="+vim, "TGREP_SCRIPT_PATH="+self, "LC_ALL=en_US.UTF-8"), args) + issues, err := os.ReadFile(filepath.Join(root, "errors")) + if code != 0 || err != nil || len(issues) > 0 { + t.Fatalf("vim: exit %d, %v, %s %s", code, err, issues, log) + } +} + +func TestComparisonInVim(t *testing.T) { root := t.TempDir() origin := "\ufeffhi\r\n한 hi\r\n" + strings.Repeat("wrapped ", 60) + "\r\n" target := "Hi\n" writeFile(t, filepath.Join(root, "en/doc"), origin, 0644) writeFile(t, filepath.Join(root, "ja/doc"), target, 0644) - // Let Vim open the real embedded script with the comparison's arguments, - // then inspect its windows after startup without requiring a terminal. - writeFile(t, filepath.Join(root, "bin/vim"), "#!/bin/sh\nexec \"$REAL_VIM\" -es --cmd 'autocmd VimEnter * execute \"source \" . fnameescape($HOME . \"/check.vim\")' \"$@\"\n", 0755) - writeFile(t, filepath.Join(root, "check.vim"), `call assert_equal('en/doc', bufname()) + checkComparison(t, root, `call assert_equal('en/doc', bufname()) call assert_equal(2, line('.')) call assert_equal([1, 1, 2], getmatches()[0].pos1) call assert_equal([2, 5, 2], getmatches()[0].pos2) @@ -137,22 +147,16 @@ call assert_equal(1, g:linked_scroll) wincmd l call assert_equal('ja/doc', bufname()) call assert_equal([1, 1, 2], getmatches()[0].pos1) -call assert_equal(3, line('$')) -call assert_true(strlen(getline(3)) > 0) +call assert_equal(1, line('.')) +call assert_equal(2, line('$')) +call assert_true(strlen(getline(2)) > 0) normal s call assert_equal(0, g:linked_scroll) call assert_equal(['Hi'], getline(1,'$')) normal s call assert_equal(1, g:linked_scroll) call assert_true(&readonly && !&modifiable) -call writefile(v:errors, $HOME . '/errors') -qa! -`, 0644) - _, log, code := invoke(t, root, []string{"REAL_VIM=" + vim, "TGREP_SCRIPT_PATH=" + self, "TGREP_QUERY=hi", "TGREP_TARGET_LANGS=ko,ja", "LC_ALL=en_US.UTF-8"}, []string{"--_compare", "2", "doc", "2"}) - issues, err := os.ReadFile(filepath.Join(root, "errors")) - if code != 0 || err != nil || len(issues) > 0 { - t.Fatalf("vim: exit %d, %v, %s %s", code, err, issues, log) - } +`, []string{"TGREP_QUERY=hi", "TGREP_TARGET_LANGS=ko,ja"}, []string{"--_compare", "2", "doc", "2"}) for lang, want := range map[string]string{"en": origin, "ja": target} { b, err := os.ReadFile(filepath.Join(root, lang, "doc")) if err != nil || string(b) != want { @@ -160,3 +164,34 @@ qa! } } } + +func TestKoreanComparisonUsesSourceLine(t *testing.T) { + root := t.TempDir() + writeFile(t, filepath.Join(root, "en/doc"), "wrapped\nparagraph\n\nhit\n", 0644) + writeFile(t, filepath.Join(root, "ko/doc"), "첫 문단\n\n다음 문단\n원문의 줄 번호\n", 0644) + checkComparison(t, root, `call assert_equal(4, line('.')) +call assert_equal(4, getcurpos(win_getid(2))[1]) +`, []string{"TGREP_QUERY=hit", "TGREP_TARGET_LANGS=ko,ja"}, []string{"--_compare", "1", "doc", "4"}) +} + +func TestJapaneseComparisonScroll(t *testing.T) { + root := t.TempDir() + writeFile(t, filepath.Join(root, "en/doc"), strings.Repeat("intro\n", 40)+"## Use pods {#pods}\n\nfirst paragraph\ncontinues\n\na matched\npassage\n\nnext\n"+strings.Repeat("tail\n", 25), 0644) + writeFile(t, filepath.Join(root, "ja/doc"), strings.Repeat("冒頭\n", 16)+"## Pod の使用 {#pods}\n\n最初の段落\n\n該当する段落\n\n次\n"+strings.Repeat("末尾\n", 25), 0644) + checkComparison(t, root, `call assert_equal(47, line('.')) +call assert_equal(21, getcurpos(win_getid(2))[1]) +call assert_equal('該当する段落', getbufline(winbufnr(2), 21)[0]) +normal! 49G +doautocmd CursorMoved +call assert_equal(23, getcurpos(win_getid(2))[1]) +normal s +wincmd l +normal! 25G +doautocmd CursorMoved +call assert_equal(49, getcurpos(win_getid(1))[1]) +normal s +call assert_equal(51, getcurpos(win_getid(1))[1]) +doautocmd VimResized +call assert_equal(51, getcurpos(win_getid(1))[1]) +`, []string{"TGREP_QUERY=passage", "TGREP_TARGET_LANGS=ja,ko"}, []string{"--_compare", "1", "doc", "47"}) +} diff --git a/internal/cli/cli.go b/internal/cli/cli.go index fae684f..0fea9f9 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -120,5 +120,9 @@ func view(tree documents.Tree, args []string) (int, error) { if !tree.Has(lang, path) { return picker.Message(fmt.Sprintf("No translation available for %s/%s.", lang, path)) } - return 0, editor.Compare(c.Root, filepath.Join(c.Origin, path), filepath.Join(lang, path), line) + targetLine, err := tree.ComparisonLine(lang, path, line) + if err != nil { + return 1, err + } + return 0, editor.Compare(c.Root, filepath.Join(c.Origin, path), filepath.Join(lang, path), line, targetLine) } diff --git a/internal/documents/alignment.go b/internal/documents/alignment.go new file mode 100644 index 0000000..bd75d57 --- /dev/null +++ b/internal/documents/alignment.go @@ -0,0 +1,148 @@ +package documents + +import ( + "os" + "strings" +) + +// ComparisonLine locates the English search result in the Japanese document. +// Both the input and returned line numbers are one-based, as in Vim. +func (t Tree) ComparisonLine(lang, path string, line int) (int, error) { + sourceLang, _, _ := strings.Cut(t.Config.Origin, "-") + targetLang, _, _ := strings.Cut(lang, "-") + if !strings.EqualFold(sourceLang, "en") || !strings.EqualFold(targetLang, "ja") { + return line, nil + } + source, err := readLines(t.Path(t.Config.Origin, path)) + if err != nil { + return 0, err + } + target, err := readLines(t.Path(lang, path)) + if err != nil { + return 0, err + } + return alignedLine(source, target, line), nil +} + +func readLines(path string) ([]string, error) { + data, err := os.ReadFile(path) + if err != nil { + return nil, err + } + text := strings.TrimPrefix(string(data), "\ufeff") + return strings.Split(strings.TrimSuffix(text, "\n"), "\n"), nil +} + +// A repeated ID is ambiguous. Only use IDs that identify one line per document. +func uniqueLines(marks []anchor) map[string]int { + lines := make(map[string]int) + for _, a := range marks { + if _, seen := lines[a.key]; seen { + lines[a.key] = -1 + } else if a.key != "" { + lines[a.key] = a.line + } + } + return lines +} + +type linePair struct{ source, target int } + +func headingsBetween(marks []anchor, start, end, level int) []anchor { + var headings []anchor + for _, a := range marks { + if a.line > start && a.line < end && a.level == level { + headings = append(headings, a) + } + } + return headings +} + +// Bracket the hit with shared anchors. Within that interval, translated +// headings can also serve as anchors when their count and levels agree. +func section(source, target []string, hit int) (linePair, linePair) { + left, right := anchors(source), anchors(target) + originIDs, targetIDs := uniqueLines(left), uniqueLines(right) + start, end := linePair{-1, -1}, linePair{len(source), len(target)} + for _, a := range left { + n, ok := targetIDs[a.key] + if !ok || n < 0 || originIDs[a.key] != a.line { + continue + } + if a.line <= hit { + start = linePair{a.line, n} + } else if n > start.target { + end = linePair{a.line, n} + break + } + } + // Pair sibling headings from the outermost level inward. A different + // subsection count does not invalidate already matched parent headings. + for level := 1; level <= 6; level++ { + src := headingsBetween(left, start.source, end.source, level) + dst := headingsBetween(right, start.target, end.target, level) + if len(src) != len(dst) { + break + } + for i, a := range src { + if a.line > hit { + end = linePair{a.line, dst[i].line} + break + } + start = linePair{a.line, dst[i].line} + } + } + return start, end +} + +type paragraph struct{ first, last int } + +func paragraphs(lines []string) []paragraph { + var result []paragraph + for i := 0; i < len(lines); i++ { + text := strings.TrimSpace(lines[i]) + if text == "" { + continue + } + first := i + for i+1 < len(lines) && strings.TrimSpace(lines[i+1]) != "" { + i++ + } + // A section marker may appear in just one language. It has no translated prose. + if first == i && standaloneComment(text) { + continue + } + result = append(result, paragraph{first, i}) + } + return result +} + +func alignedLine(source, target []string, line int) int { + hit := min(max(0, line-1), len(source)-1) + start, end := section(source, target, hit) + if start.source == hit { + return max(1, start.target+1) + } + base := start.target + 1 + targetText := target[base:end.target] + dst := paragraphs(targetText) + if len(dst) == 0 { + // An omitted section has only its heading (or the start of the file). + return max(1, start.target+1) + } + src := paragraphs(source[start.source+1 : end.source]) + offset := hit - (start.source + 1) + for i, p := range src { + if i == len(dst) { + return base + dst[i-1].last + 1 + } + q := dst[i] + if offset < p.first { + return base + max(0, q.first-1) + 1 + } + if offset <= p.last { + return base + min(q.first+offset-p.first, q.last) + 1 + } + } + return base + len(targetText) +} diff --git a/internal/documents/alignment_test.go b/internal/documents/alignment_test.go new file mode 100644 index 0000000..cc8df74 --- /dev/null +++ b/internal/documents/alignment_test.go @@ -0,0 +1,54 @@ +package documents + +import ( + "strings" + "testing" + + "github.com/antfrog/tgrep/internal/config" +) + +func TestAlignedLine(t *testing.T) { + for _, tt := range []struct { + name, source, target string + hit, want int + }{ + {"shorter paragraph", "start\n\nfirst\nsecond\nthird\n\nlater", "最初\n\n一行にまとめた訳\n\n次", 5, 3}, + {"within paragraph", "a\nb\nc\n\nd\ne", "冒頭\n \t\n\nい\nろ\nは", 6, 5}, + {"shared ID on heading", "extra\n\nparagraph\n\n## Heading {#one}\nhit", "## 見出し {#one}\n該当行", 6, 2}, + {"English implicit heading ID", "extra\n\n## What's next?\nread on", "## 次のステップ {#whats-next}\n次へ\n## 補足", 3, 1}, + {"translated headings by structure", "extra\n\nparagraph\n\n## First\nfirst\n\n### Second\nhit", "## 初め\n一\n### 次\n該当行", 9, 4}, + {"translated parent with different subsection counts", "## Intro\n\nextra\n\nparagraph\n\n## Using Pods\n\nhit\n\n### Note", "## はじめに\n一\n## Podを使用する\n\n該当行", 9, 5}, + {"nearest shared HTML anchor", "\nextra\n\nparagraph\n\nhit", "\n一\n\n二", 6, 4}, + {"shared section marker", "first\n\nextra\n\nmatched", "\n該当行", 5, 2}, + {"untranslated section marker", "---\ntitle: Pods\n---\n\n\n\nfirst\n\nsecond", "---\ntitle: Pod\n---\n\n最初\n\n次", 7, 5}, + {"missing paragraph stays before next anchor", "## A {#a}\n\none\n\nextra\n\n## B {#b}", "## あ {#a}\n\n一\n\n## い {#b}", 5, 3}, + {"omitted section", "## A {#a}\none\n## B {#b}", "## あ {#a}\n## い {#b}", 2, 1}, + {"blank line between paragraphs", "one\nwrap\n\n\nhit", "一\n\n次", 3, 2}, + {"empty translation", "one\ntwo", "", 2, 1}, + {"longer translation", "## A\nhit", "追加\n\n## あ\n該当行", 2, 4}, + } { + t.Run(tt.name, func(t *testing.T) { + got := alignedLine(strings.Split(tt.source, "\n"), strings.Split(tt.target, "\n"), tt.hit) + if got != tt.want { + t.Fatalf("source line %d maps to %d, want %d", tt.hit, got, tt.want) + } + }) + } +} + +func TestCodeSampleDoesNotDefineAnchor(t *testing.T) { + source := []string{"## Start {#start}", "intro", "", "````md", "## Example {#fake}", "```", "````", "", "hit"} + target := []string{"## 開始 {#start}", "導入", "", "コード例", "", "該当行", "", "## 例 {#fake}"} + if got := alignedLine(source, target, 9); got != 6 { + t.Fatalf("mapped past the code sample to line %d, want 6", got) + } +} + +func TestOtherLanguagePairsKeepLineNumber(t *testing.T) { + for _, pair := range [][2]string{{"en", "ko"}, {"ja", "en"}, {"ko", "ja"}} { + tree := Tree{Config: config.Config{Origin: pair[0]}} + if line, err := tree.ComparisonLine(pair[1], "doc", 12); line != 12 || err != nil { + t.Fatalf("%s to %s: %d, %v", pair[0], pair[1], line, err) + } + } +} diff --git a/internal/documents/markdown.go b/internal/documents/markdown.go new file mode 100644 index 0000000..b127b04 --- /dev/null +++ b/internal/documents/markdown.go @@ -0,0 +1,77 @@ +package documents + +import ( + "regexp" + "strings" +) + +// BacktickFence tracks the backtick fences excluded from Markdown search. A shorter +// fence, or one with an info string, cannot close the current block. +func BacktickFence(line string, open int) (width int, delimiter bool) { + s := strings.TrimLeft(line, " ") + if len(line)-len(s) > 3 { + return open, false + } + info := strings.TrimLeft(s, "`") + n := len(s) - len(info) + if n < 3 || strings.Contains(info, "`") { + return open, false + } + if open == 0 { + return n, true + } + if n >= open && strings.Trim(info, " \t\r") == "" { + return 0, true + } + return open, true +} + +type anchor struct { + line, level int + key string +} + +var ( + atxHeading = regexp.MustCompile(`^(#{1,6})[ \t]+(.+)$`) + headingID = regexp.MustCompile(`\{\s*#([^\s}]+)\s*\}\s*$`) + punctuation = regexp.MustCompile(`[^\pL\pN\s_-]`) + htmlID = regexp.MustCompile(`(?i)^]*?)?\s+(?:id|name)\s*=\s*(?:"([^"]+)"|'([^']+)')`) +) + +func standaloneComment(line string) bool { + return strings.HasPrefix(line, "") +} + +func anchors(lines []string) []anchor { + var found []anchor + block := 0 + for i, raw := range lines { + var delimiter bool + block, delimiter = BacktickFence(raw, block) + if block != 0 || delimiter { + continue + } + s := strings.TrimLeft(raw, " ") + if len(raw)-len(s) > 3 { + continue + } + s = strings.TrimRight(s, " \t\r") + if h := atxHeading.FindStringSubmatch(s); h != nil { + title := strings.TrimSpace(strings.TrimRight(h[2], "#")) + // A translated heading may explicitly use the English heading's implicit ID. + key := "" + if id := headingID.FindStringSubmatch(title); id != nil { + key = id[1] + } else { + words := punctuation.ReplaceAllString(strings.ToLower(title), "") + key = strings.Join(strings.Fields(words), "-") + } + found = append(found, anchor{i, len(h[1]), key}) + } else if standaloneComment(s) { + found = append(found, anchor{i, 0, s}) + } else if id := htmlID.FindStringSubmatch(s); id != nil { + found = append(found, anchor{i, 0, id[1] + id[2]}) + } + } + return found +} diff --git a/internal/editor/compare.vim b/internal/editor/compare.vim index f9fb9b7..568fe74 100644 --- a/internal/editor/compare.vim +++ b/internal/editor/compare.vim @@ -1,7 +1,5 @@ set showtabline=2 laststatus=2 undolevels=-1 -let rows = max(map(getbufinfo({"bufloaded": 1}), "v:val.linecount")) - windo setlocal wrap nolinebreak nofoldenable number cursorline | let b:source_lines = getline(1, "$") function! HighlightQuery() @@ -34,11 +32,11 @@ highlight TgrepMatch term=reverse cterm=bold ctermfg=Black ctermbg=Yellow gui=bo windo call HighlightQuery() function! MeasureWrap() - let &l:numberwidth = max([4, strlen(g:rows) + 1]) + let &l:numberwidth = max([4, strlen(w:rows) + 1]) let info = getwininfo(win_getid())[0] let w:columns = max([1, info.width - info.textoff]) let w:cells = map(copy(b:source_lines), "strdisplaywidth(v:val)") - let w:cells += repeat([0], g:rows - len(w:cells)) + let w:cells += repeat([0], w:rows - len(w:cells)) let w:continuations = map(copy(w:cells), "(max([1, v:val]) - 1) / w:columns") endfunction function! SetViewLines(lines) @@ -53,10 +51,11 @@ function! SetViewLines(lines) endfunction function! PadWrap() let other = getwinvar(3 - winnr(), "continuations") - let lines = b:source_lines + repeat([""], g:rows - len(b:source_lines)) + let lines = b:source_lines + repeat([""], w:rows - len(b:source_lines)) for i in range(len(lines)) - if other[i] > w:continuations[i] - let lines[i] .= repeat(" ", other[i] * w:columns + 1 - w:cells[i]) + let peer = i + w:peer_offset + if peer >= 0 && peer < len(other) && other[peer] > w:continuations[i] + let lines[i] .= repeat(" ", other[peer] * w:columns + 1 - w:cells[i]) endif endfor call SetViewLines(lines) @@ -74,7 +73,10 @@ wincmd t function! MirrorView() let other = winnr() == 1 ? 2 : 1 - call win_execute(win_getid(other), "call winrestview(" . string(winsaveview()) . ")") + let view = winsaveview() + let view.lnum = max([1, view.lnum + w:peer_offset]) + let view.topline = max([1, view.topline + w:peer_offset]) + call win_execute(win_getid(other), "call winrestview(" . string(view) . ")") endfunction function! SetScrollMode(linked) let g:linked_scroll = a:linked @@ -89,7 +91,20 @@ function! SetScrollMode(linked) endfor endif endfunction -call SetScrollMode(1) +function! OpenComparison(source, target) + let source = min([a:source, len(b:source_lines)]) + let target = min([a:target, len(getbufvar(winbufnr(2), "source_lines"))]) + let offset = a:target == a:source ? 0 : target - source + for pane in [1, 2] + let delta = pane == 1 ? offset : -offset + let own = len(getbufvar(winbufnr(pane), "source_lines")) + let peer = len(getbufvar(winbufnr(3 - pane), "source_lines")) + call setwinvar(pane, "peer_offset", delta) + call setwinvar(pane, "rows", max([own, peer - delta])) + endfor + execute "normal! " . source . "Gzz" + call SetScrollMode(1) +endfunction autocmd VimEnter,CursorMoved,WinScrolled * if g:linked_scroll | call MirrorView() | endif autocmd VimResized * if g:linked_scroll | call AlignWrap() | call MirrorView() | endif diff --git a/internal/editor/editor.go b/internal/editor/editor.go index 5a55e2d..1c962d9 100644 --- a/internal/editor/editor.go +++ b/internal/editor/editor.go @@ -4,6 +4,7 @@ package editor import ( _ "embed" "errors" + "fmt" "os" "os/exec" "path/filepath" @@ -58,7 +59,7 @@ func Edit(path string, line int) error { //go:embed compare.vim var comparison string -func Compare(root, origin, target string, line int) error { +func Compare(root, origin, target string, sourceLine, targetLine int) error { script, err := os.CreateTemp("", "tgrep-*.vim") if err != nil { return err @@ -74,7 +75,7 @@ func Compare(root, origin, target string, line int) error { } cmd := exec.Command("vim", "-u", "NONE", "-i", "NONE", "-n", "-m", "-O", "--cmd", "set nocompatible nomodeline ttimeout ttimeoutlen=80 shortmess+=F", - "-S", script.Name(), "-c", "normal! "+strconv.Itoa(line)+"Gzz", "--", origin, target) + "-S", script.Name(), "-c", fmt.Sprintf("call OpenComparison(%d, %d)", sourceLine, targetLine), "--", origin, target) cmd.Dir = root cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr return cmd.Run() diff --git a/internal/search/search.go b/internal/search/search.go index 2346c4e..ea46694 100644 --- a/internal/search/search.go +++ b/internal/search/search.go @@ -6,7 +6,8 @@ import ( "context" "os" "path/filepath" - "strings" + + "github.com/antfrog/tgrep/internal/documents" ) type Match struct { @@ -15,27 +16,6 @@ type Match struct { Text string } -// fence recognizes the same backtick fences as the Markdown search. A shorter -// fence, or one with an info string, cannot close the current block. -func fence(line string, open int) (width int, delimiter bool) { - s := strings.TrimLeft(line, " ") - if len(line)-len(s) > 3 { - return open, false - } - info := strings.TrimLeft(s, "`") - n := len(s) - len(info) - if n < 3 || strings.Contains(info, "`") { - return open, false - } - if open == 0 { - return n, true - } - if n >= open && strings.Trim(info, " \t\r") == "" { - return 0, true - } - return open, true -} - func (p *Pattern) Search(ctx context.Context, dir string, files []string, emit func(Match) error) error { for _, rel := range files { if err := ctx.Err(); err != nil { @@ -57,7 +37,7 @@ func (p *Pattern) Search(ctx context.Context, dir string, files []string, emit f raw, data, _ = bytes.Cut(data, []byte{'\n'}) line := string(raw) var delimiter bool - block, delimiter = fence(line, block) + block, delimiter = documents.BacktickFence(line, block) if block != 0 || delimiter { continue }