Using Xdotool to type in a Libreoffice Document

I have often wondered how to automate libreoffice by using xdotool. I know that the window has to be selected out of the window stack, and I tried programming it as a window bash variable under xdotool in the bash script. I then tried sending the next keypress to the window but to no result. Right now I want to pass the ctrl+N command to the libre office window to open a new document.

#!/bin/bash
/usr/bin/libreoffice
mywindow=$(xdotool search --class libreoffice)
xdotool windowactivate $mywindow && xdotool key --window $mywindow Next
xdotool key ctrl+n

I do get an error code

There are no windows in the stack.
Invalid window '%1'
Usage: windowactivate [options] [window=%1]
--sync - only exit once window is active (is visible + active)
If no window is given, %1 is used. See WINDOW STACK in xdotool(1)

Solution 1:

  • To more selectively find a LibreOffice Writer window (and e.g. not a Calc window), use this: mywindow=$(xdotool search --class libreoffice-writer). You can see the class of open windows with the command wmctrl -lx. This lists the more generic classname and the more specific class, separated by a dot. For libreoffice, it is libreoffice.libreoffice-writer.
  • Beware: the xdotool search command will retrieve all windows of a certain class. Thus, with multiple windows, the variable will contain multiple identifiers separated by a space, e.g. 66167017 65540686. windowactivate, however, only supports a single argument.
  • After executing the libreoffice command, the process will fork to the background. No window is created yet. That is why winactivate fails. Use the --sync option to have the winactivate command wait for the window to be effectively created: mywindow=$(xdotool search --sync --class libreoffice.writer)

Solution 2:

A simple workaround would be putting LO in background, then add delay between the xdotool command.

#!/bin/bash
/usr/bin/libreoffice &
sleep 10
mywindow=$(xdotool search --class libreoffice)
xdotool windowactivate $mywindow && xdotool key --window $mywindow Next
xdotool key ctrl+n