I managed to solve this both in Apple Script and Javascript.
Now I get the Heading 1 in the parentheses.
This is the Applescript version:
on performSmartRule(theRecords)
tell application id "DNtp"
repeat with theRecord in theRecords
if (type of theRecord as string) = "markdown" then
-- Only process Markdown docs
set newText to {}
-- Set up an empty list to push the paragraphs into)
set currentText to (plain text of theRecord)
-- Get the current text of the document
set titleText to (characters 3 thru -1 of paragraph 1 of currentText as string) -- Cache all but the control characters in a variable
repeat with thisLine in (paragraphs of currentText)
-- Loop through the document, paragraph by paragraph
if thisLine begins with "##" then
-- If this is an H2 page link
set cachedText to (characters 4 thru -1 of thisLine as string) -- Cache all but the control characters in a variable
else if thisLine begins with "* " then
-- If it's just a bulleted paragraph
copy ((characters 3 thru -1 of thisLine as string) & " (" & (titleText) & ": " & (cachedText) & ") " & return) to end of newText
-- Get all but the control characters and concatenate the cachedText.
-- Then push it to the newText list
else
copy thisLine & return to end of newText
-- Anything else, including the H1 line at the top, just push into the newText list
end if
end repeat
set plain text of theRecord to (newText as string)
-- Set the text of the document to the new text
end if
end repeat
end tell
end performSmartRule