Vim: Automatic way to reformat and repeat comments?

I have documentation in the code that I would like to format:

# book_id - integer # chapter_id - integer (Optional) # relative_url - Text: the url of the screencast file on S3, relative to the book url # view_count - integer 

I installed Tabular.vim, which makes me so far away:

 # book_id - integer # chapter_id - integer (Optional) # relative_url - Text: the url of the screencast file on S3, relative to the book url # view_count - integer 

I would like some kind of automated way to generate such code. That is, wrapped in 79 characters, indented if you continue the line from the previous comment. I get the following:

 # book_id - integer # chapter_id - integer (Optional) # relative_url - Text: the url of the screencast file on S3, relative to the # book url # view_count - integer 

What I'm looking for is:

 # book_id - integer # chapter_id - integer (Optional) # relative_url - Text: the url of the screencast file on S3, relative to the # book url # view_count - integer 

Can this be done using an existing plugin sequence or hotkey? I know about gq , which reformats the text to the width of the character set in vim, but does not add indentation in things like comments.

+4
source share
2 answers

You can use the parameter formatlistpat ( :set fo+=n needed to work):

1. delete #

 :%s/^# // 

2. install flp option

 :setl flp=^[^-]*-\\s 

3. make formatting

gggqG

4. preend #

 :%s/^/# / 

You can also use the indentexpr option:

2a. set inde option

 :setl inde=15 

2b. insert blank lines

 :g/^/pu_ 

5. delete empty comments

 :g/^# $/d 
+5
source

Perhaps the easiest way to automate arbitrary tasks like these is with records. With recording, you can record any commands that you used first when you correct documentation, and then repeat them very easily.

For example, assuming that the specified documentation is at the beginning of the file:

First use set textwidth=79 so that Vim knows the maximum number of characters per line. Then:

  • Press qq to start recording
  • Press gg to go to the beginning of the file
  • Press gq} to reformat the documentation block.
  • Click :Tabularize - to use your plugin
  • Press :bnext to go to the next buffer
  • Press q to stop recording.

Now, if you click 1000@q , the entry will be repeated for all buffers opened in vim. You can also just press @q whenever you want to execute it for the current file. Take a look at :help gq and :help q for more information.

0
source

Source: https://habr.com/ru/post/1436693/


All Articles