- How To Download, Install and Use Vim In Windows
- Download
- 32 Bit Installer
- 64 Bit Installer
- Portable
- Install Vim
- Use Vim
- 1 thought on “How To Download, Install and Use Vim In Windows”
- Установка и использование текстового редактора Vim
- Установка vim
- Начало работы c Vim
- Модальное редактирование
- Обычный режим
- Режим вставки
- Визуальный режим
- Командный режим
- Перемещение по тексту в редакторе vim
- Основы перемещения
- Расширенное перемещение
- Редактирование
- Удаление текста
- Изменение текста
- Копирование и вставка
- Прочее редактирование
- Управление документами
- Итоги
- Vim — Установка и настройка
- Установка на платформе Windows
- Монтаж
- конфигурация
- Установка на Linux на основе Debian
- Build Vim in Windows with Visual Studio
- Contents
- Python interface [ edit | edit source ]
- Required tools [ edit | edit source ]
- Required directories and files [ edit | edit source ]
- Vim source and runtime files [ edit | edit source ]
- Building Vim [ edit | edit source ]
- Configuring Vim [ edit | edit source ]
- Installing Vim [ edit | edit source ]
- Diff program [ edit | edit source ]
- Comments [ edit | edit source ]
How To Download, Install and Use Vim In Windows
Vim is Linux based opensource tool. The roots goes to the vi editor. In Linux distributions vim can be easily installed via package managers like apt , yum , dnf and zypper . Windows is the most popular desktop operating system. Vim is provided for Windows operating systems too. In this tutorial we will look how to download, install and use vim in Windows Operating systems.
Download
Vim official web page provides download links for Windows operating systems. As Windows is mainly graphical user interface vim is provided with name gvim which is graphical vim. We can download from following links.
32 Bit Installer
64 Bit Installer
Portable
Install Vim
We can install vim for Windows with Windows style Next -> Next logic. Vim is installed to the C:\Program Files\Vim directory.
Install Vim
Use Vim
After installation the read me file is opened by newly installed vim . Which will look like this.
Use Vim
Windows vim provides some of its features with menu. As an example we can use following features from menu.
- Save
- Save All
- Find and Replace
- Find Next
- Load Session
- Save Current Session
- Run Vim Script
1 thought on “How To Download, Install and Use Vim In Windows”
Thank you for your article — While I wish the “Use Vim” section was more detailed this was nice to have the links to download readily available. Vim is a tough program to learn requiring multiple plug-ins (solomakerlabs a Twitch full stack streamer uses 57 of them). The functionality and productivity of using Vim seems very high, but only if one grasps how to navigate and use Vim.
There are many editors such as VSCode that are more GUI based than Vim, which may be what most people want. Vim is a program from the earlier days of the computer age, but it is still worked on and developed for as of 2019. There doesn’t seem to be an end to Vi, Vim, or Bash to name a few legacy programs that still have modern use.
Установка и использование текстового редактора Vim
Один из наиболее мощных текстовых редакторов, доступных из командной строки, – редактор Vim. Основанный на Vi и выпущенный в 1976, данный редактор обладает дополнительной функциональностью и мощностью, сохраняя при этом стиль редактирования своего предшественника.
Данное руководство охватывает установку и базовое использование Vim.
Установка vim
Благодаря широкому использованию vim в командной строке Linux он доступен в репозитории по умолчанию почти каждого дистрибутива.
Для установки редактора на Ubuntu и Debian используйте команду apt-get:
sudo apt-get install vim
Чтобы установить vim на Fedora и CentOS, используйте yum:
sudo yum install vim
На Arch Linux vim можно установить с помощью pacman:
sudo pacman -S vim
Итак, теперь Vim установлен.
Начало работы c Vim
При вызове без аргументов Vim по умолчанию открывает пустой документ. В зависимости от дистрибутива Vim может сначала вывести вступление и лицензию, которые исчезнут сразу после начала работы с редактором.
Тем не менее, сейчас запускать vim с чистого документа не нужно. Чтобы продемонстрировать возможности vim, можно создать новый документ под названием «newfile»
echo «This is a new file.
Here is the second line
And here is the third line.
Some more text is on this line. We will edit this file in vim.
It will be great fun.» >> newfile
Теперь откройте только что созданный файл.
Модальное редактирование
Главное отличие Vim от большинства других редакторов состоит в том, что vim является «модальным» редактором. В редакторах такого типа специальные функции редактирования, такие как копирование текста, выполняются путем удерживания одной или нескольких клавиш-модификаторов и затем нажатия обычной клавиши. Vim использует различные режимы, чтобы отличать эти функции от обычного ввода текста.
Обычный режим
Используется для редактирования операций. Копирование, вставка, перемещение, удаление и изменение текста осуществляются в этом режиме.
Vim выполняет редактирование в «обычном» режиме. В данном режиме редактор находится при запуске. Этот режим используется для быстрого перемещения и редактирования текстового документа. Он не используется для ввода текста.
- [esc] – чтобы перейти в обычный режим, нажмите клавишу «escape».
Режим вставки
Используется для ввода текста. Данный режим можно установить несколькими способами.
Чтобы ввести текст, vim нужно перевести в режим вставки. Этот режим является аналогом интерфейса ввода, который используется большинством других программ ввода текста. Набранный в документе текст выводится на экран. Все обычные клавиши создают соответствующий символ в текущей позиции курсора.
- i – устанавливает режим вставки в текущей позиции курсора;
- а – устанавливает режим вставки после текущей позиции курсора;
- I – устанавливает режим вставки в начале текущей строки;
- А – устанавливает режим вставки в конце текущей строки.
Визуальный режим
Используется для визуального выделения. Многие команды, доступные в обычном режиме, можно применить к конкретной выделенной части текста.
Третий режим, который использует Vim, называется визуальным. Участки текста выделяются как цель для команд редактирования или форматирования.
- v – устанавливает обычный визуальный режим. Выбор осуществляется путем перемещения курсора вверх, вниз, влево и вправо.
- V – устанавливает режим визуальной строки. Выбираются целые строки, от первого до последнего символа, путем перемещения вверх и вниз.
- [ctrl]-v – Переход в режим визуального блока. Блок для выбора можно расширить и сузить. С помощью этого метода можно выбрать отдельные части нескольких строк.
Командный режим
Используется для выполнения команд. Для активации этого режима используется двоеточие.
Дополнительный режим, который необходим для сложного редактирования, изменения настроек и для управления vim, называется командным. Данный режим используется для сохранения документов, завершения работы программ, выполнения сложного поиска, и т.п.
Перемещение по тексту в редакторе vim
Основы перемещения
Перемещаться по тексту всегда можно при помощи клавиш со стрелками, но Vim предоставляет и более быстрые способы перемещения по документу. В обычном режиме можно использовать клавиши h, j, k и l для передвижения влево, вниз, вверх и вправо соответственно.
Сначала эти клавиши управления курсором могут сбить с толку и показаться нелогичными, но их выбор не случаен. На обычной клавиатуре они расположены в опорном ряду клавиш. Это значит, что работать с ними намного удобнее.
Расширенное перемещение
Существуют также другие горячие клавиши перемещения. Ниже приведены самые полезные их них.
- gg – перемещение в начало документа;
- G – перемещение в конец документа. Указав перед данной опцией номер строки, можно перейти к этой строке.
- w – переход к следующему слову. Указав перед опцией число, можно перейти к такому количеству слов.
- b – вернуться к предыдущему слову. Указав перед опцией число, можно вернуться на такое количество слов назад.
- e – переход в конец слова. Указав перед опцией число, можно пропустить такое количество слов.
- 0 – перемещение в начало строки.
- $ – передвижении в конец строки.
Редактирование
Редактирование текста в Vim осуществляется путем запуска команд в обычном режиме.
Важно понимать, что команды редактирования в Vim очень мощны в сочетании с операторами движения. Все опции, описанные в главе о перемещении, могут быть использованы в качестве направления. К примеру, команду редактирования слова можно выполнить при помощи внесения флага «w».
Ниже приведены несколько действий, которые можно использовать:
Удаление текста
- x – удаляет символ под курсором.
- d – удаляет символ в направлении, указанном после ввода команды. Например, «dl» удаляет символ справа.
- dd – удаляет строку.
- D – удаляет текст от текущей позиции курсора до конца строки.
Изменение текста
- r – заменяет символ под курсором. Укажите символ, который нужно заменить, в конце команды.
- c – изменяет текст в указанном направлении. К примеру, «cw» изменяет текущее слово. После выполнения этой команды vim переходит в режим вставки, так что можно ввести текст для замены.
- C – изменяет текст до конца строки. Данная команда также переводит vim в режим вставки.
Копирование и вставка
- y – копирует в указанном направлении.
- yy – копирует целую строку.
- Y – копирует текст до конца строки.
- p – вставляет последнюю скопированную (или удаленную) строку под текущей строкой.
- P – вставляет последнюю скопированную (или удаленную) строку над текущей строкой.
Прочее редактирование
- u – отменить последнее действие.
- —r – повторить последнее действие.
- J – соединить текущую строку со следующей.
Управление документами
Vim управляет документами преимущественно в командном режиме. Для ввода команд перед каждой нужно использовать двоеточие.
- :q – выйти из vim. Если изменения не были сохранены, это не удастся.
- :q! – выйти из vim, не учитывая все несохраненные изменения.
- :w – сохранить изменения. Нажмите пробел и введите имя файла, чтобы сохранить документ в другое место; если это первое сохранение, укажите место для сохранения.
- :e – отредактировать следующий файл.
- :bn – отредактировать следующий открытый в vim файл.
- :bp – отредактировать предыдущий открытый в vim файл.
Итоги
Как уже упоминалось ранее, мощность Vim состоит в возможности объединять различные команды в цепи. Самый простой способ понять эту концепцию – рассматривать команды vim как английский язык. То есть, клавиши в обычном режиме могут представлять прилагательные, глаголы и существительные.
К примеру, чтобы скопировать (yank) 4 слова (words), просто переведите эту фразу на понятный vim язык. В данном случае получится:
Чтобы удалить (delete) текст с текущей строки и до конца файла, введите:
Такой подход также полезен для того, чтобы понять некоторые условные обозначения, которые vim использует в командах редактирования.
Заглавная версия команды редактирования чаще всего нацелена от текущей позиции курсора до конца строки. К примеру, чтобы изменить текст от текущей позиции курсора до конца строки, используйте:
Чтобы выполнить эту же команду на несколько строк, просто добавьте к команде числовой префикс. Это изменит текст от текущей позиции курсора до конца следующей строки:
Существует целое множество мощных техник использования vim, не вошедших в данное руководство. Чтобы получить больше информации, используйте встроенный в vim мануал. Он не охватывает сложных тем, но дает представление о том, как работать и выполнять базовое редактирование с Vim. Для запуска учебника используйте:
Vim — Установка и настройка
Vim — это легкий пакет, и его установка действительно проста. В этой главе мы обсудим следующие пункты —
- Установка на платформе Windows
- Установка на Linux на основе Debian
- Установка на основе RPM Linux
Установка на платформе Windows
У Vim нет особых требований. Это простой пакет программного обеспечения, который обеспечивает все зависимости.
Монтаж
Чтобы скачать Vim, посетите vim.org
Нажмите на опцию загрузки на левой панели
Нажмите на ПК — MS-DOS и MS-Windows вариант
Загрузите установщик .exe с этой страницы. На момент написания этого учебника имя установщика было gvim80.exe
Дважды щелкните установщик и следуйте инструкциям на экране для завершения установки
Чтобы скачать Vim, посетите vim.org
Нажмите на опцию загрузки на левой панели
Нажмите на ПК — MS-DOS и MS-Windows вариант
Загрузите установщик .exe с этой страницы. На момент написания этого учебника имя установщика было gvim80.exe
Дважды щелкните установщик и следуйте инструкциям на экране для завершения установки
конфигурация
Vim хранит свою конфигурацию в простом текстовом файле, а именно _vimrc, и находится в домашнем каталоге пользователя.
Чтобы найти домашний каталог текущего пользователя, выполните в терминале следующую команду —
Чтобы найти домашний каталог текущего пользователя, выполните в терминале следующую команду —
Перейдите в домашний каталог и создайте новый файл, а именно _vimrc. Убедитесь, что этот файл не имеет расширения.
Откройте этот файл в текстовом редакторе, введите следующий текст и сохраните его —
Перейдите в домашний каталог и создайте новый файл, а именно _vimrc. Убедитесь, что этот файл не имеет расширения.
Откройте этот файл в текстовом редакторе, введите следующий текст и сохраните его —
Теперь Vim будет показывать номера строк при открытии файла. Мы добавим больше опций в этот файл позже.
Теперь Vim будет показывать номера строк при открытии файла. Мы добавим больше опций в этот файл позже.
Установка на Linux на основе Debian
Установка на платформе Linux довольно проста по сравнению с Windows. В этом разделе описывается установка и настройка в Linux на основе Debian.
Build Vim in Windows with Visual Studio
created July 28, 2011 · complexity basic · author JohnBeckett · version 7.0
This tip explains how to download the source for Vim, then build a Vim executable, and install it on a Windows system. Optionally, Vim can be compiled with a Python 2.x or 3.x interface. The build is performed using the Microsoft Visual Studio 2010 Express (free). See Building Vim for related information, including how to download Vim if you do not want to build it yourself.
Administrative privileges are not required for the steps in this tip, except when installing:
- Python (if Python is wanted).
- Mercurial (if using the «needs admin rights» installer to make Mercurial available for all users).
- Microsoft Visual Studio.
Contents
Python interface [ edit | edit source ]
This tip shows how to build Vim with or without a Python interface. Python is optional, and not needed for normal Vim.
Vim can be compiled to provide an interface so that Vim scripts can be written in Python, and so that Vim commands like :py print 2**1024 work. If an interface between Vim and Python is wanted, Python needs to be installed separately, and Vim needs to be compiled with support for the version of Python used. Vim can be configured to work with Python 2.x or 3.x or both (although the 3.x configuration is newer and less tested).
To determine whether a particular installation of Vim supports Python, enter the command :version in Vim. If the output includes +python/dyn (with » + «) then Python 2.x is supported, and the DLL file specified in the link command shown in the output will be dynamically loaded if needed. If the output includes +python3/dyn then Python 3.x is supported, and the Python 3 DLL file shown in the output will be dynamically loaded if needed. On Windows, dynamic loading is standard with the result that although Python needs to be installed to build Vim, the resulting Vim executable can be run on a system with no Python (Vim would work, but attempting to use the Python interface would fail).
Required tools [ edit | edit source ]
The following tools may be installed to download and build the Vim source.
Python programming language (optional) For example, install using «Python 2.7.2 Windows Installer (Windows binary — does not include source)» from here. This is not needed by Mercurial or Vim. Mercurial uses file python26.dll that is included in the standard Mercurial installer for Windows. Vim can be built to provide an interface so that Vim scripts can be written in Python, and so that Vim commands like :py print 2**1024 work. If that is wanted, Python needs to be installed before building Vim. Mercurial version control system ( hg command) For example, install using «Mercurial-2.0 (32-bit msi) needs admin rights to install» from here. Mercurial recommends that the Windows indexing service and virus scanners be configured to exclude directories containing a repository or a working copy. This advice can probably be ignored, but a virus scanner may lock a file after it is written so any program (such as Mercurial) which writes many files then attempts to operate on them, could fail. Microsoft Visual C++ 2010 Express (part of Visual Studio) Free download here. The product can be downloaded, installed, and the Visual Studio GUI run for thirty days (or indefinitely if registered online with Microsoft). Registration is not required to build Vim because only the command line tools are used. Administrative privileges are required to install and to register.
To install Python or Mercurial, download the wanted setup program and run it.
It is not needed for Vim, but if you want to run Python in a command prompt window, you need to first adjust the PATH, for example:
To install Visual Studio, download the setup program (see link above). Setup is a small program which downloads components as required. As an administrator, run setup and perform these steps:
- Accept or clear «send information about my setup experiences to Microsoft».
- Agree to license.
- Accept or clear option to install Microsoft Silverlight.
- Accept default install location.
- Restart computer when prompted.
- After restarting, log on as an administrator; setup will automatically continue running.
- When finished, setup prompts that Windows Update should be used.
- Use Windows Update to install security updates; restart when prompted.
- Later, you can run the «Microsoft Visual C++ 2010 Express» GUI and use the Help menu, «Register Product» to register within 30 days.
Required directories and files [ edit | edit source ]
The following directories will be used as examples:
Directory \current\build\vim Will hold Vim source and runtime files as downloaded using Mercurial. Also used to build Vim. Replace » current » with whatever you like, however if the path contains spaces, more care will be needed. Directory \myname\bin Will hold some files used when building, as well as the Vim executable and runtime files used to run Vim. The intention is that myname holds programs or other files that are wanted on several different computers. Make a master copy on one computer, then copy the master to other computers. No installation will be required on the other computers, apart from adjusting the PATH. The bin directory can contain any simple tools that do not need installation, although for this tip it will only contain two batch files. The Vim files will be installed in a subdirectory. Replace » myname » with whatever you like, however if the path contains spaces, more care will be needed.
In a command prompt window, enter the following to make the current and build directories (the vim subdirectory will be created later).
Enter the following to make the myname and bin directories.
Create file \myname\bin\vimconfig.cmd with contents as follows, if a Python interface is not wanted:
Alternatively, use the following contents if a Python interface is wanted (this text assumes a default install of Python 2.7):
If installing with Python 3 and above, replace PYTHON with PYTHON3 :
Additional options could be:
More information on the build options is available here.
Create file \myname\bin\vimcopy.cmd with contents as follows:
Vim source and runtime files [ edit | edit source ]
The following sets build as the current directory, then downloads the entire Vim source and runtime files to a tree under the vim subdirectory (created by the hg command). This is required once only, to get started, and will take a few minutes.
In the future, changes to the Vim source and runtime files can be downloaded with the following.
If you accidentally change some Vim source files, you can clean the source to discard your changes.
Building Vim [ edit | edit source ]
After the initial clone ( hg clone ) or update ( hg pull -u ), the executable Vim programs can be built with the following.
These commands use:
- File \current\build\vim\src\msvc2010.bat supplied with Vim. This calls file vsvars32.bat (installed with Visual Studio) to configure environment variables to allow building at the command prompt.
- File \myname\bin\vimconfig.cmd (created in an earlier step) to configure environment variables for the options wanted while building Vim.
- File nmake.exe (installed with Visual Studio) to compile and link Vim.
The above builds programs gvim.exe (GUI Vim), vimrun.exe (to run external commands from Vim), and xxd.exe (to display binary files in hex). If wanted, you can also build vim.exe (console Vim, to run in a command prompt window) with:
If wanted, you can change the options used to build Vim (see Make_mvc.mak ). However, the old build files must be «cleaned» (deleted, so the new build will not use a mixture of files from the old and new configurations). Clean with the following.
Configuring Vim [ edit | edit source ]
Vim is usually configured with a vimrc file and with runtime files set by the user (in addition to the runtime files provided with Vim). Generally the user config files are under the $HOME directory. Vim sets its $HOME variable from the environment variable HOME , if defined, or, more commonly on Windows systems, by joining variables HOMEDRIVE and HOMEPATH .
By default, a user logged on as Myname on a Windows XP system will have C:\Documents and Settings\Myname as their $HOME directory. On some systems, that location can be changed by running lusrmgr.msc : display the Properties of the user; on the Profile tab, set «Home folder, Local path» to be any wanted directory (for example C:\myname ).
In Vim, you can display the value of $HOME by entering:
Create file $HOME/_vimrc with your preferred settings, for example:
See disable beeping for information on the ‘visualbell’ option, and see example vimrc for further ideas.
As an example of a configuration file, create file python.vim in the directory $HOME\vimfiles\after\ftplugin (you will need to create the vimfiles and after and ftplugin directories). The file should contain:
After creating the directories, you can enter this command in Vim to create the file (
is the same as $HOME ):
The effect of this example is that, when editing *.py files, the ‘expandtab’ option will be set, so spaces will be inserted when the Tab key is pressed.
Installing Vim [ edit | edit source ]
After building, copy the executables and runtime files to overwrite the current Vim installation (or to create it). This can be run from any directory. Any previous runtime files are overwritten. Make sure Vim is not running.
This uses file vimcopy.cmd (created in an earlier step) to copy the Vim files from the build directory to directory C:\myname\bin\vim\vim73 (and subdirectories).
Vim can now be run in a command prompt window, although it is necessary to adjust the PATH:
To permanently update the PATH, run System Properties: on the Advanced tab, click Environment Variables. An administrator can edit «Path» under System variables (which will apply to all users). Append ;C:\myname\bin\vim\vim73 to the existing PATH.
If other tools are placed in the bin directory, also append ;C:\myname\bin to the PATH. If that is done, the «build» step can use vimconfig rather than \myname\bin\vimconfig.cmd , and the «installing» step can use vimcopy rather than \myname\bin\vimcopy.cmd
It is possible to add an «Edit with Vim» entry to the Windows Explorer context menu. If that is not wanted, installation is finished, and gvim can be run from a command prompt window. It is also possible to drag and drop one or more files from Windows Explorer to gvim and then to display each file in its own tab by entering :tab sball .
To add an «Edit with Vim» entry to the context menu, as an administrator open a command prompt window and enter:
The install.exe program runs in a command prompt window and presents a series of options regarding the actions that it will take. Actions can be configured or disabled by responding to the prompts. One of the possible actions is to generate a sample vimrc file which is not recommended. The option to add an entry to the popup (context) menu only works when performed by an administrator.
Diff program [ edit | edit source ]
Vim can display the differences between files, providing a diff program is available. Windows users should download the setup program for «Complete package, except sources» from GnuWin32 diff. Run setup and either accept the defaults, or install in a temporary directory that you will later delete (perhaps by running the uninstall program). If wanted, you can install without administrative privileges: select «Don’t create a Start Menu folder» and click Ignore several times when setup fails to write to the registry. Copy files diff.exe and *.dll from the resulting GnuWin32\bin subdirectory to a directory that is in your PATH (you could use C:\myname\bin\vim\vim73 although it would be better to use another directory for programs not distributed with Vim).
If you have run the Vim install.exe program and used it to generate a sample vimrc file, it will include set diffexpr=MyDiff() which is not wanted: remove that line (and the MyDiff function) from vimrc.
Comments [ edit | edit source ]
- Show a HUGE or BIG build example to show how it’s done.
- Check claims made about MyDiff and if valid, explain why it isn’t wanted. Fritzophrenic has to use MyDiff to make diffs. Check when used with paths with embedded spaces.