From 9d618380ed1d0b9fe3bff9d9a8f0d6b29fe6ccc6 Mon Sep 17 00:00:00 2001 From: Attacktive Date: Mon, 23 May 2022 14:09:54 +0900 Subject: [PATCH] Implement 'command minus n'. --- src/utils/history.ts | 30 +++++++++++++++++++++++++----- 1 file changed, 25 insertions(+), 5 deletions(-) diff --git a/src/utils/history.ts b/src/utils/history.ts index bc126a7..57bee13 100644 --- a/src/utils/history.ts +++ b/src/utils/history.ts @@ -26,14 +26,29 @@ export function push(command: string): History { export function getCommandIfHistoryExpansion(input): string { let command = undefined; - const regExpExecArray = /!(?:(\d+)|!)/.exec(input); + const regExpExecArray = /!(-?)(?:(\d+)|!)/.exec(input); if (regExpExecArray) { - const index = regExpExecArray[1]; - if (index === '!') { + const isMinus = + Boolean(regExpExecArray[1]) && regExpExecArray[1].length > 0; + + /** + * either digits or '!' + */ + const n = regExpExecArray[2]; + const index = parseInt(n); + if (Number.isNaN(index)) { command = getLast(); } else { - // parseInt here is guaranteed to succeed I suppose. - command = get(parseInt(index)); + /** + * !0, !-0 are invalid + */ + if (index > 0) { + if (isMinus) { + command = getMinus(index); + } else { + command = get(index); + } + } } } @@ -44,6 +59,11 @@ function get(index: number): string { return history[index]; } +function getMinus(index: number): string { + // '!!' is a synonym for '!-1' so + 1 + return history[historyIndex - index + 1]; +} + function getLast(): string { return history[historyIndex]; }