Talk:Python as a macro language

From Apache OpenOffice Wiki
Revision as of 04:48, 9 June 2007 by Jza (Talk | contribs)

Jump to: navigation, search

I would like to improve some info on this page, but i have never edited a wiki before, so i'm discussing it here first.

Recently it took me 3 whole days to discover some very simple facts about writing a python macro, because they are not clear in the documentation.
Also, some things seem to have changed since the documentation was written.

Here is the information that i want to convey:

To write a simple macro:

  • in Python
  • stored in the document
  • called from a toolbar button (not a dialog)

this is what you need to know, that is different from the existing documentation:

  • your function must accept an argument
  • it does not need to import uno or unohelper (or anything at all)
  • you do not have to modify manifest.xml, it's done automatically

and this is what you need to know, that is hard discover in the existing documentation:
(it's there, but in a different context, so it's hard to know the relevance of it when you first see it)

Within your function, to get to the UNO API,
(like "ThisDocument" and "StarDesktop" in OO Basic)
use XSCRIPTCONTEXT, like this:
this_doc = XSCRIPTCONTEXT.getDocument()
desktop = XSCRIPTCONTEXT.getDesktop()

Code example:

def test_toolbar_button( *tpl_args ):
	"""Test of basic text insertion;
	prints whatever args are passed to this function."""

	this_doc = XSCRIPTCONTEXT.getDocument()
	doc_text = this_doc.Text
	cursor = text.createTextCursor()

	s_text_1 = 'These arguments were passed:\n%r\n\n' % ( tpl_args, )
	doc_text.insertString( cursor, s_text_1, 0 )

	return 0

The following aspects of the task were easy enough to understand from the documentation:

  • putting the script file into the document (unzip/zip)
  • making a toolbar button and connecting it to the function

Why was it so hard to find the clue about XSCRIPTCONTEXT?

The clue is given in HelloWorldPython(), but that example

  • is given in a context other than embedding in a document
  • does not run, so i ignored it. (it does not run because it does not accept an argument)

The example that is given in the context of embedding in the document (push_me_python4.odt) does not use XSCRIPTCONTEXT. (It runs from a dialog, so it gets an 'event' instance passed to it, and gets context from that; so this example is no use if you want to run from a toolbar button.)

I'm thinking of writing a separate page about "Simple Python macro", and linking to it from 'Python_as_a_macro_language'.

jim_hill_au 14:30, 8 June 2007 (CEST)

Contribute to the python samples

I would like if you help me build the Python-UNO page, I already have quite a bit, you might want to check one of the latest page I have been working at which are the Python_samples which is the ones that are included in the OOo distribution.

Personal tools