Jun 19, 2009

Fixing Sequential Numbers

The code at the end of this article is a simplified example of script for Illustrator CSx that fixes sequential numbers.

"Simplified" means that this script supposes:
  1. There is a opened document.
  2. There're 2 or more objects in the selection of the active document.
  3. All the objects in the selection are text objects.
  4. The contents of the first and last objects are numbers.
If there is something out of these conditions, the script just stops with an error dialog.
But it is preferable to add some codes for checking the conditions and showing more comprehensible dialogs for general users who aren't familiar with JavaScript on errors.
// fixes sequential numbers
var sel = activeDocument.selection;
var num_to = sel[0].contents - 0;
var num_from = sel[ sel.length - 1 ].contents - 0;

var unit = (num_to - num_from) / (sel.length - 1);

var digit = 0;
if( sel[0].contents.match(/\.(\d+)/) ){
digit = RegExp.$1.length;

for(var i = 1; i < sel.length; i++){
sel[i].contents = (num_to - unit * i).toFixed(digit);


  1. would love to use this - but copying your steps above gives me the error 'typeError: cannot read property '0' from undefined'

    Additionally - I'd like to have a sequence from 0001 to 0025. Any thoughts?

  2. Please make sure to select whole text objects before run the script. If you got the error even if you did so, please let me know the version of AI you use, and the numbers you selected. If you use CS4, it may need to modify "activeDocument" to "app.activeDocument".

    I'll write a script that make a 0001-0025 sequence after this problem is fixed.

  3. Hi Hiroyuki!

    Using CS4 so I updated to reflect app.activeDocument but it now gives another error: Type Error: Cannot read property "selection" from undefined.

    I did a simple test of four digits - 0 is the first and 3 is the last.

    ideally it'd most be used for counting in 10s, or 20s etc.

    so like 0, 10, 20, 30, 40
    and 0, 20, 40, 60, 80, 100

    but with zero leaders like:
    000, 020, 030, 040, 060

    not sure if that would work but it'd be great!

  4. Hi jayse,
    I don't have CS4, so I can't test the script with it. But I found a expression "app.activeDocument.selection" in a sample code in AI CS4 JavaScript reference PDF.
    So the error message you encountered is mysterious...

    Anyway, I wrote a script that supports zero leaders. Here is a url for download. I hope it works.


  5. Hiroyuki you did it! Works perfectly~! I'm just getting into scripting for AI so this helps a ton to see what you did and how you coded it. Thanks a mega-ton!

  6. The script in my above message has moved to the following address.


Note: Only a member of this blog may post a comment.