Further examination shows the problem isn't related to the order of bookmarks but because the code previously works from top to bottom.
Changing this
for (const [index, bookmark] of bookmarks.entries()) {
// code
}
to this
for (const [index, bookmark] of bookmarks.reverse().entries()) {
// code
}
solves the problem.
It's worth to note that when working with Position
it's a good idea to always work from bottom to top, for good reasons.
==============
As for the order problem, I've created an example in github to workaround this issue.
The idea is to define the order yourself.
const config = [
{
imageName: 'Figure 1',
bookmarkId: 'id.wglkb02zor96'
},
{
imageName: 'Figure 2',
bookmarkId: 'id.ifl1btgwoni'
},
{
imageName: 'Figure 3',
bookmarkId: 'kix.jithfpq0bbwm'
}
];
Then use that order to work the bookmarks.
const docsId = '...';
const docs = DocumentApp.openById(docsId);
const doc = docs.getTabs()[0];
const bookmarks = doc.asDocumentTab().getBookmarks();
const bookmarkOrder = config.map(item => item.bookmarkId);
bookmarks.sort((a, b) => { // order bookmarks using config
const indexA = bookmarkOrder.indexOf(a.getId());
const indexB = bookmarkOrder.indexOf(b.getId());
return indexA - indexB;
});
Alas, it's a shame that an important feature like bookmark is not well-behaved.