On Jun 27, 2010, at 6:46 PM, Hamid Haji wrote:
> It is possible to have a NWP macro which can merge two index files created
> in NWP?
>
> Index file 1:
> apples 1, 3, 10, 30
> bananas 3, 6, 10
>
> Index file 2:
> apples 31, 33, 40, 43
> bananas 33, 36, 41
>
> Merged file:
> apples 1, 3, 10, 30-31, 33, 40, 43
> bananas 3, 6, 10, 33, 36, 41
Here is a macro for that. Before running it, you have to change the character "Before Page Number" in your index files from space to tab or something unique, i.e. never used in entries nor in Page Number Separator. The language of the caret in the active document is used to determine the sort order. Sub-entries are not supported.
Kino
--
$numberOfIndexFiles = 2
$BeforePageNumber = Cast to String "\t"
$PageNumberSeparator = Cast to String ', '
$PageNumberRangeMark = Cast to String '-'
$docs = Document.openDocuments
if $docs.count < $numberOfIndexFiles
exit "The macro requires $numberOfIndexFiles index files, exiting..."
else
$message = 'Generate an index file merging: '
$i = 0
while $i < $numberOfIndexFiles
$message &= $docs[$i].displayName
$i += 1
if $i < $numberOfIndexFiles
$message &= $PageNumberSeparator
end
end
Prompt $message
end
$sel = TextSelection.active
$lang = $sel.displayTypingAttributes.language
$findExp = '^[^' & "$BeforePageNumber]+"
$findExp &= $BeforePageNumber & "\\d+(?:$PageNumberRangeMark\\d+)?(?:$PageNumberSeparator\\d+(?:$PageNumberRangeMark\\d+)?){0,}\$"
$data = Hash.new
$i = 0
while $i < $numberOfIndexFiles
$sels = $docs[$i].text.findAll $findExp, 'E', '-am'
foreach $sel in $sels
$item = $sel.subtext.split $BeforePageNumber
if $data{$item.firstValue} == undefined
$data{$item.firstValue} = Hash.new
end
$pages = $item.lastValue.split $PageNumberSeparator
foreach $page in $pages
if $page.rangeOfString $PageNumberRangeMark, 's'
$PageNumbers = $page.split $PageNumberRangeMark
$p = $PageNumbers.firstValue
while $p <= $PageNumbers.lastValue
$data{$item[0]}{$p} = true
$p += 1
end
else
$data{$item[0]}{$page} = true
end
end
end
$i += 1
end
$words = $data.keys
$words.sort 'li', $lang
$output = Array.new
foreach $word in $words
$temp = $word & $BeforePageNumber
$pages = $data{$word}.keys
$pages.sort
$continuous = $rangeStart = false
$max = undefined
foreach $i, $page in reversed $pages
if $i == 0
if $continuous == true
$rangeStart = true
end
else
$diff = $page - $pages[$i-1]
if $diff == 1
if $max == undefined
$max = $page
end
$continuous = true
$pages.removeValueAtIndex $i
else
if $continuous == true
$continuous = false
$rangeStart = true
end
end
end
if $rangeStart == true
$value = $page & $PageNumberRangeMark
$value &= $max
$pages.setValueAtIndex $value, $i
$continuous = $rangeStart = false
$max = undefined
end
end
$temp &= $pages.join $PageNumberSeparator
$output.appendValue $temp
end
$LF = Cast to String "\n"
$output = $output.join $LF
Document.newWithText $output
# end
|