LoginSignup
1
1

More than 3 years have passed since last update.

fzf.vimでtagsを検索しながら色付きのpreviewを表示する

Posted at

PHPでせめて定義元ぐらいは辿りたいんだけど、Language Serverが使えない、phpcdも使えない、けれど絶対Vim使うってときに、ctagsを使うことにした。他のプラグインとかで何とかなるかもしれないけど、何とかなるって情報が見つけられなかった。

仕方なくctagsでタグを作ってfzf.vimでpreviewを表示させながら選びたい。

どういうことか

こういうファイルがあって、test2()を辿りたい。

caller.php
<?php

require_once './functions.php';
test2();
functions.php
<?php

function test1()
{
    echo __FUNCTION__;
}


function test2()
{
    echo __FUNCTION__;
}

function test3()
{
    echo __FUNCTION__;
}

どうするか

ひとまずctagsでtagsファイルを作っておく。

$ ls
caller.php  functions.php
$ ctags -R # 作る
$ ls
caller.php  functions.php  tags # tagsができあがる
$ cat tags # tagsの中身
!_TAG_FILE_FORMAT   2   /extended format; --format=1 will not append ;" to lines/
!_TAG_FILE_SORTED   1   /0=unsorted, 1=sorted, 2=foldcase/
!_TAG_PROGRAM_AUTHOR    Darren Hiebert  /dhiebert@users.sourceforge.net/
!_TAG_PROGRAM_NAME  Exuberant Ctags //
!_TAG_PROGRAM_URL   http://ctags.sourceforge.net    /official site/
!_TAG_PROGRAM_VERSION   5.8 //
test1   functions.php   /^function test1()$/;"  f
test2   functions.php   /^function test2()$/;"  f
test3   functions.php   /^function test3()$/;"  f

設定

fzf.vimはpreviewを外部から受け取れる。今回はshellScriptを一つ作って、previewに渡す。

/path/to/ctags_preview.sh
#!/usr/bin/env zsh

NAME=$1
FILE=$2

 #タブに囲まれた3つめの検索パターンの抽出
 #/^ any $/;" を ^ any $ に置換
PATTERN=$(echo $3 | cut -f 3 | sed "s/^\///" | sed -E "s/\/;\".*$//" | sed "s/\"/\\\\\"/g")

# 前5行、後5行を表示、-48でgrepしてるのは検索文字列に色をつけるため
grep -B 5 -A 42 --color=never "${PATTERN}" $FILE | grep -48 --color=always $NAME

で、~/.vimrcに以下を書き込む。

~/.vimrcか他のconfig
command! -bang Tags
  \ call fzf#vim#tags(expand('<cword>'), {
  \     'options': '+i
  \                 --exact
  \                 --with-nth 1
  \                 --reverse
  \                 --no-unicode
  \                 --preview "/path/to/ctags_preview.sh {1} {2} {}"
  \                     '
  \ })

nnoremap <silent> <Leader>ft :<C-u>Tags<CR>

こうなる

caller.phpのtest2の上で、ftを押すと、下記のようなプレビューが表示される。(floating windowにしてある)

スクリーンショット 2020-04-09 1.10.38.png

まぁ……全然完全ではないんだけど……。

1
1
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1