Update TOC via command line

Hi! Is there a way to update a document’s TOC via command line?

Reason: I’m generating an ODT via Pandoc which has a TOC, but unfortunately Pandoc only creates the TOC configuration and place, leaving it blank. As only LibreOffice has power to generate a proper TOC, it would be wonderful to make it via command line.

Updating ToC considered editing. There are legitimate use cases where edits in document should not result in ToC updates, and thus any such update should be done explicitly (by user or by macro; there’s tdf#44448 to allow autoupdate).

Command line does not edit documents; it may print them, or convert (and do everything it can to keep data and formatting intact, i.e. avoid edits). So no, it’s not possible simply with command line.

You may consider creating a macro to update indices, and calling it from command line.

Thank you! I’ll search for how to make such macro, and how to call it from command line.

On Update Toc with LibreOffice Command, there is a working solution (Many thanks to ChanMo!!!)

Create a macro module in libreoffice or add the following code in an existing module (eg. “Standard.Module1”).

REM  *****  BASIC  *****

 Option Explicit

 Sub UpdateIndexes(path As String)
     '''Update indexes, such as for the table of contents''' 
     Dim doc As Object
     Dim args()

     doc = StarDesktop.loadComponentFromUrl(convertToUrl(path), "_default", 0, args())

     Dim i As Integer

     With doc ' Only process Writer documents
	 If .supportsService("com.sun.star.text.GenericTextDocument") Then
	     For i = 0 To .getDocumentIndexes().count - 1
		 .getDocumentIndexes().getByIndex(i).update()
	     Next i
	 End If
     End With ' ThisComponent

     doc.store()
     doc.close(True)

 End Sub ' UpdateIndexes  

Save the module and run the macro on your file with this command line:
soffice --headless "macro:///Standard.Module1.UpdateIndexes(/path/to/file.odt)"

Done!

Note: Here, we suppose that the macro is in the module “Standard/Module1”. Change the path if necessary.

1 Like