Thursday, May 12, 2022

Update Block of Codes with VIM

Recently I have been working on my iOS app project. One thing I need to do is to update several blocks of codes in a code file. The update is to add directives #if...#endif to the matched block of codes. Those blocks of codes have very similar pattern:

  1. private func configureSearchControllerDelegates(_ sc: UISearchController)
  2. {
  3.    log.logMessage() {
  4.        return "configureSearchControllerDelegates"
  5.    }
  6.  ....
  7. }

The first thing is to find the matched block of codes. Use the following command:


Here is the explaination

\( and \) is for grouping. Starting from spaces \s and then log.logMessage(), followed by many spaces till the char of {. After that many lines of any chars till the char of }. \_. is for multiple lines, and {-} for none-greedy match(matches 0 or more of the preceding atom, as few as possible).

In VIM, the matched codes are marked as red.

With above verification, it is time to add my desired directive codes around the matched block of codes. Here is the replacement command.

:%s/(\s*log.logMessage()\s*{\_.\{-}}\)/#if D_1\r\1\r#endif/

Here is the explaination

Replacing the matched codes: insert #if D_1 as the first line, then the matched codes as group by\1. Finally add the last line of #endif after the matched codes. \r is a line break.

Here is the replacement command in VIM:

and wallah is the result: