4

This might be more of a bash question than vim, but I thought I should start here. Frequently when editing code, it would be "nice" to copy and paste the directory structure into a text editor. For example:

I have the following directory structure:

img/foo.jpg
img/foo2.jpg
img/Another_foo.jpg

I'm editing a file with the following code:

<img src="img/foo.jpg">
<img src="img/foo2.jpg">
<img src="img/Another_foo.jpg">

I add more files to the img directory so that it looks like this:

img/foo.jpg
img/foo2.jpg
img/Another_foo.jpg
img/bar.gif
img/bar2.jpg
img/Another_bar.png

In graphical editing environments, I would just copy and paste the filenames into the file and quickly get this:

<img src="img/foo.jpg">
<img src="img/foo2.jpg">
<img src="img/Another_foo.jpg">
<img src="img/bar.gif">
<img src="img/bar2.jpg">
<img src="img/Another_bar.png">

(For larger filesets, I hack my way through by pasting the directory structure into Excel and then concatenating the code for each line).

Is there an easily-reproducible way to do something similar with vim?

1 Answer 1

5

First step, insert the file listing:

:r!ls

Second step, turn each line into an HTML tag:

:'[,s/.*/<img src="&">

See :help :r, :help range, :help mark-motions, and :help :s.

3
  • 2
    You can use :r!find some_dir -type f for a recursive listing (you can optionally add -maxdepth to only find files up to a certain depth). Jan 19, 2016 at 17:49
  • As a side note, if you're not into substitutions, you could mark your filenames in vim in blockwise visual mode (<Ctrl>-v), and then type I<img src= to insert at the beginning of all lines. This does not work properly for A (it will fill up with whitespaces), but you could use gv to reselect, then type :'<,'> normal A"> to append "> to all lines (you could have done it that way in the first step, using normal I instead of normal A). Jan 21, 2016 at 7:55
  • In addition to @PhilippFrank 's comment, you can append to the end of every line by selecting the region and calling :right, followed by blockwise selection and A">. The answer is much nicer though
    – Steve
    Jan 21, 2016 at 16:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.