3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

.vimrcでfor文を使ってDRYに書く

Last updated at Posted at 2020-02-15

はじめに

  • vimrcでfor文をうまく使う方法が調べてもすぐにでてこなかったのでまとめました。
  • 筆者は駆け出しのVimmerですので、よりよい方法等ございましたらご指摘いただけますと幸いです。

本記事の対象者

  • Vimmer
  • .vimrc(or init.vim)の書き方がある程度わかるひと(noremapがわかる人であれば読めます)

先に結論

ciwとかのiを省略できるようにしたいとき、(もとのcw機能はceで代用できる)

for文を使わないと…
nnoremap cw ciw
nnoremap vw viw
nnoremap dw diw
nnoremap yw yiw
nnoremap c" ci"
nnoremap v" vi"
nnoremap d" di"
nnoremap y" yi"
nnoremap c' ci'
nnoremap v' vi'
nnoremap d' di'
nnoremap y' yi'
nnoremap c( ci(
nnoremap v( vi(
nnoremap d( di(
nnoremap y( yi(
" (以下略)
for文を使うと
for each_surround in ['w', 't', '"', "'", '(', '{', "`"]
  for each_command in ['c', 'd', 'v', 'y']
    execute 'nnoremap ' . each_command . each_surround . ' ' . each_command . 'i' . each_surround
  endfor
endfor

解説

vimscriptでのfor文の使い方

最近の言語と同じ感覚で使うことができます。

簡単な例
for i in [1, 2, 3]
  echo i
endfor
結果
1
2
3

文字列と変数を連結

.で連結することができます。

簡単な例
let editor = 'Vim'
echo 'Hello, ' . editor . '!'
結果
Hello, Vim!
```

## 文字列をコマンドとして実行
`execute`を使います

```vim:簡単な例
let message = 'I use Vim.'
execute 'echo message'
```
```shell:結果
I use Vim.
```

# 最後に
`vimrc`の行数が多い ≒ vimの熟練度が高い
という風潮がある気がします。今回の記事を実践すると、行数が減ってしまうじゃないか! とお怒りになる方もいるかもしれません。それでも、DRYに書いて行数が減らせることによって、

- 見やすい
- 変更を加えたいときに少ない修正箇所で済む

という確かなメリットがあると考えています


3
3
0

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
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?