Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.jp.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ tgrep 'sign in'
- 別々に読みたいときは `s` を押し、左キーで原文、右キーで翻訳を選んでスクロールします。もう一度 `s` を押すと、選択中のペインの位置から連動を再開します。
- `Esc` で元の検索結果に戻ります。

連動中は両方のペインが行番号で揃います。翻訳で行を追加・削除した場合は、対応する文の位置がずれることがあります。
英語の原文と日本語訳を比較するときは、検索結果の直前にある共通のアンカーか対応する Markdown 見出しを基準に、段落の順番と段落内の行番号を合わせます。対応するアンカーや見出しがなければ、文書の先頭から数えます。原文で見つかった行が日本語の段落の長さを超える場合は、その段落の最終行を表示します。連動スクロールでは、最初に合わせた行番号の差を保ちます。

## 翻訳を直接編集する

Expand Down
2 changes: 1 addition & 1 deletion README.kr.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ tgrep 'sign in'
- 따로 읽으려면 `s`를 누르고 `←`로 원문, `→`로 번역을 선택해 스크롤합니다. `s`를 다시 누르면 선택한 패널의 위치에서 연동을 재개합니다.
- `Esc`를 누르면 같은 검색 결과로 돌아옵니다.

연동 모드에서는 두 패널이 줄 번호를 기준으로 맞춰집니다. 번역에서 줄을 추가하거나 삭제했다면 같은 문장이 다른 줄에 있을 수 있습니다.
영어 원문과 일본어 번역을 비교할 때는 검색 결과 앞에서 가장 가까운 공통 앵커나 대응하는 마크다운 제목을 찾아 문단 순서와 문단 안의 줄 번호를 맞춥니다. 기준이 될 앵커나 제목이 없으면 문서 처음부터 셉니다. 원문에서 찾은 줄이 일본어 문단의 길이를 넘으면 그 문단의 마지막 줄을 표시합니다. 연동 스크롤은 처음 맞춘 두 줄의 간격을 유지합니다.

## 바로 편집하기

Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
65 changes: 50 additions & 15 deletions cmd/tgrep/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand All @@ -121,42 +122,76 @@ 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)
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 {
t.Fatalf("comparison modified %s", lang)
}
}
}

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"})
}
6 changes: 5 additions & 1 deletion internal/cli/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
148 changes: 148 additions & 0 deletions internal/documents/alignment.go
Original file line number Diff line number Diff line change
@@ -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)
}
54 changes: 54 additions & 0 deletions internal/documents/alignment_test.go
Original file line number Diff line number Diff line change
@@ -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", "<a name='one'></a>\nextra\n\nparagraph\n<a id=\"two\"></a>\nhit", "<a id='one'></a>\n一\n<a name='two'></a>\n二", 6, 4},
{"shared section marker", "first\n\nextra\n<!-- body -->\nmatched", "<!-- body -->\n該当行", 5, 2},
{"untranslated section marker", "---\ntitle: Pods\n---\n\n<!-- overview -->\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)
}
}
}
Loading
Loading