当前位置:网站首页>Configuring vim(7) from scratch - autocommands

Configuring vim(7) from scratch - autocommands

2022-08-10 23:16:00 Masimaro

This article we have to talk aboutvimA very important thing——自动命令.

从编程的角度来看,Automatic command is a bit similar to the incident response,Or the callback function.When external some events,Automatically defined a set of commands in advance.

Define an automatic command format is as follows

autocmd type pattern cmd
  • autocmd: Automatic command to autocmd 关键字开始,它的作用类似与 js Defined in the function of function 关键字
  • type: Trigger the command event type
  • pattern: 事件的过滤,According to different event types have different meanings
  • cmd : 将要执行的命令

说了这么多,我们以一个例子来说明: 当我们使用 vim 打开一个不存在的文件,如果直接退出,We will find that it has not been saved.Because when you open a non-existent file vim Not really in the disk to create such a file,It just opened a new buffer,When the write command only really will create a file.我们使用 q! 退出的话,It is not written to the file

We try to modify this behavior,Open a new file is created,Is opening a new file is executed when the write operation.Open new file events using BufNewFile 来表示.Here we do not limit the file format,因此 pattern This is used * 来表示,执行的命令是 :w 来写入.

:autocmd BufNewFile * w

Automatic command event type

Command can automatically monitor the event types are mainly the following

  • Start editing a current file does not exist,Also is a situation we described above.这种情况使用 BufNewFile 来表示
  • Start editing an existing file.这种情况使用 BufReadPre 或者 BufReadPost 来表示.They said the file content is loaded before and after being loaded
  • Change a buffer filetype 选项的时候,它与 vim The file type used.这种情况使用 FileType 来表示
  • The file is written back to disk.这种情况用 BufWritePreBufWritePost.Their meanings and the above BufReadPreBufReadPost 类似.
  • Entry and exit insert mode,Into insert mode is used when InsertEnter,Exit insert mode is used when InsertLevel.
  • Vim After complete start all initialization can use VimEnter 来表示
  • Input can make the vim 退出的命令,可以使用 ExitPre 来表示.如果输入 :quit ,When deciding whether to quit before,可以使用 QuitPre.

这些只是 vim A small part of the big event,Want to learn about other events,可以使用 :help autocmd-events

同时绑定多个事件

We can bind multiple events at the same time,Use a comma between events as segmentation can be,For example, we want to be in writing or loadingHTMLFile for automatic layout before,You can use the following code

:autocmd BufReadPost,BufWritePre *.html normal gg=G

Automatic command in the event it is triggered when the,执行命令.Is equivalent to our manual input command in command mode.Have introduced said command mode in before,In command mode, using the normal mode of operation can be used normal.ggSaid moves the cursor to the first line,=GSaid last line from current cursor to perform the operation of the automatic layout.

我们在 html 文件中输入

<html>
<body>
    <div>
<div>
        <p>hello!</p>
</div>
    </div>
</body>
</html>

执行 :wAfter we found it automatically layout.或者我们也可以使用 :editOpen a typesetting messHTML文件,会发现vimAutomatic layout for it.

Or we will take an example,Before we set the function word wrap,Because in general programming language,One line of code to write too long is not a good habit.但是像 markdown 或者 html The markup language used to write document,Hard to avoid can appear a long text,At this time to set up automatic line is a little out of place,We can use the following statement for these two documents to eliminate

:autocmd BufNewFile, BufReadPost *.html setlocal nowrap

这里我们使用 BufNewFile和 BufReadPost,Because we need for the newly created and existing htmlDocuments are to enable the Settings.

FileType 事件

This type of event is our most commonly used,Through this event to cooperate setlocal Can be very convenient for different programming languages to do different Settings For example, we will cancel above HTML Word wrap do a rewrite the code,改写成使用 FileType

:autocmd FileType html setlocal nowrap

Or we can according to the different language,Define a shortcut quick add a comment

:autocmd FileType python nnoremap <buffer> <localleader>c I#<esc>
:autocmd FileType javascript nnoremap <buffer> <localleader>c I//<esc>

在输入完命令之后,我们新打开一个 js或者 python文件,就可以直接测试

We also can combine introduced before the definition of local abbreviation,According to different types of files define the abbreviation of different,例如

:autocmd FileType c iabbrev <buffer> main int main(int argc, char* argv[])
:autocmd FileType python iabbrev <buffer> main if __name__ == "__main__":

According to different language fast fillmain函数.

我们结合FileType Events and abbreviations seems to define the corresponding code snippet for different language,This is some editors also provide code snippet 的功能,Combined with the plug-in we can use vim Define a more powerful code fragment

Automatic command group

Have discussed automatic command so many things,Your friend may have mastered has even started to can't wait to add content to the configuration file.但是在 luaHow to use automatic command in the?先别着急,Automatic command related content haven't finished discussing,Introduction I sell a imprison son,We talk about it in the back to in luaAdd automatic command.

How can we temporarily do not speak in lua Add automatic command,Here we try to enable init.vim 文件.We add a line inside

autocmd BufWrite * sleep 200m

Then we save and use :source $MYVIMRC启用

If no change is.别着急,We executed many times :source $MYVIMRC.And then perform the save operation.是不是发现vim越来越慢了.这是怎么回事呢?

我们每次执行 :source $MYVIMRC 的时候,vim Don't throw away the original Settings,Will only start again read and load the new Settings,A bit like file additional.At the time of multiple loading configuration file,vim Have created multiple automatic command.Along with the increase in loading times,vim Saved more dormant automatic command.所以 vim 会变得越来越卡.

你可能会说,Who have no matter to idle has been loading the configuration file to play,And no one will write delay.But consider this scenario is like we were modified and test configuration will do.Although we don't delay,But loading configuration or load the plug-in needs to be the time,Some will also perform automatic command,If the quantity is big up,自然会影响vim的启动速度.

我们该如何处理这个问题呢?

vimGiven in the solution is to put automatic command in a user name in the group,Form a automatic command group.

使用关键字 augroup To create an automated command group.For example, we can create the following automatic command group

:augroup testgrp
:    autocmd BufWrite * echom "hello1"
:    autocmd BufWrite * echom "hello2"
:augroup END

Directly on the command line, enter the kind of thing is too much trouble,我们还是在 init.vim 中输入.Enable us then to perform the save operation then,执行 :message 命令来查看日志,Found that there are two printing

We'll revise the configuration file or at the command line input and add the following sentence

:augroup testgrp
:    autocmd BufWrite * echom "hello3"
:augroup END

我们先退出vim,再打开,And then perform the save operation,Look at the log there are several output?

The answer may be the other fellow a mystery,It will print three.Not you think it is,The group with the same cover.It also additional happens here,Will the same set of multiple commands together.Since different groups will add,So what I want it good,I wrote so many more code.别着急,我们慢慢往下看.

Group a is to separate modules,The second reason is that we can use autocmd! To clear the command before the same group. For example we amend the above command to

:augroup testgrp
:    autocmd!
:    autocmd BufWrite * echom "hello3"
:augroup END

这个时候再次测试,We find that it will only print a statement.

But if we put it in a different group of,The situation is changed again

:augroup testgrp
:    autocmd BufWrite * echom "hello1"
:    autocmd BufWrite * echom "hello2"
:augroup END

:augroup testgrp1
:    autocmd!
:    autocmd BufWrite * echom "hello3"
:augroup END

We found that after the save,It will print3条语句

autocmd! Will only to clear all the command before the same set of,And different set of commands it won't take effect.This gives us according to the module partition named convenience.

Improve the automatic loading configuration file action

Before we through binding shortcuts <leader>ssTo automatically reloads the configuration,After studied the automatic command we can further be lazy,Use of automatic command,We can do it as long as the configuration file is saved,就自动加载.

:augroup NVIMRC
:    autocmd!
:    autocmd BufWritePost init.vim source %
:augroup END

这里我们先使用 autocmd!Clean up before loading operation.In the back of the automatic command,我们使用 BufWritePostIn the configuration file is saved to disk before to perform the loading operation,Ensure that loaded into the configuration file from the disk after the modification of consistent with us.

Automatic naming in we realize vim Automatic programming of an important tool for.甚至 vim Itself has many functions rely on it to achieve,Such as file type detection.The file type testing we will discuss in the next chapter.

原网站

版权声明
本文为[Masimaro]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/222/202208102229583785.html