Vimrc где находится
Перейти к содержимому

Vimrc где находится

  • автор:

Customizing Vim

Settings like indentation and keyword-pairs can vary between different programming languages and file types. You might need to adapt style guides based on client requirements. Or perhaps, you wish to create or override commands to suit your preferences.

This chapter will discuss how you can customize Vim for different purposes. Some of the settings will be specific to GVim.

    — set your settings — make new commands — write a Vim script — using filetypes — reference manual for Options — reference manual for Key mapping, abbreviations and user-defined commands — reference manual for Automatic commands

Editing vimrc

The Vim script language is used for the startup vimrc file, syntax files, and many other things.

The vimrc file can contain all the commands that you type after a colon. The simplest ones are for setting options.

  • :e $MYVIMRC if you already have a vimrc file, you can use this predefined variable to open it to find out where the vimrc file should be located for your OS
  • :source $MYVIMRC apply changes from within your current Vim session

To view a sample vimrc file, I have one on GitHub. More resources are mentioned in the Further Reading section at the end of this chapter.

defaults.vim

  • source $VIMRUNTIME/defaults.vim add this to your vimrc file if you want to keep these defaults describes the settings provided by defaults.vim

Alternatively, you can copy only the parts you want to retain from the defaults.vim file to your vimrc file.

General Settings

set syntax and guidelines were introduced in the Setting options section.

  • set history=200 increase default history from 50 to 200
    • as mentioned in the Command-line mode chapter, there are separate history lists for : commands, search patterns, etc
    • you can use :colorscheme followed by a space and then press Tab or Ctrl + d to get a list of the available color schemes
    • first tab will complete as much as possible
    • second tab will provide a list
    • third and subsequent tabs will cycle through the completion options

    :h ‘history’ will give you the documentation for the given option (note the use of single quotes).

    You can use these settings from the Command-line mode as well, but will be active for the current Vim session only. Settings specified in the vimrc file will be loaded automatically at startup. You can also load a different file as the vimrc , which will be discussed in the CLI options chapter.

    Further Reading

    Text and Indent Settings

    • filetype plugin indent on enables loading of plugin and indent files
      • these files become active based on the type of the file to influence syntax highlighting, indentation, etc
      • :echo $VIMRUNTIME gives your installation directory ( indent and plugin directories would be present in this path)
      • see :h vimrc-filetype, :h :filetype-overview and :h filetype.txt for more details
      • useful for files not affected by indent setting
      • see also :h smartindent
      • white space is used to break lines, so a line can still be greater than the limit if there’s no white space
      • default is 0 which disables this setting
      • use highlight ColorColumn setting to customize the color for this vertical bar
      • see vi.stackexchange: Keeping lines to less than 80 characters for more details

      Search Settings

      • set hlsearch highlight all matching portions
        • using :noh (short for :nohlsearch ) will clear the current highlighted portions
        • pressing Enter key would move the cursor to the matched portion
        • pressing Esc key would keep the cursor at the current location
        • other matching terms will be highlighted based on hlsearch setting

        Custom mapping

        • nnoremap Normal mode non-nested, non-recursive mapping
        • xnoremap Visual mode non-nested, non-recursive mapping
        • inoremap Insert mode non-nested, non-recursive mapping
        • inoreabbrev Insert mode non-nested, non-recursive abbreviation
        • nmap , xmap , imap and iabbrev allows nested and recursive mappings
        • nunmap , xunmap , iunmap and iunabbrev unmaps the given command (usually used from Command-line mode to temporarily disable a mapping, will be available again on startup if it was defined in vimrc )
          • use mapclear instead of unmap to clear all the mappings for that particular mode

          :nmap , :xmap , :imap and :iab will list all the current mappings for that particular mode. You can provide an argument to display the mapping for that particular command, for example :nmap Y . See :h key-mapping and :h map-overview for reference manuals.

          Normal mode

          • nnoremap &LTF2> :w&LTCR> press F2 function key to save changes
            • &LTF2> represents the F2 function key and &LTCR> represents the Enter key
            • I chose F2 since it is close to the Esc key ( F1 opens help page)
            • likewise, you can map the other arrow keys to do nothing as well
            • &LTsilent> modifier executes the command without displaying on Command-line
            • Note that this mapping also retains the default behavior of the Space key
            • I prefer this to make switching tabs consistent with browser and terminal shortcuts

            See :h map-which-keys to know which keys are not already Vim commands, which ones are not commonly used, etc.

            See :h key-notation for a list of keys that can be represented using the <> notation.

            Map leader

            • nnoremap &LTLeader>f gg=G if mapleader hasn’t been set, using \f will auto indent the code for the whole file
            • let mapleader = «;» change the leader key to ;
              • nnoremap &LTLeader>f gg=G this will now require ;f since the leader key was changed

              Insert mode

              • inoremap &LTF2> &LTC-o>:w&LTCR> press F2 to save changes in Insert mode as well
                • Ctrl + o to execute a command and return back to Insert mode automatically
                • imap &LTF2> &LTC-o>&LTF2> can also be used if you’ve already defined the Normal mode mapping
                • I’d prefer Ctrl + e but that is useful to cancel autocompletion
                • If you need Ctrl + v functionality, the Ctrl + q alias can be used to insert characters like Enter key (but this alias may not work in some terminals)
                • See :h i_CTRL-x and :h ins-completion for all the features offered by Ctrl + x

                Use noremap! if you want a mapping to work in both Insert and Command-line modes.

                Visual mode

                • xnoremap * y/&LTC-R>»&LTCR> press * to search the visually selected text in the forward direction
                  • recall that Ctrl + r helps you insert register contents in Command-line mode

                  Note that xnoremap is used here since vnoremap affects both Visual and Select modes.

                  Abbreviations

                  Abbreviations are usually used to correct typos and insert frequently used text. From :h abbreviations documentation:

                  An abbreviation is only recognized when you type a non-keyword character. This can also be the &LTEsc> that ends insert mode or the &LTCR> that ends a command. The non-keyword character which ends the abbreviation is inserted after the expanded abbreviation. An exception to this is the character &LTC-]> , which is used to expand an abbreviation without inserting any extra characters.

                  inoreabbrev p #!/usr/bin/env perl&LTCR>use strict;&LTCR>use warnings;&LTCR> expand p to the text as shown in the code snippet below

                  • you can trigger the abbreviation completion using non-keyword character such as Esc , Space and Enter keys, punctuation characters and so on
                  • use Ctrl + ] to expand the abbreviation without adding anything extra

                  inoreabbrev py #!/usr/bin/env python3 expand py to #!/usr/bin/env python3

                  • this might cause issues if you need py literally (for example, script.py )
                  • you can use something like [p or @p instead

                  inoreabbrev teh the automatically correct teh typo to the

                  inoreabbrev @a always @()&LTCR>begin&LTCR>end&LTEsc>2k$ expand @a to the text as shown in the code snippet below

                  • this one works best when you type @a followed by Esc key to place the cursor at the end of the first line

                  :abbreviate or :ab list all abbreviations

                  See :h 24.7 for more details about using abbreviations.

                  Matching Pairs

                  • set matchpairs+=&LT:> add <> to the list of pairs matched by % command in Normal mode

                  To match keywords like if — else pairs with % , you can install matchit.vim plugin. This supports filetypes such as HTML, Vim, LaTeX, XML, etc. See :h matchit-install for more details.

                  GUI options

                  • set guioptions-=m remove menu bar
                  • set guioptions-=T remove tool bar

                  Third-party customizations

                  See :h ‘runtimepath’ to know the path within which you can add the plugins and packages discussed in this section.

                  /.vim is commonly used on Unix/Linux systems.

                  Make sure to backup your directory (

                  /.vim for example) and the vimrc file, so that you can easily apply your customizations on a new machine.

                  plugin

                  Some plugins are loaded by default. Some come with Vim installation but you have to explicitly enable them. You can also write your own or add plugins written by others. From :h add-plugin:

                  • global plugin: Used for all kinds of files

                  • filetype plugin: Only used for a specific type of file

                  If you want to add a global plugin created by you or someone else, place it in the plugin directory. If you don’t have that directory yet, you can create it using the below command (assuming Unix/Linux):

                  If you have multiple related plugin files, you can put them under a subdirectory:

                  If you want to add plugins that should work based on specific filetype, add them to the ftplugin directory:

                  package

                  Packages make it easy to manage projects that require multiple plugins, use a version controlled repository directly and so on. See :h packages for more details. From :h add-package:

                  A package is a set of files that you can add to Vim. There are two kinds of packages: optional and automatically loaded on startup.

                  The Vim distribution comes with a few packages that you can optionally use. For example, the matchit plugin.

                  • packadd! matchit enable matchit package
                    • this plugin comes with Vim, see :h matchit for further details
                    • ! is used to prevent loading this plugin when Vim is started with —noplugin CLI option

                    vim-surround is used here as an example for a third-party package. Installation instructions (provided in this repository) are shown below, assuming you want to enable this package at startup:

                    • ysiw] will surround a word with [] , for example hello to [hello]
                    • cs»‘ will change text surrounded by double quotes to single quotes, for example «hi bye» to ‘hi bye’
                    • :packadd vim-surround enable this package from Command-line mode
                    • packadd! vim-surround enable this package in vimrc (usually under some condition)

                    color scheme

                    There are different ways to add a new color scheme. The simplest is to copy the theme.vim file to the

                    /.vim/colors directory. Or, follow the installation steps provided by the theme creators. Here are couple of solarized themes you can check out:

                    After installation, you can use the :colorscheme command to set the new theme. If the theme offers multiple variations, you might need additional settings like set background=dark or set background=light . See the installation instructions provided in the above repositories for more details.

                    See Where to put what section under :h packages for more details about installation directories.

                    autocmd

                    An autocommand is a command that is executed automatically in response to some event, such as a file being read or written or a buffer change.

                    Autocommands are very powerful. Use them with care and they will help you avoid typing many commands. Use them carelessly and they will cause a lot of trouble.

                    Где отредактировать конфигурацию vim?

                    bobrovskyserg

                    / — это ваша домашняя директория?
                    Нет, вы шутите, я вам не верю!

                    • Facebook
                    • Вконтакте
                    • Twitter

                    bobrovskyserg

                    bobrovskyserg

                    nathanael

                    /.vimrc и поехали.

                    ntzch: С какой стати при установке в систему должен создаваться какой-либо файл в каталоге пользователя?

                    Для тех пакетов, у которых имеется файл настроек по умолчанию, тот получает прописку в /etc, иногда в другом каталоге, но никак не в домашнем каталоге какого-либо пользователя. Последнее может произойти только в случае установки ПО не штатными средствами дистрибутива (через пакетный менеджер), а в пользовательский каталог.

                    Where Are .vimrc and vimrc Files?

                    Vim is a popular command-line text editor that provides a lot of advanced features. These features can be configured in different ways from the Vim interface or command line or configuration files named .vimrc and vimrc .

                    Vim Configuration Files

                    Vim basically provides 2 configuration files. The first configuration file is named .vimrc and used for the current user specifically. The second configuration file is named vimrc and applied for all users in the system.

                    Global (System-wide) Vim Configuration File – vimrc

                    The global or system-wide vim configuration file is generally located under the /etc/vim/vimrc . This configuration file is applied to all users and when Vim is started this configuration file is read and Vim is configured according to this file contents. This configuration file contains some basic configurations like enabling syntax highlighting on background color etc by default.

                    Global (System-wide) Vim Configuration File – vimrc

                    User Vim Configuration File – .vimrc

                    The second configuration file is named .vimrc and located under every user home directory like

                    /.vimrc . This configuration is applied for the current user only and other users are not affected. This configuration file is also applied after the global configuration file is applied in order to preserve and apply user-specific configuration different from the system-wide configuration. In some cases, this configuration file may not be created by default. You can create the

                    /.vimrc file like below.

                    Alternatively, following path specifications can be used for .vimrc configuration file in Linux.

                    Vim is a cross-platform tool that can be also installed on other operating systems like Windows. If you are using the Windows operating system the .vimrc is located under the user’s home directory with the name of _vimrc .

                    Настройка Vim

                    Vim — это очень сложный, но в то же время очень популярный текстовый редактор текста среди пользователей операционных систем Linux. Программа позволяет перемещаться по тексту и выполнять большинство действий с помощью клавиатуры, это очень сильно ускоряет работу за компьютером, поэтому что вам не надо постоянно переносить руку на мышь и обратно.

                    В нескольких предыдущих статьях я рассказывал про основы работы с Vim и основные команды программы, сегодня же хочу поговорить о настройке и персонализации программы. Добавление нескольких строчек в конфигурационный файл может сделать Vim намного удобнее. Несмотря на то, что в тексте я буду писать Vi, речь будет идти про современную версию редактора — Vim.

                    Настройка редактора Vim

                    Основной конфигурационный файл Vim находится в папке /etc/. Это файл /etc/vimrc/vimrc. Коме того, для каждого отдельного пользователя можно настроить Vi с помощью локального конфигурационного файла, который находится в домашней папке

                    /.vimrc. Вы можете использовать тот файл, который вам надо, например:

                    Я рекомендую комментировать если не каждую строчку, то хотя бы каждую секцию, потому что если вы этого не будете делать, то потом не разберетесь что и зачем добавляли. Для комментария добавьте перед строкой символ кавычки — «.

                    1. Отступы и нумерация строк

                    Если вы собрались программировать в Vi, то вам надо обязательно разобраться с отступами. В стандартах многих языков программирования рекомендуется использовать пробелы вместо табов, а каждый отступ оформлять фиксированным количеством пробелов, например, стандарт Python PEP-8 рекомендует использовать четыре пробела. Чтобы это настроить добавьте такие строки:

                    set expandtab
                    set smarttab
                    set tabstop=4
                    set softtabstop=4
                    set shiftwidth=4

                    Переменная expandtab включает замену табов на пробелы, tabstop — количество пробелов в одном обычном табе, softtabstop — количество пробелов в табе при удалении, smarttab — при нажатии таба в начале строки добавляет количество пробелов равное shiftwidth.

                    Чтобы добавить нумерацию строк добавьте такую команду:

                    Раз мы уже заговорили про отступы, давайте сделаем ещё небольшой отступ между левой частью окна:

                    2. Внешний вид

                    Для редактора доступно несколько цветовых схем. Вы можете посмотреть все доступные схемы открыв редактор и набрав там команду :colorscheme, затем пробел, а затем Tab:

                    Для выбора цветовой схемы на постоянной основе добавьте в конфигурационный файл такую строчку

                    colorscheme имя_цветовой_схемы

                    Для многих языков программирования есть подсветка синтаксиса, чтобы её включить добавьте:

                    3. Звук

                    При нажатии неверной клавиши или ошибке в Vim проигрывается специальный звук. Если он вам мешает, его можно отключить:

                    set noerrorbells
                    set novisualbell

                    4. Поддержка мыши

                    Если вы работаете в графическом окружении, то, возможно, вам понадобиться поддержка мышки. Поддержка может быть добавлена в несколько режимов работы программы:

                    • n — обычный режим;
                    • v — визуальный режим (режим выделения);
                    • i — режим вставки;
                    • c — режим командой строки;
                    • a — все перечисленные ранее режимы;
                    • r — для режима «Нажмите Enter» или запроса ввода информации.

                    В большинстве случаев чтобы включить мышку во всех режимах программы достаточно добавить такую строчку:

                    Также можно включить мышку только в визуальном режиме:

                    Или вовсе её отключить:

                    При включённой поддержке мыши, вы все ещё можете копировать текст в системный буфер обмена, для этого просто зажмите клавишу Shift.

                    5. Настройка привязок

                    Очень полезная возможность Vim — это настройка своих привязок клавиш. Для этого существует функция map. Она похожа на alias в Linux и сообщает программе, что если мы вводим что-то, то хотим сделать ещё что-то. Здесь прежде чем переходить к настройке нужно понять как это работает. Синтаксис map простой:

                    map набор_символов_или_сочетание_клавиш на_что_заменить

                    Откройте редактор и выполните там команду:

                    :map losst <ESC>iHello world!<CR>

                    При вводе набора символов losst программа нажимает клавишу Esc, затем вводит i чтобы перейти в режим редактирования, потом пишет приветствие и добавляет символ перевода строки. Клавиши, которые надо нажать пишутся в скобках <>.

                    Мы рассмотрели общую команду map, но существуют также отдельные команды для других режимов:

                    • nmap — нормальный режим;
                    • vmap — визуальный режим;
                    • omap — режим, когда выбран оператор действия (y,p или d);
                    • cmap — режим командной строки;
                    • imap — режим вставки.

                    Кроме того есть не рекурсивный вариант команды. Например, если на слово Hello назначить ещё одну замену, то в нашем примере она сработает. Но в не рекурсивном варианте всё равно будет вставлено Hello. Не рекурсивные варианты команды тоже есть для всех режимов, это noremap, vnoremap, nnoremap, onoremap, cnoremap и inoremap.

                    Но это ещё не всё. В начале пользовательских привязок клавиш принято использовать клавишу <leader> по умолчанию это обратный слеш. Например, если сделать вот так:

                    :map <leader>losst <ESC>iHello world!<CR>

                    Тогда для выполнения этой привязки надо набрать \losst. Использовать обратный слеш не всегда удобно, поэтому часто его заменяют на запятую. Для этого в конфигурационный файл надо добавить:

                    Теперь вы знаете как настроить привязки клавиш в vim и что это всё означает. Теперь можно добавить сочетание клавиш для быстрого сохранения:

                    Поиск дальше нажатием пробела:

                    Поиск предыдущего вхождения по нажатию Ctrl+Пробел:

                    Более удобное перемещение между открытыми вкладками редактора:

                    Включение или отключение проверки орфографии:

                    map <leader>ss :setlocal spell!<CR>

                    Таким образом, вы можете сделать более удобным и быстрым любое действие в редакторе.

                    6. Буфер обмена

                    Vim использует специальный внутренний буфер обмена для копирования и вставки текста, он никак не связан с системным. Постоянная проблема пользователей Vim в графическом интерфейсе, это невозможность что-либо скопировать непосредственно из визуального режима Vim в системный буфер обмена. Если окно редактора пусто, нет никаких дополнительных настроек или плагинов, можно просто копировать текст из терминала, но если запустить vim в tmux или screen, то тут уже возникнет проблема. Она решается. В Vim существуют специальные регистры для системного буфера обмена, это + и *. К ним можно получить доступ с помощью клавиши «.

                    Но сначала надо убедится, что ваша версия Vim поддерживает работу с системным буфером обмена. Для этого выполните:

                    vim —version | grep clipboard

                    Если вы видите надпись +clipboard, значит всё хорошо. В противном случае надо искать другую версию vim. В Ubuntu или Debian для поддержки буфера обмена можно установить пакет vim-gtk:

                    sudo apt install vim-gtk

                    Теперь, когда вы нажмете «+y в визуальном режиме, выделенный текст будет скопирован в системный буфер обмена, а при нажатии «+p в обычном режиме, содержимое буфера обмена будет вставлено в позицию курсора. Для большего удобства можно добавить горячие клавиши:

                    Теперь чтобы вставить из буфера vim будет достаточно нажать Ctrl+V, а для копирования в буфер обмена системы — Ctrl+C.

                    7. Настройка поиска

                    Давайте немного настроим поиск. Для того чтобы игнорировать регистр при поиске добавьте в конфигурационный файл:

                    set ignorecase
                    set smartcase

                    Подсвечивать результаты поиска:

                    Чтобы программа подсказывала первое вхождение при вводе шаблона поиска добавьте:

                    8. Команды

                    Для сохранения, открытия нового файла в программе и выполнения многих других операций мы вводим команды. Но кроме предустановленных команд вы можете добавлять свои. Для этого используется такая конструкция:

                    command опции имя действие

                    В качестве действия может быть указано выполнение какой-либо команды, нажатие клавиш, как в случае с привязками или вызов какой-либо функции. Это очень обширная тема, поэтому я не буду трогать её в этой статье.

                    Добавьте такую строчку чтобы с помощью команды :W можно было сохранить файл, если он открыт не через sudo:

                    command! W execute ‘w !sudo tee % > /dev/null’ <bar> edit!

                    9. Плагины

                    Для Vim существует огромное количество различных плагинов и начиная с восьмой версии появилась своя система управления пакетами. Все пакеты должны располагаться в папке

                    /.vim, подпапке pack/vendor/start или pack/vendor/opt. Файлы из подпапки start загружаются автоматически при старте программы, и из opt надо подгружать вручную.

                    Например, давайте установим такой популярный плагин, как NerdTree. Для этого просто склонируйте его с GitHub в эту папку:

                    git clone https://github.com/preservim/nerdtree.git

                    После этого разработчики рекомендуют выполнить такую команду, чтобы загрузить страницы справки:

                    vim -u NONE -c «helptags

                    /.vim/pack/vendor/start/nerdtree/doc» -c q

                    После этого вы можете запустить программу и набрать такую команду для активации панели выбора файлов:

                    Можно добавить горячую клавишу на открытие панели, для этого добавьте в конфигурационный файл:

                    nmap <F6> :NERDTreeToggle<CR>

                    Установим для примера ещё один плагин, Vim , который позволяет выполнять unix команды прямо в командной строке редактора:

                    git clone https://tpope.io/vim/eunuch.git

                    vim -u NONE -c «helptags

                    /.vim/pack/vendor/start/eunuch/doc» -c q

                    Перезагрузите Vim и вы сможете пользоваться и этим плагином. Вообще, вы можете найти подробную инструкцию по установке любого нужного вам плагина на GitHub странице самого плагина.

                    10. Кодировка

                    Часто при открытии в Vim тестовых файлов с кириллическими символами, те отображаются неверно. Чтобы они отображались как надо следует выбрать кодировку UTF-8 по умолчанию:

                    Также можно установить стандарт использования символов переноса строки в файлах:

                    В данном случае на первом месте находится вариант Unix, где для переноса строки используется только символ \n.

                    Выводы

                    В этой статье я постарался детально разобрать как выполняется настройка Vim. Вы узнали о базовых переменных, которые надо установить чтобы изменить внешний вид, о привязках клавиш, а также о том как устанавливать плагины. К тому же у нас получился такой файл

                    «Табы и пробелы
                    set expandtab
                    set smarttab
                    set tabstop=4
                    set softtabstop=4
                    set shiftwidth=4
                    «Нумерация строк и отступ
                    set number
                    set foldcolumn=2
                    «Цветовая схема
                    colorscheme delek
                    syntax on
                    «Без звука
                    set noerrorbells
                    set novisualbell
                    «Мышь
                    set mouse=a
                    «Привязки
                    let mapleader = «,»
                    nmap <leader>w :w!<CR>
                    map <space> /
                    map <C-space> ?
                    map <C-j> <C-W>j
                    map <C-k> <C-W>k
                    map <C-h> <C-W>h
                    map <C-l> <C-W>l
                    map <leader>ss :setlocal spell!<CR>
                    inoremap <C-v> <ESC>»+pa
                    vnoremap <C-c> «+y
                    vnoremap <C-d> «+d
                    «Поиск
                    set ignorecase
                    set smartcase
                    set hlsearch
                    set incsearch
                    «Выход с sudo
                    command! W execute ‘w !sudo tee % > /dev/null’ <bar> edit!
                    «Кодировка
                    set encoding=utf8
                    «Тип переноса
                    set ffs=unix,dos,mac

                    Даже этот небольшой конфигурационный файл уже может сильно помочь вам в работе, а дальше останется только расширять его дополнительными командами и привязками клавиш. А какие команды и привязки используете вы? Какие плагины? Поделитесь в комментариях!

                    Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

                    Vimrc Configuration Guide — How to Customize Your Vim Code Editor with Mappings, Vimscript, Status Line, and More

                    Vimrc Configuration Guide - How to Customize Your Vim Code Editor with Mappings, Vimscript, Status Line, and More

                    Configuring your .vimrc file lets you use the full power of Vim. With a customized .vimrc file you can increase your Vim powers tenfold.

                    In this article I will show you a few ways you can customize your .vimrc file.

                    • Basic Settings
                    • Plugins
                    • Folding
                    • Vimscript
                    • Status line

                    First create the following directory structure in your home directory.

                    Create a .vimrc file in your home directory.

                    How to Update Basic Settings in Vim

                    First let’s add some basic settings that will improve your editing experience. I use double quote characters to comment out lines.

                    Add the following lines to your .vimrc file:

                    Syntax highlighting is very useful. The next line we add will enable syntax highlighting and make your code easier to read.

                    This is what it looks like before:

                    vim-no-highlighting.png

                    And after:

                    vim-highlighting.png

                    You can also choose to display line numbers to make navigating the file easier.

                    set-numbers.png

                    You can pinpoint exactly where the cursor is located by highlighting the line it is on horizontally and vertically.

                    Add these lines to enable this feature.

                    set-cursor-line-column.png

                    Here are some more common setting that enhance the editing experience.
                    Each line contains a comment above it explaining what it does.

                    Add the following lines to the .vimrc file.

                    Bash completion is a great feature which saves keystrokes by auto completing what you type. Vim has a similar feature called wildmenu.

                    Add the following lines to enable the wildmenu feature. You will see a list of files matching the file you are searching for. You can also enable auto completion to Vim.

                    Type :help <command> for more information on specific commands.

                    How to Fold Long Files in Vim

                    The .vimrc file can get long so organizing it into sections is a smart idea.
                    Vim will allow you to fold long files to hide sections of text.

                    Add the following lines to the bottom of your .vimrc to organize the file into sections.

                    Save the .vimrc file with :w and source the .vimrc file like this :source

                    /.vimrc to make the changes take effect. Now, once you move your cursor on a fold you can press:

                    zo to open a single fold under the cursor.

                    zc to close the fold under the cursor.

                    zR to open all folds.

                    zM to close all folds.

                    Type :help folding for more information.

                    How to Add Plugins to Vim

                    You can add plugins to Vim to add extra functionality. Most people use a plugin manager to make plugin installation easy.

                    There are a variety of plugin managers we can use. I will show you how to install and use the vim-plug plugin manager.

                    To install the vim-plug plugin, run this command:

                    On Linux or Mac OS.

                    On Windows with Powershell.

                    Add the call plug#begin(‘

                    /.vim/plugged’) and call plug#end() lines in the plugins section. The plugins we install will be added between the two function calls.

                    Now installing plugins is as easy as adding the Plug ‘username/plugin-name’ string you find on GitHub in between the function calls.

                    Add these two lines in between the two call plug#. lines:

                    Save the .vimrc file with the command :w and source the .vimrc file with this command :source

                    /.vimrc to make the changes take effect.

                    Now type :PlugInstall to download and install the two plugins.

                    vim-plug-install.png

                    How to Map Keyboard Shortcuts in Vim

                    In the mapping section we will add shortcuts to making typing longer commands easier. This will save you key strokes and lots of time, especially for long commands.

                    Key mapping syntax is like this:

                    map_mode <what_you_type> <what_is_executed>

                    Popular Mapping Modes in Vim

                    Here are a few popular mapping modes and probably the most useful and important.

                    • nnoremap – Allows you to map keys in normal mode.
                    • inoremap – Allows you to map keys in insert mode.
                    • vnoremap – Allows you to map keys in visual mode.

                    A common mapping example is to map ‘jj’ to the escape key. You will be pressing the escape key a lot. The escape key is in the far corner of the keyboard.
                    The letter ‘j’ is in the middle of the keyboard so it is easier to press ‘jj’ instead of reaching for the escape key.

                    This is how you would map the escape key to jj .

                    inoremap jj <esc>

                    How to Use Mapleader in Vim

                    Mapleader will allow you set a key unused by Vim as the <leader> key.
                    The leader key, in conjunction with another key, will allow you to create new shortcuts.

                    The backslash key is the default leader key but some people change it to a comma «,» .

                    With the leader key mapped to backslash, I can use it like this:

                    Turn off search highlighting by pressing \\ .
                    nnoremap <leader>\ :nohlsearch<CR>

                    Here are some common mappings that people use. See the comments above each line for the explanation.

                    Add this code in the mappings section:

                    Type help: map-modes for more information.

                    How to Add Some Vimscripting

                    Vimscript is a scripting language that lets you create scripts using variables, if else statements, and functions. Auto commands are waiting for events to occur in order to trigger a command.

                    Read Learn Vimscript the Hard Way for more information on Vimscript.

                    Type :help autocmd for more information on auto commands.

                    How to Add Color Schemes to Vim

                    You can easily add color schemes to Vim to change the default colors. Do a search for Vim color schemes and you will find many, many choices.

                    Installing a color scheme is a simple as adding a <colorscheme>.vim file to the

                    I will add the popular color scheme molokai:

                    To set the color scheme, type this command:

                    Example color schemes:

                    vim_four_colorschemes

                    color schemes: molokai, base16-tomorrow, blue, one

                    How to Configure the Status Bar in Vim

                    You can configure your Vim status bar with useful information. For example, configure the file type, total number of lines in the file, path to the file, column number, row number, percentage through file, and much more.

                    Add this code in the status line section:

                    %F – Display the full path of the current file.

                    %M – Modified flag shows if file is unsaved.

                    %Y – Type of file in the buffer.

                    %R – Displays the read-only flag.

                    %b – Shows the ASCII/Unicode character under cursor.

                    0x%B – Shows the hexadecimal character under cursor.

                    %l – Display the row number.

                    %c – Display the column number.

                    %p%% – Show the cursor percentage from the top of the file.

                    vim_statusline

                    Type help: statusline for more information.

                    This is the complete .vimrc file.

                    Conclusion

                    In this article, I have only scratched the surface of how you can customize Vim.
                    There are thousands of ways to configure and customize a .vimrc to your liking.
                    You can even write your own plugins and color schemes and share them with the world.

                    I hope that you have learned a new trick or two by reading this article. So if you use Vim, don’t leave home without a .vimrc file!

                    Customizing Vim

                    Settings like indentation and keyword-pairs can vary between different programming languages and file types. You might need to adapt style guides based on client requirements. Or perhaps, you wish to create or override commands to suit your preferences.

                    This chapter will discuss how you can customize Vim for different purposes. Some of the settings will be specific to GVim.

                      — set your settings — make new commands — write a Vim script — using filetypes — reference manual for Options — reference manual for Key mapping, abbreviations and user-defined commands — reference manual for Automatic commands

                    Editing vimrc

                    The Vim script language is used for the startup vimrc file, syntax files, and many other things.

                    The vimrc file can contain all the commands that you type after a colon. The simplest ones are for setting options.

                    • :e $MYVIMRC if you already have a vimrc file, you can use this predefined variable to open it to find out where the vimrc file should be located for your OS
                    • :source $MYVIMRC apply changes from within your current Vim session

                    To view a sample vimrc file, I have one on GitHub. More resources are mentioned in the Further Reading section at the end of this chapter.

                    defaults.vim

                    • source $VIMRUNTIME/defaults.vim add this to your vimrc file if you want to keep these defaults describes the settings provided by defaults.vim

                    Alternatively, you can copy only the parts you want to retain from the defaults.vim file to your vimrc file.

                    General Settings

                    set syntax and guidelines were introduced in the Setting options section.

                    • set history=200 increase default history from 50 to 200
                      • as mentioned in the Command-line mode chapter, there are separate history lists for : commands, search patterns, etc
                      • you can use :colorscheme followed by a space and then press Tab or Ctrl + d to get a list of the available color schemes
                      • first tab will complete as much as possible
                      • second tab will provide a list
                      • third and subsequent tabs will cycle through the completion options

                      :h ‘history’ will give you the documentation for the given option (note the use of single quotes).

                      You can use these settings from the Command-line mode as well, but will be active for the current Vim session only. Settings specified in the vimrc file will be loaded automatically at startup. You can also load a different file as the vimrc , which will be discussed in the CLI options chapter.

                      Further Reading

                      Text and Indent Settings

                      • filetype plugin indent on enables loading of plugin and indent files
                        • these files become active based on the type of the file to influence syntax highlighting, indentation, etc
                        • :echo $VIMRUNTIME gives your installation directory ( indent and plugin directories would be present in this path)
                        • see :h vimrc-filetype, :h :filetype-overview and :h filetype.txt for more details
                        • useful for files not affected by indent setting
                        • see also :h smartindent
                        • white space is used to break lines, so a line can still be greater than the limit if there’s no white space
                        • default is 0 which disables this setting
                        • use highlight ColorColumn setting to customize the color for this vertical bar
                        • see vi.stackexchange: Keeping lines to less than 80 characters for more details

                        Search Settings

                        • set hlsearch highlight all matching portions
                          • using :noh (short for :nohlsearch ) will clear the current highlighted portions
                          • pressing Enter key would move the cursor to the matched portion
                          • pressing Esc key would keep the cursor at the current location
                          • other matching terms will be highlighted based on hlsearch setting

                          Custom mapping

                          • nnoremap Normal mode non-nested, non-recursive mapping
                          • xnoremap Visual mode non-nested, non-recursive mapping
                          • inoremap Insert mode non-nested, non-recursive mapping
                          • inoreabbrev Insert mode non-nested, non-recursive abbreviation
                          • nmap , xmap , imap and iabbrev allows nested and recursive mappings
                          • nunmap , xunmap , iunmap and iunabbrev unmaps the given command (usually used from Command-line mode to temporarily disable a mapping, will be available again on startup if it was defined in vimrc )
                            • use mapclear instead of unmap to clear all the mappings for that particular mode

                            :nmap , :xmap , :imap and :iab will list all the current mappings for that particular mode. You can provide an argument to display the mapping for that particular command, for example :nmap Y . See :h key-mapping and :h map-overview for reference manuals.

                            Normal mode

                            • nnoremap &LTF2> :w&LTCR> press F2 function key to save changes
                              • &LTF2> represents the F2 function key and &LTCR> represents the Enter key
                              • I chose F2 since it is close to the Esc key ( F1 opens help page)
                              • likewise, you can map the other arrow keys to do nothing as well
                              • &LTsilent> modifier executes the command without displaying on Command-line
                              • Note that this mapping also retains the default behavior of the Space key
                              • I prefer this to make switching tabs consistent with browser and terminal shortcuts

                              See :h map-which-keys to know which keys are not already Vim commands, which ones are not commonly used, etc.

                              See :h key-notation for a list of keys that can be represented using the <> notation.

                              Map leader

                              • nnoremap &LTLeader>f gg=G if mapleader hasn’t been set, using \f will auto indent the code for the whole file
                              • let mapleader = «;» change the leader key to ;
                                • nnoremap &LTLeader>f gg=G this will now require ;f since the leader key was changed

                                Insert mode

                                • inoremap &LTF2> &LTC-o>:w&LTCR> press F2 to save changes in Insert mode as well
                                  • Ctrl + o to execute a command and return back to Insert mode automatically
                                  • imap &LTF2> &LTC-o>&LTF2> can also be used if you’ve already defined the Normal mode mapping
                                  • I’d prefer Ctrl + e but that is useful to cancel autocompletion
                                  • If you need Ctrl + v functionality, the Ctrl + q alias can be used to insert characters like Enter key (but this alias may not work in some terminals)
                                  • See :h i_CTRL-x and :h ins-completion for all the features offered by Ctrl + x

                                  Use noremap! if you want a mapping to work in both Insert and Command-line modes.

                                  Visual mode

                                  • xnoremap * y/&LTC-R>»&LTCR> press * to search the visually selected text in the forward direction
                                    • recall that Ctrl + r helps you insert register contents in Command-line mode

                                    Note that xnoremap is used here since vnoremap affects both Visual and Select modes.

                                    Abbreviations

                                    Abbreviations are usually used to correct typos and insert frequently used text. From :h abbreviations documentation:

                                    An abbreviation is only recognized when you type a non-keyword character. This can also be the &LTEsc> that ends insert mode or the &LTCR> that ends a command. The non-keyword character which ends the abbreviation is inserted after the expanded abbreviation. An exception to this is the character &LTC-]> , which is used to expand an abbreviation without inserting any extra characters.

                                    inoreabbrev p #!/usr/bin/env perl&LTCR>use strict;&LTCR>use warnings;&LTCR> expand p to the text as shown in the code snippet below

                                    • you can trigger the abbreviation completion using non-keyword character such as Esc , Space and Enter keys, punctuation characters and so on
                                    • use Ctrl + ] to expand the abbreviation without adding anything extra

                                    inoreabbrev py #!/usr/bin/env python3 expand py to #!/usr/bin/env python3

                                    • this might cause issues if you need py literally (for example, script.py )
                                    • you can use something like [p or @p instead

                                    inoreabbrev teh the automatically correct teh typo to the

                                    inoreabbrev @a always @()&LTCR>begin&LTCR>end&LTEsc>2k$ expand @a to the text as shown in the code snippet below

                                    • this one works best when you type @a followed by Esc key to place the cursor at the end of the first line

                                    :abbreviate or :ab list all abbreviations

                                    See :h 24.7 for more details about using abbreviations.

                                    Matching Pairs

                                    • set matchpairs+=&LT:> add <> to the list of pairs matched by % command in Normal mode

                                    To match keywords like if — else pairs with % , you can install matchit.vim plugin. This supports filetypes such as HTML, Vim, LaTeX, XML, etc. See :h matchit-install for more details.

                                    GUI options

                                    • set guioptions-=m remove menu bar
                                    • set guioptions-=T remove tool bar

                                    Third-party customizations

                                    See :h ‘runtimepath’ to know the path within which you can add the plugins and packages discussed in this section.

                                    /.vim is commonly used on Unix/Linux systems.

                                    Make sure to backup your directory (

                                    /.vim for example) and the vimrc file, so that you can easily apply your customizations on a new machine.

                                    plugin

                                    Some plugins are loaded by default. Some come with Vim installation but you have to explicitly enable them. You can also write your own or add plugins written by others. From :h add-plugin:

                                    • global plugin: Used for all kinds of files

                                    • filetype plugin: Only used for a specific type of file

                                    If you want to add a global plugin created by you or someone else, place it in the plugin directory. If you don’t have that directory yet, you can create it using the below command (assuming Unix/Linux):

                                    If you have multiple related plugin files, you can put them under a subdirectory:

                                    If you want to add plugins that should work based on specific filetype, add them to the ftplugin directory:

                                    package

                                    Packages make it easy to manage projects that require multiple plugins, use a version controlled repository directly and so on. See :h packages for more details. From :h add-package:

                                    A package is a set of files that you can add to Vim. There are two kinds of packages: optional and automatically loaded on startup.

                                    The Vim distribution comes with a few packages that you can optionally use. For example, the matchit plugin.

                                    • packadd! matchit enable matchit package
                                      • this plugin comes with Vim, see :h matchit for further details
                                      • ! is used to prevent loading this plugin when Vim is started with —noplugin CLI option

                                      vim-surround is used here as an example for a third-party package. Installation instructions (provided in this repository) are shown below, assuming you want to enable this package at startup:

                                      • ysiw] will surround a word with [] , for example hello to [hello]
                                      • cs»‘ will change text surrounded by double quotes to single quotes, for example «hi bye» to ‘hi bye’
                                      • :packadd vim-surround enable this package from Command-line mode
                                      • packadd! vim-surround enable this package in vimrc (usually under some condition)

                                      color scheme

                                      There are different ways to add a new color scheme. The simplest is to copy the theme.vim file to the

                                      /.vim/colors directory. Or, follow the installation steps provided by the theme creators. Here are couple of solarized themes you can check out:

                                      After installation, you can use the :colorscheme command to set the new theme. If the theme offers multiple variations, you might need additional settings like set background=dark or set background=light . See the installation instructions provided in the above repositories for more details.

                                      See Where to put what section under :h packages for more details about installation directories.

                                      autocmd

                                      An autocommand is a command that is executed automatically in response to some event, such as a file being read or written or a buffer change.

                                      Autocommands are very powerful. Use them with care and they will help you avoid typing many commands. Use them carelessly and they will cause a lot of trouble.

                                      Где отредактировать конфигурацию vim?

                                      bobrovskyserg

                                      / — это ваша домашняя директория?
                                      Нет, вы шутите, я вам не верю!

                                      • Facebook
                                      • Вконтакте
                                      • Twitter

                                      bobrovskyserg

                                      bobrovskyserg

                                      nathanael

                                      /.vimrc и поехали.

                                      ntzch: С какой стати при установке в систему должен создаваться какой-либо файл в каталоге пользователя?

                                      Для тех пакетов, у которых имеется файл настроек по умолчанию, тот получает прописку в /etc, иногда в другом каталоге, но никак не в домашнем каталоге какого-либо пользователя. Последнее может произойти только в случае установки ПО не штатными средствами дистрибутива (через пакетный менеджер), а в пользовательский каталог.

                                      Open vimrc file

                                      The vimrc file contains optional runtime configuration settings to initialize Vim when it starts. On Unix based systems, the file is named .vimrc , while on Windows systems it is named _vimrc . :help vimrc

                                      You can customize Vim by putting suitable commands in your vimrc. Here is a very simple example:

                                      Lines that begin with » are comments and are not read by vim.

                                      Search for file vimrc_example.vim in your Vim files for another example. :help vimrc-intro :help vimrc_example.vim

                                      To customize Vim for editing a specific file, or a specific type of file, you can use modelines, or auto commands, or filetype plugins. :help auto-setting :help filetype

                                      Location of vimrc [ ]

                                      In Vim, your home directory is specified with $HOME . On Unix systems, this is your

                                      directory. On Windows systems, the best way to find the value of $HOME is from within Vim, as follows. These commands are useful to see what directories your Vim is using:

                                      Note the ‘system vimrc file’ and ‘user vimrc file’ paths displayed by the :version command. The system vimrc file can be created by an administrator to customize Vim for all users. In addition, each user can have his or her own user vimrc.

                                      The output from :version includes the paths of the system and user vimrc and gvimrc files. For example:

                                      If the gvimrc files exist, they are used to configure Vim when the GUI version (gvim) runs (after settings from vimrc are applied).

                                      Settings for gvim can also be placed in the vimrc file using a has(‘gui_running’) check:

                                      Although this can be useful to avoid the clutter of both a vimrc and gvimrc file, using the gvimrc file has distinct benefits over the «gui_running» check. The most notable being that a gvimrc file is sourced when using the :gui command to change a vim session into a gvim session. Anything that was in the vimrc inside a «gui_running» check will not be applied since the vimrc is only sourced when Vim initially starts.

                                      Per-directory vimrc [ ]

                                      Vim can be configured so that, when starting, it reads commands from a vimrc file in the current directory, after reading the primary vimrc. This is configured by adding set exrc to the primary vimrc file. Setting ‘exrc’ can be a security problem because it means Vim will execute commands from any vimrc file in the directory where Vim is started. :help ‘exrc’ For that reason, set the ‘secure’ option if you use this option, and you may also want to limit setting this option to when Vim is started from known «safe» directory trees:

                                      Opening vimrc [ ]

                                      If Vim finds your vimrc file during startup, Vim will set the MYVIMRC environment variable to the full path of the vimrc file. Similarly, if your gvimrc file is found, the MYGVIMRC variable is set. Therefore, you can easily edit these files from within Vim:

                                      Using file name completion, you could type :e $M then press Tab until you see the desired variable. If you only want to see the path, type :echo $M then press Tab to see the variable, and press Enter.

                                      In gvim, the Edit menu includes «Startup Settings» which will use $MYVIMRC to edit your vimrc file. If $MYVIMRC does not exist, «Startup Settings» will create a new file using the «user vimrc file» path shown by the :version command.

                                      Sourcing vimrc [ ]

                                      After you have saved changes to your vimrc file, you can see the results by exiting from Vim, then starting Vim again.

                                      If you are making frequent changes, you might want to «source» (execute) the changed vimrc file without exiting:

                                      Warning You may need to plan your vimrc so re-sourcing does not cause problems. If you define commands, functions, or autocmds, you must make them remove or override the previous version when sourced, or you will get errors (for commands and functions) or duplicates (for autocmds). Here are some examples that will work correctly when re-sourced:

                                      Recovering from errors [ ]

                                      Some errors in your vimrc may prevent Vim from starting successfully. A reliable way to handle that would be to rename your vimrc file, then edit the renamed file, then give it the correct name. Alternatively, you could start Vim with a command like this (or use «gvim» if that is how you run Vim):

                                      The -N starts in «not compatible» mode (that is, with extra Vim features). The NONE argument (must be uppercase) skips initializations and does not read any vimrc file ( -u ), and does not read any gvimrc file ( -U ).

                                      You could now use the :version command to show the vimrc path, then enter a command to edit that file.

                                      Comments [ ]

                                      TO DO

                                      • What else is needed to explain what vimrc is, and how to use it, for a beginner?
                                      • Do something with the following text from the original tip (if keep it, need to fix text because it assumes you have used some standard setup for installation, and assumes $VIM and $HOME are some default, and of course is for Windows):

                                      On Windows, when you start Vim normally, it *either* runs the file «C:\Documents and Settings\(user name)\_vimrc» (where «(user name)» is replaced by the actual user name); *or*, if that file doesn’t exist (it usually doesn’t, for most users), it runs the file «C:\Program Files\vim\_vimrc». Note that if you have more than one disk your home may be different; do an «:echo $HOME» to know where is your home. You should also see the _viminfo file in that directory.

                                      • Include information for Windows:
                                        • When $HOME is not defined, it is created by combining $HOMEDRIVE and $HOMEPATH (if defined).
                                        • The recommended method to define $HOMEDRIVE and $HOMEPATH is to set the «Home folder . Local path» on the Profile tab of the User properties in Local Users and Groups (run lusrmgr.msc).
                                        • I’d say that this (the item above) is the recommended method to set your home folder in Windows. The recommendes method to specify where your _vimrc is located (if it differs from your home folder) is to set the $HOME environment variable. (Spiiph 00:16, 29 July 2009 (UTC))
                                        • Link to the #vim-approved .vimrc ? 😉 (Spiiph 00:18, 29 July 2009 (UTC))

                                        Proposal Omit suggestions like the following that attempt to auto-source vimrc. I suspect that anyone needing to read a tip to do this could get themselves in quite a bit of trouble. IMHO it’s a lot more sensible to map a key to source a script so you can control when it is sourced. I haven’t bothered to put such a mapping in the tip so far because the :so % info seems more helpful, and entirely adequate. —JohnBeckett 11:56, 23 August 2008 (UTC)

                                        To source changes immediately, add to vimrc:

                                        Why not use a BufWritePost instead of BufLeave, so it will source whenever you save?

                                        Getting started tip . I hit this page because I could not remember the «mkvim» command. I found it elsewhere and thought I’d throw it in here. If you open vim, change some settings and get things how you like you can use this command

                                        to automatically make a vimrc file based on your current settings. The [file] part is optional; vim will use

                                        /.vimrc by default. If you already have a .vimrc and you attempt this you we will be warned that .vimrc already exists. You can use

                                        to overwrite the existing file if you like. However once you do this your original .vimrc file is gone so you may want to back up any existing .vimrc before you try this.

                                        Using :mkvimrc to create .vimrc isn’t a terribly good idea, since it saves mappings and abbreviations setup by plugins. It can be useful to copy currently set options to .vimrc however. (Spiiph 14:51, 27 July 2009 (UTC))

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *