Find Terms with Line Numbers

Get help using and writing Nisus Writer Pro macros.
Post Reply
Posts: 92
Joined: 2007-11-09 15:27:25

Find Terms with Line Numbers

Post by jb »

I’ve got several documents, each with about 1000 lines (poetry). I also have a list of about 25 words I’m interested in finding and listing with corresponding line numbers. I do know how to find those words, and for the time being I’ve styled them (Bold) so that they stand out to the eye.

But I'd like a list of each found word with the line numbers where it appears. Like so:

apple: 23, 77, 758
orange: 326, 445
pear: 89, 976

Any help appreciated.

User avatar
Posts: 1166
Joined: 2007-02-07 00:58:12
Location: Japan

Re: Find Terms with Line Numbers

Post by phspaelti »

Hello James,

I'm assuming that by line numbers you mean the line numbers provided by Nisus. Here is some code that will do that. To run this code, put the find expression in the find dialog, and then run the macro:

Code: Select all

# Find with Line Numbers
$doc =

# Get the find expression from the Find dialog and collect the search hits
$findExp = Read Find Expression
$finds = $doc.text.findAll $findExp, '*', '-am'

# Loop through all the search hits
$results =
foreach $find in $finds
    # Combine each hit with the line number
    $results.push $find.substring & ': ' & $find.text.lineNumberAtIndex($find.location)

# Sort the results

# Output the results in a new document
Document.newWithText $results.join("\n")
Find with Line Numbers.nwm
(3.92 KiB) Downloaded 439 times
Now this macro is very 'bare bones' and will put each word on a separate line followed by the line number, which means it will give:
apple: 23
apple: 77
apple: 758
orange: 326
orange: 445

You can of course just use Find/Replace to reshape this to the output you want.
To do it directly, the above code could be changed as follows:
  • Change the results array to a hash with the found words as keys, and the values being arrays of line numbers
  • While looping add the line numbers to the hash value array that has the word as key
  • Add another loop, which goes through the word/keys in order and combines each array of line numbers to a comma list
Here the macro with those changes:
Find with Line Numbers (comma list).nwm
(4.03 KiB) Downloaded 440 times

Posts: 92
Joined: 2007-11-09 15:27:25

Re: Find Terms with Line Numbers

Post by jb »

Thank you, Philip.
This is perfect, and of course the second macro is what I really want. So an extra Thank You for that.

I keep telling myself that one day I will study some of the macros you've made (for me) and learn to make them myself, but it seems that there is always just enough mysterious magic that I stumble. I will try again ;-)

Thanks much,

Post Reply