Mimsy Were the Borogoves

Hacks: Articles about programming in Python, Perl, PHP, and whatever else I happen to feel like hacking at.

Renumber selected lines of text

Jerry Stratton, December 16, 2016

I use this script extensively with as a service in the Services menu, to, as the title says, renumber lines. It’s extremely simple, and that means it can renumber across multiple lines:

1.	Do this.
	Explanation of doing this.
1.	Do that.
	Explanation of doing that.
1.	And maybe do this other thing.
	Explanation of why I might want to.

The script looks for numbers at the beginning of lines, and that’s it. It allows for tabs and spaces preceding the number, and remembers the first one when it modifies the counter. On subsequent lines, it only modifies the line if the leader matches and is followed by a number.

[toggle code]

  • #!/usr/bin/perl
  • $counter = 0;
  • while (<>) {
    • if (/^([\t ]*)([0-9]+)/) {
      • if ($counter == 0) {
        • $leader = $1;
        • $counter = $2;
      • }
      • $counter++ if s/^$leader[0-9]+/$leader$counter/;
    • }
    • print;
  • }

The first time it encounters a number, it uses that number as the starting point. Subsequent numbers will increment from this number.

It handles only flat lists, because that’s all I’ve ever needed. However, because it checks the spaces and tabs in front of the first selected number, it will not harm indented lists.

I use it mainly (a) when I insert a new item among existing items, and (b) when I re-order items, putting the numbers out of whack.

The easiest way to set it up is using Automator. From the Utilities library, choose Run Shell Script and put the full path to the script into the text box, as pictured. Remember to ensure that the script gets its input from “stdin”. You may also have to check the box that reads “Output replaces selected text”.

1.	Do this.
	Explanation of doing this.
2.	Do that.
	Explanation of doing that.
3.	And maybe do this other thing.
	Explanation of why I might want to.

Whatever you name the Service when you File:Save will be the name of the Service in the Services menu.

Once the script is ready, all I need to do is select the lines I want renumbered, and choose (in my case) Renumber Text Lines from the Services menu of the app.

  1. <- Poster pixel sizes