summaryrefslogtreecommitdiff
path: root/scripting
diff options
context:
space:
mode:
authorKevin Suo <suokunlong@126.com>2020-10-10 14:43:55 +0800
committerThorsten Behrens <Thorsten.Behrens@CIB.de>2020-10-10 14:11:27 +0200
commit5fb0e0f68bc9d37d43e0782b903919630852904c (patch)
tree68e8d8500db4dec3deb7ba20dcf0aaea6f09d580 /scripting
parent3f425069fc31bd6bac86d98312631321d0ff591f (diff)
Improve example python code in scripting.
* Modified the code to be more pythonic. * If "len(theString) == 0", then "not theString" evaluates to True. * "theString[0].isupper()" and "theString[1].isupper()" can be combined. * Remove unused imported string module * Wrap long lines * run autopep8 to prettify * ... Change-Id: Ic8aaa0728a43936cd4c6e1ed590e01ba8f0fbf5b Reviewed-on: https://gerrit.libreoffice.org/c/core/+/104136 Tested-by: Jenkins Reviewed-by: Thorsten Behrens <Thorsten.Behrens@CIB.de>
Diffstat (limited to 'scripting')
-rw-r--r--scripting/Package_ScriptsPython.mk2
-rw-r--r--scripting/examples/python/Capitalise.py102
-rw-r--r--scripting/examples/python/HelloWorld.py25
-rw-r--r--scripting/examples/python/InsertText.py46
-rw-r--r--scripting/examples/python/NamedRanges.py7
-rw-r--r--scripting/examples/python/SetCellColor.py27
-rw-r--r--scripting/examples/python/TableSample.py131
-rw-r--r--scripting/examples/python/pythonSamples/TableSample.py116
8 files changed, 264 insertions, 192 deletions
diff --git a/scripting/Package_ScriptsPython.mk b/scripting/Package_ScriptsPython.mk
index 0c48839ca42d..9d401d38349b 100644
--- a/scripting/Package_ScriptsPython.mk
+++ b/scripting/Package_ScriptsPython.mk
@@ -15,7 +15,7 @@ $(eval $(call gb_Package_add_files_with_dir,scripting_ScriptsPython,$(LIBO_SHARE
python/InsertText.py \
python/NamedRanges.py \
python/SetCellColor.py \
- python/pythonSamples/TableSample.py \
+ python/TableSample.py \
))
# vim: set noet sw=4 ts=4:
diff --git a/scripting/examples/python/Capitalise.py b/scripting/examples/python/Capitalise.py
index 05e82a37ad32..64d29a51343a 100644
--- a/scripting/examples/python/Capitalise.py
+++ b/scripting/examples/python/Capitalise.py
@@ -16,61 +16,77 @@
# the License at http://www.apache.org/licenses/LICENSE-2.0 .
#
-# helper function
-def getNewString( theString ) :
- if( not theString or len(theString) ==0) :
+def getNewString(theString):
+ """helper function
+ """
+ if (not theString):
return ""
+
# should we tokenize on "."?
- if theString[0].isupper() and len(theString)>=2 and theString[1].isupper() :
- # first two chars are UC => first UC, rest LC
- newString=theString[0:1].upper() + theString[1:].lower();
+ if len(theString) >= 2 and theString[:2].isupper():
+ # first two chars are UC => first UC, rest LC
+ newString = theString[0].upper() + theString[1:].lower()
+
elif theString[0].isupper():
- # first char UC => all to LC
- newString=theString.lower()
- else: # all to UC.
- newString=theString.upper()
- return newString;
+ # first char UC => all to LC
+ newString = theString.lower()
+
+ else:
+ # all to UC.
+ newString = theString.upper()
-def capitalisePython( ):
- """Change the case of a selection, or current word from upper case, to first char upper case, to all lower case to upper case..."""
- import string
+ return newString
+
+def capitalisePython():
+ """Change the case of the selected or current word(s).
+ If at least the first two characters are "UPpercase, then it is changed
+ to first char "Uppercase".
+ If the first character is "Uppercase", then it is changed to
+ all "lowercase".
+ Otherwise, all are changed to "UPPERCASE".
+ """
# The context variable is of type XScriptContext and is available to
# all BeanShell scripts executed by the Script Framework
xModel = XSCRIPTCONTEXT.getDocument()
- #the writer controller impl supports the css.view.XSelectionSupplier interface
+ # the writer controller impl supports the css.view.XSelectionSupplier
+ # interface
xSelectionSupplier = xModel.getCurrentController()
- #see section 7.5.1 of developers' guide
+ # see section 7.5.1 of developers' guide
xIndexAccess = xSelectionSupplier.getSelection()
- count = xIndexAccess.getCount();
- if(count>=1): #ie we have a selection
- i=0
- while i < count :
- xTextRange = xIndexAccess.getByIndex(i);
- #print "string: " + xTextRange.getString();
- theString = xTextRange.getString();
- if len(theString)==0 :
- # sadly we can have a selection where nothing is selected
- # in this case we get the XWordCursor and make a selection!
- xText = xTextRange.getText();
- xWordCursor = xText.createTextCursorByRange(xTextRange);
- if not xWordCursor.isStartOfWord():
- xWordCursor.gotoStartOfWord(False);
- xWordCursor.gotoNextWord(True);
- theString = xWordCursor.getString();
- newString = getNewString(theString);
- if newString :
- xWordCursor.setString(newString);
- xSelectionSupplier.select(xWordCursor);
- else :
-
- newString = getNewString( theString );
- if newString:
- xTextRange.setString(newString);
- xSelectionSupplier.select(xTextRange);
- i+= 1
+ count = xIndexAccess.getCount()
+
+ if(count >= 1): # ie we have a selection
+ i = 0
+
+ while i < count:
+ xTextRange = xIndexAccess.getByIndex(i)
+ theString = xTextRange.getString()
+ # print("theString")
+ if len(theString) == 0:
+ # sadly we can have a selection where nothing is selected
+ # in this case we get the XWordCursor and make a selection!
+ xText = xTextRange.getText()
+ xWordCursor = xText.createTextCursorByRange(xTextRange)
+
+ if not xWordCursor.isStartOfWord():
+ xWordCursor.gotoStartOfWord(False)
+
+ xWordCursor.gotoNextWord(True)
+ theString = xWordCursor.getString()
+ newString = getNewString(theString)
+
+ if newString:
+ xWordCursor.setString(newString)
+ xSelectionSupplier.select(xWordCursor)
+ else:
+ newString = getNewString(theString)
+ if newString:
+ xTextRange.setString(newString)
+ xSelectionSupplier.select(xTextRange)
+ i += 1
# lists the scripts, that shall be visible inside OOo. Can be omitted, if
diff --git a/scripting/examples/python/HelloWorld.py b/scripting/examples/python/HelloWorld.py
index 8c3c9a8141d2..ed21b200845b 100644
--- a/scripting/examples/python/HelloWorld.py
+++ b/scripting/examples/python/HelloWorld.py
@@ -18,21 +18,30 @@
# the License at http://www.apache.org/licenses/LICENSE-2.0 .
#
-def HelloWorldPython( ):
- """Prints the string 'Hello World(in Python)' into the current document"""
-#get the doc from the scripting context which is made available to all scripts
+def HelloWorldPython():
+ """Prints the string 'Hello World (in Python)' into the current document.
+ """
+
+ # Get the doc from the scripting context which is made available to all
+ # scripts.
desktop = XSCRIPTCONTEXT.getDesktop()
model = desktop.getCurrentComponent()
-#check whether there's already an opened document. Otherwise, create a new one
+
+ # Check whether there's already an opened document.
+ # Otherwise, create a new one
if not hasattr(model, "Text"):
model = desktop.loadComponentFromURL(
- "private:factory/swriter","_blank", 0, () )
-#get the XText interface
+ "private:factory/swriter", "_blank", 0, ())
+
+ # get the XText interface
text = model.Text
-#create an XTextRange at the end of the document
+
+ # create an XTextRange at the end of the document
tRange = text.End
-#and set the string
+
+ # and set the string
tRange.String = "Hello World (in Python)"
+
return None
# vim: set shiftwidth=4 softtabstop=4 expandtab:
diff --git a/scripting/examples/python/InsertText.py b/scripting/examples/python/InsertText.py
index e04874d52b0a..801b8190860a 100644
--- a/scripting/examples/python/InsertText.py
+++ b/scripting/examples/python/InsertText.py
@@ -1,4 +1,4 @@
-# HelloWorld python script for the scripting framework
+# Example python script for the scripting framework
#
# This file is part of the LibreOffice project.
@@ -20,9 +20,11 @@
def InsertText(text):
"""Inserts the argument string into the current document.
- If there is a selection, the selection is replaced by it."""
+ If there is a selection, the selection is replaced by it.
+ """
- # Get the doc from the scripting context which is made available to all scripts
+ # Get the doc from the scripting context which is made available to
+ # all scripts.
desktop = XSCRIPTCONTEXT.getDesktop()
model = desktop.getCurrentComponent()
@@ -34,28 +36,30 @@ def InsertText(text):
# all BeanShell scripts executed by the Script Framework
xModel = XSCRIPTCONTEXT.getDocument()
- #the writer controller impl supports the css.view.XSelectionSupplier interface
+ # The writer controller impl supports the css.view.XSelectionSupplier
+ # interface.
xSelectionSupplier = xModel.getCurrentController()
- #see section 7.5.1 of developers' guide
+ # See section 7.5.1 of developers' guide
xIndexAccess = xSelectionSupplier.getSelection()
- count = xIndexAccess.getCount();
- if count >= 1: #ie we have a selection
+ count = xIndexAccess.getCount()
+
+ if count >= 1: # ie we have a selection
i = 0
while i < count:
- xTextRange = xIndexAccess.getByIndex(i);
- theString = xTextRange.getString();
- if not len(theString):
- # Nothing really selected; just insert.
- xText = xTextRange.getText();
- xWordCursor = xText.createTextCursorByRange(xTextRange);
- xWordCursor.setString(text);
- xSelectionSupplier.select(xWordCursor);
- else:
- # Replace the selection.
- xTextRange.setString(text);
- xSelectionSupplier.select(xTextRange);
-
- i += 1
+ xTextRange = xIndexAccess.getByIndex(i)
+ theString = xTextRange.getString()
+
+ if not len(theString):
+ # Nothing really selected, just insert.
+ xText = xTextRange.getText()
+ xWordCursor = xText.createTextCursorByRange(xTextRange)
+ xWordCursor.setString(text)
+ xSelectionSupplier.select(xWordCursor)
+ else:
+ # Replace the selection.
+ xTextRange.setString(text)
+ xSelectionSupplier.select(xTextRange)
+ i += 1
diff --git a/scripting/examples/python/NamedRanges.py b/scripting/examples/python/NamedRanges.py
index 34307ae8440c..0e47cb406745 100644
--- a/scripting/examples/python/NamedRanges.py
+++ b/scripting/examples/python/NamedRanges.py
@@ -10,6 +10,7 @@
import traceback
import uno
+
def GetNamedRanges():
"""Returns a list of the named ranges in the document.
"""
@@ -28,6 +29,7 @@ def GetNamedRanges():
traceback.print_tb(tb)
return None
+
def DefineNamedRange(sheet, x0, y0, width, height, name):
"""Defines a new (or replaces an existing) named range on a sheet,
using zero-based absolute coordinates
@@ -37,7 +39,9 @@ def DefineNamedRange(sheet, x0, y0, width, height, name):
# FIXME: Is there some Python-callable API to turn a row and column into an A1 string?
# This obviously works only for the first 26 columns.
abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
- content = "$" + sheet + "." + "$" + abc[x0 : x0+1] + "$" + str(y0+1) + ":" + "$" + abc[x0+width-1 : x0+width] + "$" + str(y0+height)
+ content = "$" + sheet + "." + "$" + \
+ abc[x0: x0+1] + "$" + str(y0+1) + ":" + "$" + abc[x0+width -
+ 1: x0+width] + "$" + str(y0+height)
position = uno.createUnoStruct('com.sun.star.table.CellAddress')
position.Sheet = 0
position.Column = 0
@@ -45,6 +49,7 @@ def DefineNamedRange(sheet, x0, y0, width, height, name):
model.NamedRanges.addNewByName(name, content, position, 0)
return None
+
def DeleteNamedRange(name):
try:
desktop = XSCRIPTCONTEXT.getDesktop()
diff --git a/scripting/examples/python/SetCellColor.py b/scripting/examples/python/SetCellColor.py
index 743a6daa948b..4229d9914f6a 100644
--- a/scripting/examples/python/SetCellColor.py
+++ b/scripting/examples/python/SetCellColor.py
@@ -1,15 +1,38 @@
+#
+# This file is part of the LibreOffice project.
+#
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+#
+# This file incorporates work covered by the following license notice:
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed
+# with this work for additional information regarding copyright
+# ownership. The ASF licenses this file to you under the Apache
+# License, Version 2.0 (the "License"); you may not use this file
+# except in compliance with the License. You may obtain a copy of
+# the License at http://www.apache.org/licenses/LICENSE-2.0 .
+#
+
def SetCellColor(x, y, color):
"""Sets the background of the cell at (x,y) (zero-based column and row
indices, for example (2,3) == C4) on the first sheet and
returns the contents of the cell as a string.
"""
- #get the doc from the scripting context which is made available to all scripts
+ # Get the doc from the scripting context which is made available to
+ # all scripts.
desktop = XSCRIPTCONTEXT.getDesktop()
model = desktop.getCurrentComponent()
- #check whether there's already an opened document
+
+ # Check whether there's already an opened document.
if not hasattr(model, "Sheets"):
return ""
+
sheet = model.Sheets.Sheet1
cell = sheet.getCellByPosition(x, y)
+
cell.CellBackColor = color
+
return cell.String
diff --git a/scripting/examples/python/TableSample.py b/scripting/examples/python/TableSample.py
new file mode 100644
index 000000000000..0920bf8ad021
--- /dev/null
+++ b/scripting/examples/python/TableSample.py
@@ -0,0 +1,131 @@
+#
+# This file is part of the LibreOffice project.
+#
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+#
+# This file incorporates work covered by the following license notice:
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed
+# with this work for additional information regarding copyright
+# ownership. The ASF licenses this file to you under the Apache
+# License, Version 2.0 (the "License"); you may not use this file
+# except in compliance with the License. You may obtain a copy of
+# the License at http://www.apache.org/licenses/LICENSE-2.0 .
+#
+
+import uno
+
+# a UNO struct later needed to create a document
+from com.sun.star.text.ControlCharacter import PARAGRAPH_BREAK
+from com.sun.star.text.TextContentAnchorType import AS_CHARACTER
+from com.sun.star.awt import Size
+
+
+def insertTextIntoCell(table, cellName, text, color):
+ tableText = table.getCellByName(cellName)
+ cursor = tableText.createTextCursor()
+
+ cursor.setPropertyValue("CharColor", color)
+ tableText.setString(text)
+
+
+def createTable():
+ """Creates a new writer document and inserts a table with some data
+ (also known as the SWriter sample).
+ """
+ ctx = uno.getComponentContext()
+ smgr = ctx.ServiceManager
+ desktop = smgr.createInstanceWithContext("com.sun.star.frame.Desktop", ctx)
+
+ # open a writer document
+ doc = desktop.loadComponentFromURL(
+ "private:factory/swriter", "_blank", 0, ())
+
+ text = doc.Text
+ cursor = text.createTextCursor()
+ text.insertString(
+ cursor,
+ "The first line in the newly created text document.\n",
+ 0)
+ text.insertString(
+ cursor,
+ "Now we are in the second line\n",
+ 0)
+
+ # create a text table
+ table = doc.createInstance("com.sun.star.text.TextTable")
+
+ # with 4 rows and 4 columns
+ table.initialize(4, 4)
+
+ text.insertTextContent(cursor, table, 0)
+ rows = table.Rows
+
+ table.setPropertyValue("BackTransparent", uno.Bool(0))
+ table.setPropertyValue("BackColor", 13421823)
+ row = rows.getByIndex(0)
+ row.setPropertyValue("BackTransparent", uno.Bool(0))
+ row.setPropertyValue("BackColor", 6710932)
+
+ textColor = 16777215
+
+ insertTextIntoCell(table, "A1", "FirstColumn", textColor)
+ insertTextIntoCell(table, "B1", "SecondColumn", textColor)
+ insertTextIntoCell(table, "C1", "ThirdColumn", textColor)
+ insertTextIntoCell(table, "D1", "SUM", textColor)
+
+ table.getCellByName("A2").setValue(22.5)
+ table.getCellByName("B2").setValue(5615.3)
+ table.getCellByName("C2").setValue(-2315.7)
+ table.getCellByName("D2").setFormula("sum <A2:C2>")
+
+ table.getCellByName("A3").setValue(21.5)
+ table.getCellByName("B3").setValue(615.3)
+ table.getCellByName("C3").setValue(-315.7)
+ table.getCellByName("D3").setFormula("sum <A3:C3>")
+
+ table.getCellByName("A4").setValue(121.5)
+ table.getCellByName("B4").setValue(-615.3)
+ table.getCellByName("C4").setValue(415.7)
+ table.getCellByName("D4").setFormula("sum <A4:C4>")
+
+ cursor.setPropertyValue("CharColor", 255)
+ cursor.setPropertyValue("CharShadowed", uno.Bool(1))
+
+ text.insertControlCharacter(cursor, PARAGRAPH_BREAK, 0)
+ text.insertString(
+ cursor,
+ "This is a colored Text - blue with shadow\n",
+ 0)
+ text.insertControlCharacter(cursor, PARAGRAPH_BREAK, 0)
+
+ textFrame = doc.createInstance("com.sun.star.text.TextFrame")
+ textFrame.setSize(Size(15000, 400))
+ textFrame.setPropertyValue("AnchorType", AS_CHARACTER)
+
+ text.insertTextContent(cursor, textFrame, 0)
+
+ textInTextFrame = textFrame.getText()
+ cursorInTextFrame = textInTextFrame.createTextCursor()
+ textInTextFrame.insertString(
+ cursorInTextFrame,
+ "The first line in the newly created text frame.",
+ 0)
+ textInTextFrame.insertString(
+ cursorInTextFrame,
+ "\nWith this second line the height of the rame raises.",
+ 0)
+ text.insertControlCharacter(cursor, PARAGRAPH_BREAK, 0)
+
+ cursor.setPropertyValue("CharColor", 65536)
+ cursor.setPropertyValue("CharShadowed", uno.Bool(0))
+
+ text.insertString(cursor, "That's all for now !!", 0)
+
+
+g_exportedScripts = createTable,
+
+# vim: set shiftwidth=4 softtabstop=4 expandtab:
diff --git a/scripting/examples/python/pythonSamples/TableSample.py b/scripting/examples/python/pythonSamples/TableSample.py
deleted file mode 100644
index a92c862c2674..000000000000
--- a/scripting/examples/python/pythonSamples/TableSample.py
+++ /dev/null
@@ -1,116 +0,0 @@
-#
-# This file is part of the LibreOffice project.
-#
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-#
-# This file incorporates work covered by the following license notice:
-#
-# Licensed to the Apache Software Foundation (ASF) under one or more
-# contributor license agreements. See the NOTICE file distributed
-# with this work for additional information regarding copyright
-# ownership. The ASF licenses this file to you under the Apache
-# License, Version 2.0 (the "License"); you may not use this file
-# except in compliance with the License. You may obtain a copy of
-# the License at http://www.apache.org/licenses/LICENSE-2.0 .
-#
-
-import uno
-
-# a UNO struct later needed to create a document
-from com.sun.star.text.ControlCharacter import PARAGRAPH_BREAK
-from com.sun.star.text.TextContentAnchorType import AS_CHARACTER
-from com.sun.star.awt import Size
-
-from com.sun.star.lang import XMain
-
-def insertTextIntoCell( table, cellName, text, color ):
- tableText = table.getCellByName( cellName )
- cursor = tableText.createTextCursor()
- cursor.setPropertyValue( "CharColor", color )
- tableText.setString( text )
-
-
-def createTable():
- """creates a new writer document and inserts a table with some data (also known as the SWriter sample)"""
- ctx = uno.getComponentContext()
- smgr = ctx.ServiceManager
- desktop = smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",ctx)
-
- # open a writer document
- doc = desktop.loadComponentFromURL( "private:factory/swriter","_blank", 0, () )
-
- text = doc.Text
- cursor = text.createTextCursor()
- text.insertString( cursor, "The first line in the newly created text document.\n", 0 )
- text.insertString( cursor, "Now we are in the second line\n" , 0 )
-
- # create a text table
- table = doc.createInstance( "com.sun.star.text.TextTable" )
-
- # with 4 rows and 4 columns
- table.initialize( 4,4)
-
- text.insertTextContent( cursor, table, 0 )
- rows = table.Rows
-
- table.setPropertyValue( "BackTransparent", uno.Bool(0) )
- table.setPropertyValue( "BackColor", 13421823 )
- row = rows.getByIndex(0)
- row.setPropertyValue( "BackTransparent", uno.Bool(0) )
- row.setPropertyValue( "BackColor", 6710932 )
-
- textColor = 16777215
-
- insertTextIntoCell( table, "A1", "FirstColumn", textColor )
- insertTextIntoCell( table, "B1", "SecondColumn", textColor )
- insertTextIntoCell( table, "C1", "ThirdColumn", textColor )
- insertTextIntoCell( table, "D1", "SUM", textColor )
-
- values = ( (22.5,21.5,121.5),
- (5615.3,615.3,-615.3),
- (-2315.7,315.7,415.7) )
- table.getCellByName("A2").setValue(22.5)
- table.getCellByName("B2").setValue(5615.3)
- table.getCellByName("C2").setValue(-2315.7)
- table.getCellByName("D2").setFormula("sum <A2:C2>")
-
- table.getCellByName("A3").setValue(21.5)
- table.getCellByName("B3").setValue(615.3)
- table.getCellByName("C3").setValue(-315.7)
- table.getCellByName("D3").setFormula("sum <A3:C3>")
-
- table.getCellByName("A4").setValue(121.5)
- table.getCellByName("B4").setValue(-615.3)
- table.getCellByName("C4").setValue(415.7)
- table.getCellByName("D4").setFormula("sum <A4:C4>")
-
-
- cursor.setPropertyValue( "CharColor", 255 )
- cursor.setPropertyValue( "CharShadowed", uno.Bool(1) )
-
- text.insertControlCharacter( cursor, PARAGRAPH_BREAK, 0 )
- text.insertString( cursor, " This is a colored Text - blue with shadow\n" , 0 )
- text.insertControlCharacter( cursor, PARAGRAPH_BREAK, 0 )
-
- textFrame = doc.createInstance( "com.sun.star.text.TextFrame" )
- textFrame.setSize( Size(15000,400))
- textFrame.setPropertyValue( "AnchorType" , AS_CHARACTER )
-
- text.insertTextContent( cursor, textFrame, 0 )
-
- textInTextFrame = textFrame.getText()
- cursorInTextFrame = textInTextFrame.createTextCursor()
- textInTextFrame.insertString( cursorInTextFrame, "The first line in the newly created text frame.", 0 )
- textInTextFrame.insertString( cursorInTextFrame, "\nWith this second line the height of the rame raises.",0)
- text.insertControlCharacter( cursor, PARAGRAPH_BREAK, 0 )
-
- cursor.setPropertyValue( "CharColor", 65536 )
- cursor.setPropertyValue( "CharShadowed", uno.Bool(0) )
-
- text.insertString( cursor, " That's all for now !!" , 0 )
-
-g_exportedScripts = createTable,
-
-# vim: set shiftwidth=4 softtabstop=4 expandtab: