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
29 changes: 29 additions & 0 deletions autoload/skkeleton.vim
Original file line number Diff line number Diff line change
Expand Up @@ -417,6 +417,35 @@ function! s:remove_marker_henkan(completing) abort
endif
endfunction

" Put the cursor right after a kakutei which is still in the line, so that
" |skkeleton-functions-kakuteiUndo| can delete it by feeding backspaces.
" {before} is the line in front of the kakutei as it was when it happened, so
" {before} .. {kakutei} has to still be the head of the line. Anything typed
" after the kakutei is free to differ -- that is the case this is here for --
" but an edit which has displaced or rewritten the kakutei itself makes this
" give up rather than delete text it cannot account for.
" Insert mode only: the command line has no line to walk back into, and a
" terminal buffer is not ours to edit.
function! skkeleton#locate_kakutei(bufnr, lnum, before, kakutei) abort
if mode() !=# 'i' || a:bufnr != bufnr('%') || a:lnum != line('.')
return v:false
endif
let head = a:before .. a:kakutei
if strpart(getline('.'), 0, strlen(head)) !=# head
return v:false
endif
let target = strlen(head) + 1
if col('.') != target
" Note: this does not break the undo block the insert is building up, so
" the kakutei and its undo still go back with a single |u|
" (|undojoin| would not help if it did: the deletion is fed back as
" keys once |skkeleton#handle()| has returned, which is past the
" command this runs in)
call cursor(a:lnum, target)
endif
return v:true
endfunction

function! skkeleton#initialize() abort
call skkeleton#notify_async('initialize', [])
endfunction
Expand Down
17 changes: 14 additions & 3 deletions denops/skkeleton/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ type CandidateResult = {
type KakuteiType = "henkan" | "completion";

// what |skkeleton-functions-kakuteiUndo| needs to take the last kakutei back
type KakuteiResult = {
export type KakuteiResult = {
type: KakuteiType;
// the string the kakutei has inserted into the buffer
kakutei: string;
Expand All @@ -32,7 +32,8 @@ type KakuteiResult = {
bufnr: number;
lnum: number;
// the line before the cursor as it was right after the kakutei
// used to make sure that the buffer has not been changed since then
// the undo needs the confirmed string to still be there: its tail is the
// kakutei itself, and the rest is what has to still precede it
bufferText: string;
};

Expand Down Expand Up @@ -124,10 +125,14 @@ export class Context {
}

// the kakutei which can be taken back right now, if any
// Note: that the confirmed string is still in the buffer is not decided here
// the cursor may have moved on since the kakutei, and only Vim knows
// what the line looks like beyond it, so kakuteiUndo() asks before it
// deletes anything
takeBackableKakutei(): KakuteiResult | undefined {
const last = this.lastKakutei;
if (
!last || !this.#isAt(last) || this.prevInput !== last.bufferText ||
!last || !this.#isAt(last) ||
// Note: a key handled before this one within the same handling has
// written to the buffer already, which prevInput cannot know yet
// (|skkeleton#handle()| takes a list of keys)
Expand All @@ -138,6 +143,12 @@ export class Context {
return last;
}

// whether the cursor is right after the last kakutei, which is where the
// undo can delete it without moving anything
isRightAfterKakutei(last: KakuteiResult): boolean {
return this.prevInput === last.bufferText;
}

// whether Vim is still where the kakutei has happened
#isAt(at: Pick<KakuteiResult, "vimMode" | "bufnr" | "lnum">): boolean {
return this.vimMode === at.vimMode && this.bufnr === at.bufnr &&
Expand Down
42 changes: 39 additions & 3 deletions denops/skkeleton/function/common.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { modifyCandidate } from "../candidate.ts";
import { config } from "../config.ts";
import { Context } from "../context.ts";
import { Context, KakuteiResult } from "../context.ts";
import { HenkanType } from "../dictionary.ts";
import { initializeStateWithAbbrev, modeChange } from "../mode.ts";
import { graphemeLength } from "../preedit.ts";
Expand Down Expand Up @@ -107,11 +107,44 @@ export async function completionKakutei(
});
}

// put the cursor right after the confirmed string, which is where the undo
// deletes it by feeding backspaces
//
// a mis-conversion is usually noticed after typing on, so the cursor having
// moved past the kakutei must not give up on it: ask Vim to walk back to it,
// leaving whatever has been typed since then alone. Vim only moves when the
// confirmed string is still where it was written, so an edit which has rewritten
// or displaced it takes the undo out of reach instead of deleting the wrong
// text.
//
// the cursor never having left is the common case and is answered here, without
// a round-trip to Vim.
async function locateKakutei(
context: Context,
last: KakuteiResult,
): Promise<boolean> {
if (context.isRightAfterKakutei(last)) {
return true;
}
if (!context.denops) {
return false;
}
const before = last.bufferText.slice(
0,
last.bufferText.length - last.kakutei.length,
);
return await context.denops.call(
"skkeleton#locate_kakutei",
last.bufnr,
last.lnum,
before,
last.kakutei,
) as boolean;
}

// take the last kakutei back into the candidate selection state
export async function kakuteiUndo(context: Context) {
const state = context.state;
// Note: takeBackableKakutei() makes sure that the confirmed string is still
// right before the cursor: this deletes it from the buffer
const last = context.takeBackableKakutei();
if (
!last ||
Expand All @@ -121,6 +154,9 @@ export async function kakuteiUndo(context: Context) {
) {
return;
}
if (!await locateKakutei(context, last)) {
return;
}
if (config.debug) {
console.log(`kakuteiUndo: take back a ${last.type} kakutei`);
}
Expand Down
125 changes: 125 additions & 0 deletions denops/skkeleton/function/common_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,18 +52,51 @@ function stubDenops(called: unknown[][], ret: unknown = void 0): Denops {
} as unknown as Denops;
}

// a stub which answers |skkeleton#locate_kakutei()| out of the buffer, so that
// the undo can walk the cursor back the way it does in Vim
function locatingDenops(buffer: Buffer): Denops {
return {
call: (name: unknown, ...args: unknown[]) => {
if (name !== "skkeleton#locate_kakutei") {
return Promise.resolve(void 0);
}
const [, , before, kakutei] = args as [number, number, string, string];
return Promise.resolve(buffer.locate(before, kakutei));
},
cmd: () => Promise.resolve(),
} as unknown as Denops;
}

// mimics how Vim applies the output of preEdit to the buffer
class Buffer {
#segmenter = new Intl.Segmenter("ja");
#context: Context;
// the line in front of the cursor, which is what Vim reports as prevInput
text: string;
// the rest of the line: only ever filled by walking the cursor back over
// what has been typed after a kakutei
tail = "";

constructor(context: Context, text = "") {
this.#context = context;
this.text = text;
this.#context.prevInput = text;
}

// mimics |skkeleton#locate_kakutei()|: walk the cursor back to the end of the
// kakutei, leaving what has been typed after it where it is
locate(before: string, kakutei: string): boolean {
const head = before + kakutei;
const line = this.text + this.tail;
if (!line.startsWith(head)) {
return false;
}
this.text = head;
this.tail = line.slice(head.length);
this.#context.prevInput = this.text;
return true;
}

// apply the output of preEdit and update the line before the cursor
// returns the keys that have been output
flush(): string {
Expand Down Expand Up @@ -511,6 +544,61 @@ Deno.test({
},
});

Deno.test({
name: "kakutei undo leaves a rewritten kakutei alone",
async fn() {
const context = new Context();
const buffer = new Buffer(context, "これは");
context.denops = locatingDenops(buffer);
await dispatch(context, ";kanji ");
buffer.flush();
await kakutei(context);
buffer.flush();
assertEquals(buffer.text, "これは漢字");

// something has rewritten the line in front of the kakutei, so it is no
// longer where it was written and must not be deleted from there
buffer.text = "それは漢字";
context.prevInput = buffer.text;
await kakuteiUndo(context);
assertEquals(context.toString(), "");
assertEquals(buffer.flush(), "");
assertEquals(buffer.text, "それは漢字");
},
});

Deno.test({
name: "kakutei undo after typing on",
async fn() {
const context = new Context();
const buffer = new Buffer(context, "これは");
context.denops = locatingDenops(buffer);
await dispatch(context, ";kanji ");
buffer.flush();
await kakutei(context);
buffer.flush();
assertEquals(buffer.text, "これは漢字");

// a mis-conversion is noticed after typing on
await dispatch(context, "desu");
buffer.flush();
assertEquals(buffer.text, "これは漢字です");

// the cursor walks back to the kakutei and only that is deleted
await kakuteiUndo(context);
assertEquals(context.toString(), "▼漢字");
assertEquals(buffer.flush(), "\b\b▼漢字");
assertEquals(buffer.text, "これは▼漢字");
assertEquals(buffer.tail, "です");

// picking another candidate rewrites the kakutei in place
await dispatch(context, " ");
await kakutei(context);
buffer.flush();
assertEquals(buffer.text + buffer.tail, "これは感じです");
},
});

test({
mode: "nvim", // can input mode test only in nvim
name: "kakutei undo in a buffer",
Expand Down Expand Up @@ -575,6 +663,43 @@ test({
},
});

test({
mode: "nvim", // can input mode test only in nvim
name: "kakutei undo in a buffer after typing on",
async fn(denops: Denops) {
const l = await currentLibrary.get();
await l.registerHenkanResult("okurinasi", "てすと", "手酢戸");
await l.registerHenkanResult("okurinasi", "てすと", "テスト");
await denops.cmd(
'call skkeleton#register_keymap("input", "<C-u>", "kakuteiUndo")',
);
await denops.cmd("startinsert");

for (const key of ["T", "e", "s", "u", "t", "o", " ", "<nl>"]) {
await denops.cmd(`call skkeleton#handle("handleKey", {"key": "${key}"})`);
}
assertEquals(await fn.getline(denops, "."), "テスト");

// the wrong candidate goes unnoticed until the rest has been typed, which
// no longer has to be deleted before taking the kakutei back
for (const key of ["s", "u", "r", "u"]) {
await denops.cmd(`call skkeleton#handle("handleKey", {"key": "${key}"})`);
}
assertEquals(await fn.getline(denops, "."), "テストする");

// the cursor walks back over what has been typed, and only the kakutei is
// replaced by the henkan state
await denops.cmd('call skkeleton#handle("handleKey", {"key": "<c-u>"})');
assertEquals(currentContext.get().toString(), "▼テスト");
assertEquals(await fn.getline(denops, "."), "▼テストする");

// picking another candidate rewrites the kakutei in place
await denops.cmd('call skkeleton#handle("handleKey", {"key": "<space>"})');
await denops.cmd('call skkeleton#handle("handleKey", {"key": "<nl>"})');
assertEquals(await fn.getline(denops, "."), "手酢戸する");
},
});

test({
mode: "nvim", // can input mode test only in nvim
name: "kakutei undo in a buffer after a kakutei by typing on",
Expand Down
9 changes: 6 additions & 3 deletions doc/skkeleton-functions.jax
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,12 @@ kakuteiUndo *skkeleton-functions-kakuteiUndo*
|skkeleton-completion| による確定も取り消せます。この場合は補完した
候補の見出しに対する変換となり、確定した候補が選択された状態から
始まります。
確定した文字列が、確定した場所でカーソルの直前に残っている場合のみ
動作します。続けて入力した文字を消してカーソルが戻った場合も動作
しますが、別の行やバッファに移った後は何もしません。
確定した文字列が、確定した場所に残っている場合のみ動作します。続けて
入力した後でもカーソルを戻して動作しますが、確定した文字列自体が書き
換えられたり位置がずれたりした場合と、別の行やバッファに移った後は何
もしません。
カーソルを戻すのは挿入モードのみです。コマンドラインモードと端末モー
ドでは、従来どおりカーソルの直前に残っている場合のみ動作します。
|skkeleton-function-purgeCandidate| で候補を削除した後と、辞書登録
による確定も取り消せません。skkeletonを無効化した場合も忘れます。
ユーザー辞書への学習は取り消されません。
Expand Down
Loading