Code

Vim: Using Regular Expressions, Window Management, and Macros. Part 3 of the Free Online Course

Vim: Using Regular Expressions, Window Management, and Macros. Part 3 of the Free Online Course

Free Python course ➞ A mini-course for beginners and experienced coders. Four cool portfolio projects and live chat with the speaker. Click and see what you can learn in the course.

Learn more

In 16 lessons, you'll master all the necessary skills to effectively work with the Vim editor. We'll cover basic commands, settings, and advanced features that will help you increase your productivity and optimize your code editing process. This course is ideal for both beginners and those looking to deepen their knowledge of Vim. Join us and begin your journey to Vim mastery.

  • the history of text editors;
  • working in insert mode, command mode, command line mode, and visual mode;
  • using regular expressions and creating macros;
  • plugins and plugin package managers;
  • Vim configuration, working with the .vimrc file (including the author's .vimrc file as an example);
  • working with Neovim;
  • setting up autocompletion.

Today we present three video tutorials in which we will discuss regular expressions in detail, their purpose, and application. You will also learn how to effectively manage windows in the Vim editor and how to create macros to automate tasks. This knowledge will help you increase your productivity and improve your text-processing skills.

How the course is structured

We offer video lessons and text transcripts, allowing you to study the theory in both video and text formats. Choose the learning method that is most convenient for you and dive into the material.

The course author is a professional with deep knowledge and experience in their field. Each course is created taking into account current trends and the needs of students. The author shares unique methods and practical recommendations, allowing participants not only to grasp theoretical aspects but also to apply them in practice. Through an individual approach and attention to each student, the course author promotes skill development and confident application of knowledge in real life. By choosing this course, you get the opportunity to learn from an expert whose methods have already helped many people achieve success.

Team lead at Purple Magic, video producer at Red Magic, co-host of the IT Way podcast, and author of programming training courses. He is passionate about the Ruby programming language.

In previous parts, we examined key aspects that influence the successful development of your business. We discussed the importance of strategy, market analysis, and understanding the target audience. These elements play a crucial role in creating effective marketing campaigns and increasing competitiveness. To achieve the best results, it is necessary to constantly monitor changes in the industry and adapt your approaches. It is also important to consider current trends and use digital tools to optimize business processes. In the next section, we'll dive into practical methods for implementing these strategies and explore successful examples of companies that have achieved significant results.

  • Lessons 1-2: The History of Text Editors and the Evolution of Vim
  • Lessons 3-7: All About Vim Modes

Using Regular Expressions

Our goal is to demonstrate the use of regular expressions in the Vim text editor, not to teach you all their capabilities. Using regular expressions in text editors can seem complicated at first, and we will look at several practical examples to clarify this topic. Regular expressions are a powerful tool for searching and processing text, and understanding their use in Vim will greatly simplify your work with text.

We have already discussed the text replacement capabilities in the Vim editor. Recall that the s command is used to perform a replacement. This command allows you to effectively edit text by replacing one word or phrase with another. Using this feature, you can significantly speed up the editing process and improve the quality of your code or text. Don't forget that using substitutions in Vim correctly can significantly simplify your work and increase your productivity.

Replacement in VimScreenshot: Skillbox Media

In previous In our lessons, we learned that we can add the g flag to this command to replace every occurrence in the string. Now let's discuss other arguments that can be useful when working with this command.

Adding the c (confirm) argument allows you to choose which substitutions to perform and which not. For example, you could use the command: s/user/admin/gc to replace all occurrences of user with admin, confirming each substitution. This approach avoids unwanted changes and gives the user full control over the process.

Replacing in Vim using the c argument Screenshot: Skillbox Media

Editor will select the elements one by one for confirmation. To confirm, press y (yes), to reject, press n (no). If you want to replace all remaining occurrences at once, use the a key.

The i argument in regular expressions allows you to ignore the case of letters. This means that when using the i flag, characters will be matched regardless of their case. Let's look at the application of this flag using an example: s/user/admin/gi. In this case, if any spelling variations of the word «user» appear in the string (for example, «User», «USER», «uSeR»), they will be replaced with «admin». This makes searching and replacing more flexible and convenient for working with text.

Replacing in Vim using the i argument Screenshot: Skillbox Media

All the words "user" were replaced, regardless of case.

In previous lessons, we discussed the need to use backslashes before specialized characters in regular expressions. However, in some cases, this can be challenging. For example, replacing a long file path may require writing a complex expression, making the process more difficult. To simplify working with regular expressions and avoid errors, it's important to understand how to use backslashes correctly and which characters require escaping. This knowledge will help you process strings and search and replace texts more efficiently.

Not the most convenient configuration with backslashes. Screenshot: Skillbox Media

Too many backslashes can make your text difficult to read. In such cases, you can use a simple life hack: use colons instead of backslashes in the s command. This approach significantly simplifies the code, making it easier to understand and edit. Proper formatting and optimization of text not only improves its readability, but also contributes to a better perception of information by users and search engines.

The same after the life hack with colons Screenshot: Skillbox Media

In this case, you can use slashes directly. However, it's important to remember to insert a backslash before the colons. This will help avoid errors in code interpretation and ensure correct execution of program operations. Proper use of slashes and backslashes is an important aspect of working with syntax, which is especially relevant for programming and web development.

The pipe (|) in regular expressions allows you to find lines that contain one of several specified conditions. For example, if you want to find all lines that contain the words "user" or "admin," you would use the expression /user|admin/. This expression will effectively search for lines that contain at least one of the specified words, greatly simplifying data filtering. Using pipes in regular expressions is a powerful tool for text analysis and data processing.
Finding lines containing two or more regular expressions Screenshot: Skillbox Media

Note that this expression contains a backslash. Without it, the regular expression will search for the user or admin combination, which may lead to unexpected results. Using the backslash is necessary for the regular expression to work correctly and accurately search for the desired data.

To search for all words ending with a specific regular expression, you can use an angle bracket. For example, to display all words ending in «er», you would enter the regular expression /er\>. This method allows you to effectively find the desired words in text, facilitating data management and increasing search accuracy. Regular expressions are a powerful tool for analyzing text information and can significantly simplify tasks related to processing and filtering data.

Find words ending in erScreenshot: Skillbox Media

Note that a backslash is also present here. The situation is similar with the beginning of a word, but an opening angle bracket is used instead. This is important to keep in mind when working with code and markup to avoid errors and ensure that information is displayed correctly. Make sure you use characters correctly and follow established standards to ensure that your content is correctly interpreted by browsers and search engines.

These are just a few useful tips for using regular expressions in the Vim editor. We encourage you to explore the possibilities to find the techniques that will be most useful for your workflow. Regular expressions can significantly simplify text editing and increase your productivity.

Finally, we present a few common commands related to the use of regular expressions. These commands will help you work effectively with text data, making it easier to search and process it. Regular expressions are a powerful tool for string processing, allowing you to perform complex operations such as validation, replacement, and pattern matching. Learn these commands to improve your regular expression skills and maximize their potential in your projects.

Removing all blank lines from a file is done with the g/^$/d command. Every line, even if it contains no text, has a beginning and an end. Therefore, lines consisting solely of a beginning and an end are classified as blank. This command allows you to effectively remove unnecessary blank lines from a file, which improves its structure and readability.

If your file contains lines containing only spaces, tabs, or other minor whitespace characters, you can use the :g/^\s*$/d command. Here, \s stands for whitespace. Basically, this command allows you to remove all lines that contain only whitespace characters between the beginning and end of the line, including cases where there are no whitespace characters at all. The asterisk (*) in this context indicates the possibility of any number of whitespace characters, including zero. This command is a useful tool for cleaning files of unnecessary blank lines, which helps improve the readability and structure of your text.

For this case, there is an alternative method. You can use the command :v/\S/d. Here, \S stands for any character except spaces, and :v is an analog of the g command, but with an inverted regular expression. This approach can be useful for working with simple regular expressions.

Working with Vim Windows

In previous articles, we discussed commands and methods for managing windows in Vim, including opening files in the current and new windows, as well as arranging them in both horizontal and vertical formats. In this section, we'll look at additional features for effectively managing windows in Vim, which will improve your productivity and make working with text easier.

The default keyboard shortcut for switching to an adjacent window is Ctrl + W, followed by the direction you want to move. For example, pressing Ctrl + W followed by «L» will switch to the window located to the right. This feature simplifies navigation between windows and increases work efficiency.

Moving to the right windowScreenshot: Skillbox Media

Please note that for To navigate in a direction, you need to press the Ctrl and W keys simultaneously. This process may seem inconvenient, so we recommend referring to the previous lesson, in which we looked at setting up a Ctrl and arrow key combination for navigation. This will significantly simplify your work and increase task efficiency.

The "split" command opens a new window with a horizontal split. This is convenient for working with multiple files or terminals simultaneously, ensuring efficient use of screen space. Horizontal splitting allows you to visually organize information and simplify multitasking, which is especially useful for developers, system administrators, and users working with the command line. Using this command helps improve productivity and optimize your workflow.

Opening a new window with horizontal split Screenshot: Skillbox Media

By default, the element will be placed Below the current browser window.

The "vsplit" command creates a new vertically split window in the text editor. This allows users to work on multiple files or parts of a single file simultaneously, improving workflow. Vertically splitting the screen helps organize your workspace, providing easy access to the resources you need. Use the vsplit command to increase your productivity and manage tasks effectively.

Opening a new window with a vertical split. Screenshot: Skillbox Media

By default, a new window will open on the right. It is important to note that if a file is already open in the current window, that file will also be available when you open a new window.

By default, new windows in most software split the screen space in half, both vertically and horizontally. However, there is a set of commands that allow you to resize the window. These commands provide flexibility in customizing the workspace, which can significantly improve work efficiency. The ability to resize windows helps users organize their workspace in a way that is most convenient for completing tasks.

The keyboard shortcut Ctrl + W 10 increases the window height by 10 lines, while Ctrl + W 10 decreases its height by 10 lines. These commands are useful for users who need to quickly adjust the window size, ensuring a comfortable viewing of content. Using these keyboard shortcuts significantly simplifies navigation and window management, which is especially useful when working with text editors and productivity-intensive programs. Ctrl + W expands the active window to its maximum height while leaving a single row for all other open windows. This is a convenient way to optimize screen space and improve visibility while working with applications. Using this combination, you can effectively manage windows, providing convenient access to the information you need.

Increasing the height of the current window to the maximumScreenshot: Skillbox Media

This command is useful if you need to temporarily increase the amount of displayable content in the current file. After you finish working with the enlarged view, you can return all windows to their default size using the keyboard shortcut Ctrl + w.

Return to standard window sizesScreenshot: Skillbox Media

To increase the window width by one character, use the keyboard shortcut Ctrl + w >. To decrease the width, use Ctrl + w <. If you want to change the number of characters by which the window width will be changed, add the desired number to the specified combinations. For example, Ctrl + w 10 > will increase the window by 10 characters. We recommend setting the window width in accordance with the maximum line length of your code, which in the case of Ruby projects is usually 80 or 120 characters. Properly setting the window width makes it easier to work with code and improves readability.

To maximize the window width, you need to use the keyboard shortcut Ctrl + W. This command allows you to quickly resize the window, providing a more comfortable view of the content. Effective use of the keyboard can significantly increase your productivity and simplify interaction with the interface.

Most of the functions we have listed can also be implemented in Vim using a mouse, if one is connected. However, in my opinion, using a mouse for window management can be distracting. By mastering these commands, you'll learn to use screen space effectively, optimizing every detail rather than simply resizing windows as you see fit.

One of the main advantages of the Vim editor is the ability to bind all the necessary keyboard shortcuts to a single command. This allows you to open the desired number of windows when starting the editor or configure different settings for different projects. Over time, such settings will become familiar, and you won't perceive them as something complicated. In the next lesson, we'll explore one of Vim's most impressive features: macros, which will significantly simplify your work.

Macros

Macros are a powerful tool that is often overlooked by beginners not only in Vim, but also in other programming languages, as well as in Excel and various software products. This is a shame, because using macros significantly simplifies the workflow. Instead of wasting time on routine tasks, you can set up macros that automate repetitive actions. This allows you to focus on more important aspects of your work and improve overall productivity. Mastering macros opens new opportunities to optimize processes and reduce the time spent on tasks.

Vim provides an excellent opportunity to automate repetitive actions using macros. This is especially useful when working with text files, such as CSV, where you need to perform repetitive operations. For example, in lesson seven about visual mode, we looked at a CSV file containing user data. Before deleting columns, users had to select them manually. Using macros can significantly simplify this process, saving time and minimizing the likelihood of errors. Setting up macros in Vim opens up new horizons for efficient data management.

Manual Sunset. Deleting columns in Vim visual mode. Screenshot: Skillbox Media. Let's look at an example of a CSV file containing 10,000 rows. Each row contains a last name, initials, phone numbers, and unique identifiers (UUIDs). Such a file can be useful for storing and processing large amounts of data, providing easy access to user information. The CSV format allows you to easily import and export data between different systems, making it ideal for working with large amounts of information.
A Lifetime of CSV Screenshot: Skillbox Media

Let's say we need to transfer data from a CSV file to the Ruby console in array-of-array format. Several transformations need to be performed: periods should be added after the initials, the digit 8 in all phone numbers should be replaced with +7, and each line should be enclosed in quotation marks, as this is the Ruby standard. This will allow the data to be processed correctly and avoid possible errors when using it later.

It is possible to write a Ruby script using a complex replace command via the command line that will collect data from the CSV and perform all the necessary operations. However, if you want to simplify the task, you can use macros. Macros allow you to automate processes and significantly speed up working with data, eliminating the need to manually perform routine operations. Using macros will not only save you time but also increase the efficiency of information processing.

Go to the first line of code and press Shift + o to open edit mode. Enter the opening square bracket, as this is how arrays are denoted in Ruby. This bracket will be the beginning of your main array.

Macro: beginningScreenshot: Skillbox Media

In command mode, we can go to the next line. To start recording a macro, you must type the q command followed by the character that represents the macro name, such as a. You can choose any other name for your macro.

Going to the macroScreenshot: Skillbox Media

Let's consider what actions the macro will need to perform. The lines in the CSV file are separated by commas, and these are what we'll be using for reference. First, you need to add the first quotation mark before the username. This will allow you to correctly process data when importing or exporting it.

Screenshot: Skillbox Media

To find a space in the text, use the f command, after Instead, we enter a space. This will allow us to quickly find all occurrences of the space character in a document. This method is effective for editing and analyzing text, significantly speeding up the process of working with content. This command is useful for both programmers and editors, enabling precise searches for specific symbols in large volumes of information.

Screenshot: Skillbox Media

We can use the w key to move forward one word, but this will cause the macro to work incorrectly with double last names, as they are considered two separate words. Therefore, we need to move to a space and move forward one character to place a period after the first initial, and then place a period after the second initial. Next, use the f command to move to the first comma.

Screenshot: Skillbox Media

Close the quotation mark for the username and move on to number 8 on the keyboard of mobile phones.

Screenshot: Skillbox Media

Press the key combination "s" + 7, where "s" is the first letter in entering a phone number as a string.

Screenshot: Skillbox Media

When entering commands, do not forget to press Esc to return to command mode. This is important because the macro stores information about mode transitions. To quickly jump to the end of text on a phone, use the w command, since in this case we assume there are no separators in the text.

Screenshot: Skillbox Media

We set the second quotation mark for the phone, then move on to the comma. First, put the first quotation mark, then press Esc and simultaneously Shift + A to insert the last quotation mark, closing the square bracket and comma.

Screenshot: Skillbox Media

Continuing from where we started recording the macro.

Screenshot: Skillbox Media

It's important for the macro to automatically move to the next line after each entry. This may require multiple steps. If you make a mistake during the process, don't worry; in some cases, you can make corrections. Macros can also make mistakes and correct their actions. With experience, you'll learn to recognize when it's time to correct macro errors and when it's best to start over. To run a macro, use the @a command, where @ stands for macro invocation and a is the name of your macro.

Screenshot: Skillbox Media

Macro applied once. To terminate its execution on the entire file, use the 10000@a command. This command will repeat the macro action until the end of the document, providing more efficient editing and text processing.

Screenshot: Skillbox Media

The magic is that All changes made after running the macro for 10,000 times can be easily undone with a single press of the 'u' key. This makes working with macros more convenient and safe, allowing users to experiment without fear of losing data.

Screenshot: Skillbox Media

There are many Simple macro applications, especially when dealing with long lines of code. For example, if a function call contains too many arguments, the line can become unreadable. In such cases, it's helpful to organize the arguments into columns. This will improve the readability of the code and make it easier to maintain. Using macros in such situations helps optimize the structure of the code, making it more understandable and convenient to work with.

Screenshot: Skillbox Media

Some programming languages Code formatting plugins can perform certain tasks automatically. However, if such a function is missing, you can create a macro to solve the problem. Macros automate repetitive actions, simplifying the coding process and increasing productivity. Creating a macro is an easy way to ensure proper formatting and compliance with project requirements, which is especially important for keeping your code clean and readable.

Screenshot: Skillbox Media
Screenshot: Skillbox Media
Screenshot: Skillbox Media
Screenshot: Skillbox Media
Screenshot: Skillbox Media

Repeat it eight times.

Screenshot: Skillbox Media
Screenshot: Skillbox Media
Screenshot: Skillbox Media

Macros are a powerful tool that allows you to effectively modify both source code and text files containing large amounts of data. Using macros significantly speeds up the process of editing and automating tasks, which is especially useful when working with large projects or databases. They allow you to quickly make changes, making your work more productive and less time-consuming.

In the next lesson, we'll look at the infrastructure associated with the Vim editor. We'll discuss the main tools and plugins that can improve the performance and functionality of Vim. We'll also learn how to properly configure the environment for effective development and optimize your workflow.

Reading is an important part of our lives. It not only develops thinking, but also enriches vocabulary, improves concentration, and promotes emotional development. In today's world, where information is available in vast quantities, reading books, articles, and other materials helps you identify key points and form your own opinion. Choosing the right literature can significantly improve the quality of your reading and broaden your horizons. Don't forget to take the time to read every day to gain new knowledge and inspiration.

  • Turning Vim into a full-fledged Python IDE
  • The best motivation to go into IT is the lack of a stable income
  • Who is a DevOps engineer: a programmer, a system administrator, or all at once