I added an option for modifying the behaviour of the macro. But as far as I observed, "14-15" is a common format for index page numbers.
Code: Select all
### Bind Numbers ###
# Works on selection(s). If there is no selection, the whole document will be processed.
# This macro converts selected text(s) such as
# 125, 44, 12, 35, 521, 9, 41, 124, 334, 42, 78, 5, 123, 335, 23, 1, 15, 31, 81, 4, 14, 43, 333, 3
# into
# 1, 3-5, 9, 12, 14-15, 23, 31, 35, 41-44, 78, 81, 123-125, 333-335, 521
# or
# 1, 3-5, 9, 12, 14, 15, 23, 31, 35, 41-44, 78, 81, 123-125, 333-335, 521
# If $sepJustTwoNums is set to true, "14" and "15" will be "14, 15".
# If it is set to false, "14" and "15" will be "14-15".
# You can customize separator (', ' in the example above) and joiner ('-' in the example above)
# by modifying the definition of $separator = $sep and $joiner near the beginning of the macro.
$sepJustTwoNums = true
$separator = $sep = '.'
$joiner = '-'
Require Application Version '3.1'
$doc = Document.active
$sel = TextSelection.active
if ! $sel.length
Select All Document
end
if $sepJustTwoNums == true
$min = 3
else
$min = 2
end
$spChars = Hash.new '$', '\$', '(', '\(', ')', '\)', '*', '\*', '+', '\+', '.', '\.', '?', '\?', '\\', '\x5C', '^', '\^', '{', '\{', '|', '\|', '}', '\}', '[', '\[', ']', '\]'
$range = Range.new 0, $sep.length
$sep.transliterateInRange $range, $spChars
$findExp = '[0-9]+(?:' & $sep
$findExp &= '[0-9]+)+'
$numFound = Find All $findExp, 'Es'
if ! $numFound
Exit 'Nothing found, exit...'
end
$selections = $doc.textSelections
foreach $sel in reversed $selections
$numbers = $sel.subtext
$numbers = $numbers.split $separator
$numbers.sort 'n'
$converted = Array.new
$continuous = false
$baseNum = $last = $numbers.firstValue
$numGroups = Hash.new
$numGroups{$baseNum} = Array.new $baseNum
foreach $n in $numbers
$diff = $n - $last
if $diff > 1
$numGroups{$n} = Array.new $n
$baseNum = $n
elsif $diff == 1
$numGroups{$baseNum}.appendValue $n
end
$last = $n
end
$baseNumbers = $numGroups.keys
$baseNumbers.sort 'n'
foreach $i in $baseNumbers
$nums = $numGroups{$i}
if $nums.count >= $min
$value = $nums.firstValue & $joiner
$value &= $nums.lastValue
else
$value = $nums.join $separator
end
$converted.appendValue $value
end
$converted = $converted.join $separator
$converted = Cast to String $converted
$sel.text.replaceInRange $sel.range, $converted
end
### end of macro ###