1

How can I change the following LaTeX coding:

\cite{1,3-7,9} 

to

\cite{1,3,4,5,6,7,9}  

in vim? I would prefer to use regular expressions.

3
  • You mean replace it?
    – Braiam
    Commented Aug 24, 2014 at 13:53
  • yes . i want to replace it by regular expression
    – Indian
    Commented Aug 24, 2014 at 13:57
  • @sam And you also want it to work on other ranges I suppose? I am not sure if you can do that by using just regular expressions. I think you need a more sophisticated function.
    – Bernhard
    Commented Aug 25, 2014 at 5:36

4 Answers 4

3

You can use vim's substitute command to accomplish this:

:%s/\\cite{1,3-7,9}/\\cite{1,3,4,5,6,7,9}/g  

This will replace all occurrences of \cite{1,3-7,9} with \cite{1,3,4,5,6,7,9}.

To replace only occurrences that exist on the current line you can use:

:s/\\cite{1,3-7,9}/\\cite{1,3,4,5,6,7,9}/g 

Append c if you want vim to ask for confirmation before changing any lines. For example:

:%s/\\cite{1,3-7,9}/\\cite{1,3,4,5,6,7,9}/gc  
5
  • I'm sure he didn't mean the literal \cite{1,3-7,9} but anything that matched \d-\d
    – Braiam
    Commented Aug 26, 2014 at 15:42
  • @Braiam You mean simply expand 3-7?
    – Seth
    Commented Aug 26, 2014 at 19:21
  • Yeah, if it's 2-5 and 7-10 he wants to expand them too, not just the static 3-7.
    – Braiam
    Commented Aug 26, 2014 at 21:21
  • yeah exactly. Braiam said it
    – Indian
    Commented Aug 28, 2014 at 1:52
  • @sam Then I recommend editing your question to clarify that, and checking out Ingo Karkat's answer.
    – Seth
    Commented Aug 30, 2014 at 18:05
2

To expand any single instance of a range of the form m-n within a \cite{...} expression, you could perhaps do something like

 perl -pe 's/\\cite{(?:\d+,)*\K(\d+)-(\d+)(?=(?:,\d+)*})/sprintf "%s", join(",", ($1..$2))/e' file.tex
1

With my PatternsOnText plugin, you can restrict :substitute commands to pattern matches (\cite{...} in your case):

:%SubstituteInSearch/\\cite{[^}]\+}/\(\d\+\)-\(\d\+\)/\=join(range(submatch(1),submatch(2)), ',')/g

The regular expression parses the start and end numbers, and transforms them into the number range via join() and range(), using :help sub-replace-expr.

3
  • But its is not working in vim
    – Indian
    Commented Sep 2, 2014 at 3:47
  • "SubstituteInSearch" command not found
    – Indian
    Commented Sep 2, 2014 at 3:47
  • @sam Then the plugin (and its dependencies) hasn't been properly installed. Commented Sep 2, 2014 at 6:18
0

Often vim comes with Perl linked.

The possibility of using perl (or similar) in Vim, may by relevant.

When you have +perl, you can use :perldo + @steeldriver solution (in fact a slightly variation):

:perldo s/\\cite{(?:\d+,)*\K(\d+)-(\d+)(?=(,.*?)?})/sprintf "%s",join(",", $1..$2)/e

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .