Smile Engineering Blog

ジェイエスピーからTipsや技術特集、プロジェクト物語を発信します

ChangeLog の日付間の移動を速やかに

Vim では ]][[ 入力で関数(セクション)単位にカーソル移動できるコマンドがあります。[[ だと一つ前の関数に移動、]] だと一つ後ろの関数に移動、といった具合です。

自分は日記を ChangeLog 形式で書いていて、ChangeLog でもこの動作ができたら良いな、と常々思ってました。ただ Vim script はなんだか敷居が高そう。ということで近ごろ話題の ChatGPT に作ってもらうことにしました。

出来上がったスクリプトがこちら。

" This script allows you to move a date in a Changelog-style text format.

" Define a function to move the date.
function! MoveDate(direction)
  " Search for the line containing the date.
  if search('^\d\{4}-\d\{2}-\d\{2}', a:direction) == 0
    echo "No date found"
    return
  endif

  " Save the line containing the date.
  let date_line = getline(".")

  " Extract the date from the line.
  let date = matchstr(date_line, '\d\{4}-\d\{2}-\d\{2}')

  " Delete the line containing the date.
  delete_line

  " Insert the date into the new location.
  if a:direction == 'above'
    call append(line(".") - 1, date_line)
  elseif a:direction == 'below'
    call append(line(".") + 1, date_line)
  endif
endfunction

" Map the 'gD' key to move the date above the current line.
nnoremap <silent> gDa :call MoveDate('above')<CR>

" Map the 'gD' key to move the date below the current line.
nnoremap <silent> gDb :call MoveDate('below')<CR>

ご丁寧に解説付きです。

が、違う!そうじゃない!

書いていただいたスクリプトは「日付(の行)を簡単に(一つ上の行、もしくは下の行に)移動できる」ものですね。移動するのは「日付(の行)」。自分が欲しかったのは、移動するのは「カーソル」です。「日付間のカーソル移動を簡単に~」とお願いすれば良かったのかもしれません。日本語で聞いたのに英語で応えてくるあたりに、若干のイラ立ちを感じます。コミュニケーションって大事。

そんなわけで自分で書きました。こちらです。

function! s:jump(d) abort
    let l:i = 0
    while i < v:count1
        execute(a:d . "^\\d\\{4}")
        let l:i += 1
    endwhile
endfunction

" Remap ]] and [[ to jump betweeen days
nnoremap <buffer> <silent> ]] :<Cmd>call <SID>jump('/')<CR>
nnoremap <buffer> <silent> [[ :<Cmd>call <SID>jump('?')<CR>

これを $HOME/.vim/after/ftplugin/changelog.vim に配置すれば使えます。

やっていることは単純で、[[ 入力で行頭の数字 4 ケタ(西暦)を後方検索、]] 入力で前方検索しているだけです。数値に続いて入力すると n 日前/後に移動できます。while でループしているのはそのためです。

この機能、誰か作ってるだろうと思ってたんですけど探しても見つからない。探し方がヘタなのか、Vimmer にとっては言うに及ばず、なのか。そもそも ChangeLog 形式で日記を書く人は希少なのかもしれないですね。いつもどおり、備忘録扱いで。

参考にさせていただいたページ:

動作確認環境:

git for windows の Git Bash に付属してる Vim

:version
VIM - Vi IMproved 8.2 (2019 Dec 12, compiled Jun 23 2022 04:01:15)
Included patches: 1-5117
Compiled by <https://www.msys2.org/>