Reputation: 23
Question: how to read the heading reference (of the form #heading=h.12345) in a google docs doc?
Background: Would like to use cross-references within doc. Example.
1.1 Chapter 1 (i.e. paragraph has heading DocumentApp.ParagraphHeading.HEADING1)
Sample text. For more, see chapter 1.2.
1.2 Chapter 2
Sample text. For more, see chapter 1.1.
Now, google docs can do cross-references (insert link), but are "normal" links and do not carry the chapter number.
Thus, approach would be to: - insert links for cross-references
with apps script, build index of heading references and chapter numbers
also with apps script, update see chapter texts based on their link
I looked at getLinkUrl without success:
var links = [];
var ps = DocumentApp.getActiveDocument().getBody().getParagraphs();
for(var i = 0; i < ps.length; i++) {
var h = ps[i].getHeading();
if( h == DocumentApp.ParagraphHeading.HEADING1 ) {
var t = ps[i].editAsText();
var u = t.getLinkUrl();
}
}
Is it possible to read the heading reference at all?
Upvotes: 2
Views: 2886
Reputation: 560
Here is your code (modified slightly) to detect HEADING1 assuming there is only one instance. It can be adapted to detect other heading types and multiple occurrences.
function get_some_heading() {
var ps = DocumentApp.getActiveDocument().getBody()
var searchType = DocumentApp.ElementType.PARAGRAPH;
var searchHeading = DocumentApp.ParagraphHeading.HEADING1;
var searchResult = null;
while (searchResult = ps.findElement(searchType, searchResult)) {
var par = searchResult.getElement().asParagraph();
if (par.getHeading() == searchHeading) {
// Found one, update Logger.log and stop.
var h = searchResult.getElement().asText().getText();
return h;
}
}
//return null or something
}
Here is the enum Paragraph Heading reference and here is the search pattern reference used above (for a slightly different use case).
Upvotes: 1
Reputation: 45750
Is it possible to read the heading reference at all?
Absolutely, at least from the Table of Contents. Those references are in the attributes
of the TOC entries. You can see an example, with a script, in this answer.
Upvotes: 1