//DESCRIPTION: re-range page numbers
/*-----------------------------------------------------------------
Expand page ranges, sort, and do page ranges again
These formats are handled:
Leech, G., 1, 2, 3, 4, 6, 8, 9, 10, 15, 18, 20, 21, 22, 23
Leech, Geoff, 1, 2, 3, 4, 6, 8, 9, 10, 15, 18, 20, 21, 22, 23
Leech, G.\u20021, 2, 3, 4, 6, 8, 9, 10, 15, 18, 20, 21, 22, 23
Leech, Geoff\u20021, 2, 3, 4, 6, 8, 9, 10, 15, 18, 20, 21, 22, 23
span = 1: ‘1, 2, 3, 4, 6’ > ‘1-4, 6’
span = 2: ‘1, 2, 3, 4, 6’ > ‘1-6’
etc.
---------------------------------------------------------------------*/
span = 1
switch( app.selection[0].constructor.name )
{
case "TextFrame" : doStory(); break;
case "InsertionPoint" : doParagraph(); break;
default : errorM( "Select a text frame\ror an insertion point" )
}
function doStory()
{
var par = app.selection[0].parentStory.contents.split("\r");
for( var i = 0; i < par.length; i++ )
par[i] = oneLine( par[i] );
app.selection[0].parentStory.contents = par.join("\r")
}
function doParagraph()
{
var par = app.selection[0].paragraphs[0].contents.split("\r")[0];
app.selection[0].paragraphs[0].contents = oneLine( par ) + "\r"
}
function oneLine( p )
{
p = p.replace( /(\d+)\u2013(\d+)/g, expandNum );
//separate entry from the pages. Separation is: period or
//word character, perhaps followed by comma, followed by white space
p = p.replace( /([\.\w],?\s)(\d)(.+)\b/g, compressPages )
//alert(p); exit()
return p
}
function expandNum()
{
//alert(arguments[1]+"|"+arguments[2]);
var exp = "";
var start = +arguments[1];
var stop = +arguments[2];
for( var i = start; i < stop; i++ )
exp += i + ", ";
exp += stop;
return exp
}
function compressPages()
{
return arguments[1] + indexCompress(
(arguments[2]+arguments[3]).split(", ") )
}
function indexCompress( array )
{
array.sort( sortNum );
//arrayCompress( array )
var i = 0;
var j = 0; while( i < array.length )
{
j = i;
while( ( array[j+1] - +array[j] <= span ) && ( j < array.length ) )
j++;
if( j - i > 1 )
{
array[i] += "\u2013" + array[j ];
array.splice( i+1 , (j-i) )
}
i++;
}
return array.join(", ")
}
function sortNum( a, b )
{
return a - b
}
function errorM( m )
{
alert( m );
exit()
}