Vijay Dev
Vijay Dev

Reputation: 27486

Vim - Deleting XML Comments

How do I delete comments in XML?

If the opening and the closing comment tags are on the same line, I use :g/^<!--.*-->$/d to delete the comment. How to delete the comments that are spread across many lines?

Upvotes: 8

Views: 2297

Answers (5)

Rob Wells
Rob Wells

Reputation: 37133

G'day,

Doesn't entering

da>

delete the comment when the cursor is placed somewhere within the comment block?

You have to have a vim with textobjects enabled at compile time. Entering:

:vers

will let you see if textobjects are enabled in your build.

There's a lot of these funky text selections. Have a look at the relevant page in the docs.

Edit: You might have to add

set matchpairs+=<:>

to your .vimrc for this to work.

HTH

cheers,

Upvotes: 2

Kaivosukeltaja
Kaivosukeltaja

Reputation: 15735

I believe this should work:

:g/<!--.*?-->/d

The question mark makes the asterisk "lazy" instead of "greedy", meaning it will match as little as possible to satisfy the expression. This prevents the expression from removing the middle part of this example:

We want to keep this<!-- This is a comment -->We also want to keep this<!-- Another comment -->

EDIT: Looks like the vim flavor of regex doesn't support *? lazy matching. My bad.

Upvotes: 0

fengb
fengb

Reputation: 1488

\_. instead of . allows matching on all characters including newlines. But that alone will cause the regex engine to go overboard since regexes are greedy by default. Use \{-} instead of * for a non-greedy match all.

Since the g/ /d command only deletes a single line (even for a multiline match), it would be preferable to switch to s/ / /g (substitute global).

:%s/<!--\_.\{-}-->//g

Upvotes: 19

ghostdog74
ghostdog74

Reputation: 342619

if its not too much of a hassle and you have gawk on your system. you can try this

$ more file
<!--
asdlfj
sdjf
;jsgsdgjasl -->
text i want
i want
....
<!-- junk junk -->
i want text
anthor text
end

$ gawk -vRS='-->' '{ gsub(/<!--.*/,"")}1' file


text i want
i want
....


i want text
anthor text
end

Upvotes: 0

Dave
Dave

Reputation: 5173

You should use XSLT to transform the file to a new file. You use the identity transform with an additional rule to not copy over the comments.

<xsl:template match="node()|@*">
   <xsl:copy>
     <xsl:apply-templates select="@*"/>
     <xsl:apply-templates/>
   </xsl:copy>
 </xsl:template>

<xsl:template match="comment()"/>

You can use "xsltproc" in the libxslt package on Linux to do this as a script which I imagine you can execute from vim.

Upvotes: 2

Related Questions