ScriptForge.Basic service

The ScriptForge.Basic service proposes a collection of LibreOffice Basic methods to be executed in a Python context. Basic service methods reproduce the exact syntax and behaviour of Basic builtin functions.

Typical example:


   bas.MsgBox('Display this text in a message box from a Python script')
  
warning

ScriptForge.Basic service is limited to Python scripts.


Service invocation

Before using the Basic service, import the CreateScriptService() method from the scriptforge module:


    from scriptforge import CreateScriptService
    bas = CreateScriptService("Basic")
  

Properties

Name

ReadOnly

Type

Beschreibung

MB_OK, MB_OKCANCEL, MB_RETRYCANCEL, MB_YESNO, MB_YESNOCANCEL

Yes

Integer

Values: 0, 1, 5, 4, 3

MB_ICONEXCLAMATION, MB_ICONINFORMATION, MB_ICONQUESTION, MB_ICONSTOP

Yes

Integer

Values: 48, 64, 32, 16

MB_ABORTRETRYIGNORE, MB_DEFBUTTON1, MB_DEFBUTTON2, MB_DEFBUTTON3

Yes

Integer

Values: 2, 128, 256, 512

IDABORT, IDCANCEL, IDIGNORE, IDNO, IDOK, IDRETRY, IDYES

Yes

Integer

Values: 3, 2, 5, 7, 1, 4, 6
Constants indicating MsgBox selected button.

StarDesktop

Yes

UNO
object

StarDesktop object represents LibreOffice Start Center.


List of Methods in the Basic Service

CDate
CDateFromUnoDateTime
CDateToUnoDateTime
ConvertFromUrl
ConvertToUrl
CreateUnoService
DateAdd
DateDiff
DatePart

DateValue
Format
GetDefaultContext
GetGuiType
GetPathSeparator
GetSystemTicks
GlobalScope.BasicLibraries
GlobalScope.DialogLibraries
InputBox

MsgBox
Now
RGB
ThisComponent
ThisDatabaseDocument
Xray




CDate

Converts a numeric expression or a string to a datetime.datetime Python native object.

note

This method exposes the Basic builtin function CDate to Python scripts.


Syntax:

svc.CDate(expression: any): obj

Parameter:

expression: a numeric expression or a string representing a date.

Wenn Sie eine Zeichenkette konvertieren, müssen Datum und Uhrzeit entweder in einem der für Ihre Gebietsschema-Einstellung definierten Datum-Annahmemuster eingegeben werden (siehe – Spracheinstellungen – Sprachen) oder im ISO-Datumsformat (momentan wird nur das ISO-Format mit Bindestrichen akzeptiert, beispielsweise "2012-12-31"). In numerischen Ausdrücken stehen die Werte links von der Dezimalstelle für das Datum ab dem 31. Dezember 1899. Die Werte rechts von der Dezimalstelle stehen für die Uhrzeit.

Beispiel:


    d = bas.CDate(1000.25)
    bas.MsgBox(str(d)) # 1902-09-26 06:00:00
    bas.MsgBox(d.year) # 1902
  

CDateFromUnoDateTime

Converts a UNO date/time representation to a datetime.datetime Python native object.

Syntax:

svc.CDateFromUnoDateTime(unodate: uno): obj

Parameter:

unodate: A UNO date/time object of one of the following types: com.sun.star.util.DateTime, com.sun.star.util.Date or com.sun.star.util.Time

Beispiel:

The following example creates a com.sun.star.util.DateTime object and converts it to a datetime.datetime Python object.


    import uno
    uno_date = uno.createUnoStruct('com.sun.star.util.DateTime')
    uno_date.Year = 1983
    uno_date.Month = 2
    uno_date.Day = 23
    new_date = bas.CDateFromUnoDateTime(uno_date)
    bas.MsgBox(str(new_date)) # 1983-02-23 00:00:00
  

CDateToUnoDateTime

Converts a date representation into a com.sun.star.util.DateTime object.

Syntax:

svc.CDateToUnoDateTime(date: obj): uno

Parameter:

date: A Python date/time object of one of the following types: datetime.datetime, datetime.date, datetime.time, float (time.time) or time.struct_time.

Beispiel:


    from datetime import datetime
    current_datetime = datetime.now()
    uno_date = bas.CDateToUnoDateTime(current_datetime)
    bas.MsgBox(str(uno_date.Year) + "-" + str(uno_date.Month) + "-" + str(uno_date.Day))
  

ConvertFromUrl

Returns a system path file name for the given file: URL.

Syntax:

svc.ConvertFromUrl(url: str): str

Parameter:

url: An absolute file: URL.

Rückgabewert:

A system path file name.

Beispiel:


    filename = bas.ConvertFromUrl( "file:///C:/Program%20Files%20(x86)/LibreOffice/News.txt")
    bas.MsgBox(filename)
  

ConvertToUrl

Returns a file: URL for the given system path.

Syntax:

svc.ConvertToUrl(systempath: str): str

Parameter:

systempath: A system file name as a string.

Rückgabewert:

A file: URL as a string.

Beispiel:


    url = bas.ConvertToUrl( 'C:\Program Files(x86)\LibreOffice\News.txt')
    bas.MsgBox(url)
  

CreateUnoService

Instantiates a UNO service with the ProcessServiceManager.

Syntax:

svc.CreateUnoService(servicename: str): uno

Parameter:

servicename: A fully qualified service name such as com.sun.star.ui.dialogs.FilePicker or com.sun.star.sheet.FunctionAccess.

Beispiel:


    dsk = bas.CreateUnoService('com.sun.star.frame.Desktop')
  

DateAdd

Adds a date or time interval to a given date/time a number of times and returns the resulting date.

Syntax:

svc.DateAdd(interval: str, number: num, date: datetime): datetime

Parameter:

interval: A string expression from the following table, specifying the date or time interval.

interval (string value)

Erklärung

yyyy

Jahr

q

Quartal

m

Monat

y

Kalendertag

w

Wochentag

ww

Kalenderwoche

d

Tag

h

Stunde

n

Minute

s

Sekunde


number: A numerical expression specifying how often the interval value will be added when positive or subtracted when negative.

date: A given datetime.datetime value, the interval value will be added number times to this datetime.datetime value.

Rückgabewert:

A datetime.datetime value.

Beispiel:


    dt = datetime.datetime(2004, 1, 31)
    dt = bas.DateAdd("m", 1, dt)
    print(dt)
  

DateDiff

Returns the number of date or time intervals between two given date/time values.

Syntax:

svc.DateDiff(interval: str, date1: datetime, date2: datetime, firstdayofweek = 1, firstweekofyear = 1): int

Parameter:

interval: A string expression specifying the date interval, as detailed in above DateAdd method.

date1, date2: The two datetime.datetime values to be compared.

firstdayofweek: An optional parameter that specifies the starting day of a week.

firstdayofweek value

Erklärung

0

Systemvorgabewert verwenden

1

Sonntag (Vorgabe)

2

Montag

3

Dienstag

4

Mittwoch

5

Donnerstag

6

Freitag

7

Samstag


firstweekofyear: An optional parameter that specifies the starting week of a year.

firstweekofyear value

Erklärung

0

Systemvorgabewert verwenden

1

Woche 1 ist die Woche, auf die der 1. Januar fällt. (Vorgabe)

2

Woche 1 ist die erste Woche, die mindestens vier Tage dieses Jahres enthält

3

Woche 1 ist die erste Woche, die ausschließlich Tage dieses Jahres enthält


Rückgabewert:

A number.

Beispiel:


    date1 = datetime.datetime(2005,1, 1)
    date2 = datetime.datetime(2005,12,31)
    diffDays = bas.DateDiff('d', date1, date2)
    print(diffDays)
  

DatePart

The DatePart function returns a specified part of a date.

Syntax:

svc.DatePart(interval: str, date: datetime, firstdayofweek = 1, firstweekofyear = 1): int

Parameter:

interval: A string expression specifying the date interval, as detailed in above DateAdd method.

date: The date/time from which the result is calculated.

firstdayofweek, firstweekofyear: optional parameters that respectively specify the starting day of a week and the starting week of a year, as detailed in above DateDiff method.

Rückgabewert:

The extracted part for the given date/time.

Beispiel:


    print(bas.DatePart("ww", datetime.datetime(2005,12,31)
    print(bas.DatePart('q', datetime.datetime(1999,12,30)
  

DateValue

Computes a date value from a date string.

Syntax:

svc.DateValue(date: str): datetime

Parameter:

Date: String expression that contains the date that you want to calculate. In contrast to the DateSerial function that passes years, months and days as separate numeric values, the DateValue function requests the date string to be according to either one of the date acceptance patterns defined for your locale setting (see - Language Settings - Languages) or to ISO date format (momentarily, only the ISO format with hyphens, e.g. "2012-12-31" is accepted).

Rückgabewert:

The computed date.

Beispiel:


    dt = bas.DateValue("23-02-2011")
    print(dt)
  

Format

Converts a number to a string, and then formats it according to the format that you specify.

Syntax:

svc.Format(expression: any, format = ''): str

Parameter:

expression: Numeric expression that you want to convert to a formatted string.

format: String that specifies the format code for the number. If format is omitted, the Format function works like the LibreOffice Basic Str() function.

Rückgabewert:

Text string.

Formatting Codes

The following list describes the codes that you can use for formatting a numeric expression:

0: If expression has a digit at the position of the 0 in the format code, the digit is displayed, otherwise a zero is displayed.

If expression has fewer digits than the number of zeros in the format code, (on either side of the decimal), leading or trailing zeros are displayed. If the expression has more digits to the left of the decimal separator than the amount of zeros in the format code, the additional digits are displayed without formatting.

Decimal places in the expression are rounded according to the number of zeros that appear after the decimal separator in the format code.

#: If expression contains a digit at the position of the # placeholder in the format code, the digit is displayed, otherwise nothing is displayed at this position.

This symbol works like the 0, except that leading or trailing zeroes are not displayed if there are more # characters in the format code than digits in the expression. Only the relevant digits of the expression are displayed.

.: Der Dezimalplatzhalter legt die Anzahl der Dezimalstellen links und rechts vom Dezimaltrennzeichen fest.

If the format code contains only # placeholders to the left of this symbol, numbers less than 1 begin with a decimal separator. To always display a leading zero with fractional numbers, use 0 as a placeholder for the first digit to the left of the decimal separator.

%: Multiplies the expressionby 100 and inserts the percent sign (%) where the expression appears in the format code.

E- E+ e- e+ : If the format code contains at least one digit placeholder (0 or #) to the right of the symbol E-, E+, e-, or e+, the expression is formatted in the scientific or exponential format. The letter E or e is inserted between the number and the exponent. The number of placeholders for digits to the right of the symbol determines the number of digits in the exponent.

Ist der Exponent negativ, so wird bei den Symbolen E-, E+, e-, e+ ein Minuszeichen unmittelbar vor dem Exponenten ausgegeben. Ist der Exponent positiv, so wird nur bei den Symbolen E+ oder e+ ein Pluszeichen ausgegeben.

The thousands delimiter is displayed if the format code contains the delimiter enclosed by digit placeholders (0 or #).

Ob der Punkt als Tausender- oder Dezimaltrennzeichen verwendet wird, hängt vom verwendeten Gebietsschema ab. Welches Zeichen tatsächlich als Dezimaltrennzeichen angezeigt wird, richtet sich nach dem Zahlenformat in Ihren Systemeinstellungen. In den hier gezeigten Beispielen wird angenommen, dass das Gebietsschema auf "USA" eingestellt ist.

- + $ ( ) space: A plus (+), minus (-), dollar ($), space, or brackets entered directly in the format code is displayed as a literal character.

Um andere als die hier angegebenen Zeichen auszugeben, müssen Sie einen umgekehrten Schrägstrich (\) vor das entsprechende Zeichen setzen oder das Zeichen in Anführungsstriche (" ") setzen.

\ : The backslash displays the next character in the format code.

Characters in the format code that have a special meaning can only be displayed as literal characters if they are preceded by a backslash. The backslash itself is not displayed, unless you enter a double backslash (\\) in the format code.

Die Zeichen, denen Sie im Format-Code einen umgekehrten Schrägstrich voranstellen müssen, damit sie als normales Zeichen (also nicht in ihrer Sonderbedeutung) angezeigt werden, sind die Zeichen zur Formatierung von Datum- und Zeitangaben (a, c, d, h, m, n, p, q, s, t, w, y, /, :), von Zahlen (#, 0, %, E, e, Komma, Punkt) und von Zeichenketten (@, &, <, >, !).

You can also use the following predefined number formats. Except for "General Number", all of the predefined format codes return the number as a decimal number with two decimal places.

Bei Verwendung vordefinierter Formate muss der jeweilige Name im Formatausdruck in Anführungszeichen stehen.

Predefined Formats

General Number: Zahlen werden so angezeigt, wie sie eingegeben wurden.

Currency: Fügt vor der Zahl ein Dollarzeichen ein und setzt negative Zahlen in Klammern.

Fixed: Zeigt vor dem Dezimaltrennzeichen mindestens eine Ziffer an.

Standard: Zeigt Zahlen mit Tausender-Trennzeichen an.

Percent: Multipliziert die Zahl mit 100 und hängt ihr ein Prozentzeichen an.

Scientific: Zeigt die Zahl im wissenschaftlichen Format an (beispielsweise 1,00E+03 für 1000).

A format code can be divided into three sections that are separated by semicolons. The first part defines the format for positive values, the second part for negative values, and the third part for zero. If you only specify one format code, it applies to all numbers.

Sie können das Gebietsschema, das in LibreOffice Basic zur Kontrolle der Formatierung von Zahlen, Daten und Währungen verwendet wird, unter – Spracheinstellungen – Sprachen einstellen. In Basic Formatierungscodes wird immer der Dezimalpunkt (.) als Platzhalter für das Dezimaltrennzeichen verwendet, der in Ihrem Gebietsschema definiert ist, und durch das entsprechende Zeichen ersetzt.

Dies gilt entsprechend für das Gebietsschema für Datums-, Uhrzeit- und Währungsformate. Der Basic-Format-Code wird entsprechend Ihrer Gebietsschema-Einstellung ausgewertet und angezeigt.

Beispiel:


    txt = bas.Format(6328.2, '##.##0.00')
    print(txt)
  

GetDefaultContext

Returns the default context of the process service factory, if existent, else returns a null reference.

GetDefaultContext is an alternative to the getComponentContext() method available from XSCRIPTCONTEXT global variable or from uno.py module.

Syntax:

svc.GetDefaultContext(): uno

Rückgabewert:

The default component context is used, when instantiating services via XMultiServiceFactory. See the Professional UNO chapter in the Developer's Guide on api.libreoffice.org for more information.

Beispiel:


    ctx = bas.GetDefaultContext()
  

GetGuiType

Returns a numerical value that specifies the graphical user interface. This function is only provided for backward compatibility with previous versions.

Refer to system() method from platform Python module to identify the operating system.

Syntax:

svc.GetGuiType(): int

Beispiel:


    n = bas.GetGuiType()
  

GetPathSeparator

Returns the operating system-dependent directory separator used to specify file paths.

Use os.pathsep from os Python module to identify the path separator.

Syntax:

svc.GetPathSeparator(): str

Beispiel:


    sep = bas.GetPathSeparator()
  

GetSystemTicks

Returns the number of system ticks provided by the operating system. You can use this function to optimize certain processes. Use this method to estimate time in milliseconds:

Syntax:

svc.GetSystemTicks(): int

Beispiel:


    ticks_ini = bas.GetSystemTicks()
    time.sleep(1)
    ticks_end = bas.GetSystemTicks()
    bas.MsgBox("{} - {} = {}".format(ticks_end, ticks_ini,ticks_end - ticks_ini))
  

GlobalScope.BasicLibraries

Returns the UNO object containing all shared Basic libraries and modules.

This method is the Python equivalent to GlobalScope.BasicLibraries in Basic scripts.

Syntax:

svc.GlobalScope.BasicLibraries(): uno

Rückgabewert:

com.sun.star.script.XLibraryContainer

Beispiel:

The following example loads the Gimmicks Basic library if it has not been loaded yet.


    libs = bas.GlobalScope.BasicLibraries()
    if not libs.isLibraryLoaded("Gimmicks"):
        libs.loadLibrary("Gimmicks")
  

GlobalScope.DialogLibraries

Returns the UNO object containing all shared dialog libraries.

This method is the Python equivalent to GlobalScope.DialogLibraries in Basic scripts.

Syntax:

svc.GlobalScope.DialogLibraries(): uno

Rückgabewert:

com.sun.star.comp.sfx2.DialogLibraryContainer

Beispiel:

The following example shows a message box with the names of all available dialog libraries.


    dlg_libs = bas.GlobalScope.DialogLibraries()
    lib_names = dlg_libs.getElementNames()
    bas.MsgBox("\n".join(lib_names))
  

InputBox

Syntax:

svc.InputBox(prompt: str, [title: str], [default: str], [xpostwips: int, ypostwips: int]): str

Parameter:

Meldung: Zeichenkettenausdruck, der im Dialog als Meldung angezeigt wird.

Titel: Zeichenkettenausdruck, der in der Titelleiste des Dialogs angezeigt wird.

Standard: Zeichenkettenausdruck, der im Textfeld des Dialogs als Standard angezeigt wird, wenn keine andere Eingabe übergeben wird.

x_Position_twips: Integerausdruck, der die horizontale Position des Dialogs angibt. Die Position ist eine absolute Koordinate, nimmt also nicht auf das Fenster von LibreOffice Bezug.

y_Position_twips: Integerausdruck, der die vertikale Position des Dialogs angibt. Die Position ist eine absolute Koordinate, nimmt also nicht auf das Fenster von LibreOffice Bezug.

Wenn x_Position_twips und y_Position_twips weggelassen werden, wird der Dialog auf dem Bildschirm zentriert. Als Maßeinheit wird Twips verwendet.

Rückgabewert:

String

Beispiel:


    txt = s.InputBox('Please enter a phrase:', "Dear user")
    s.MsgBox(txt, s.MB_ICONINFORMATION, "Confirmation of phrase")
  
note

For in-depth information please refer to Input/Output to Screen with Python on the Wiki.


MsgBox

Displays a dialog box containing a message and returns an optional value.
MB_xx constants help specify the dialog type, the number and type of buttons to display, plus the icon type. By adding their respective values they form bit patterns, that define the MsgBox dialog appearance.

Syntax:

bas.MsgBox(prompt: str, [buttons: int], [title: str])[: int]

Parameter:

Meldung: Zeichenkettenausdruck, der im Dialog als Meldung angezeigt wird. Zeilenumbrüche können Sie mit Chr$(13) einfügen.

Dialogtitel: Zeichenkettenausdruck, der in der Titelleiste des Dialoges angezeigt wird. Wird dieser weggelassen, so erscheint in der Titelleiste der Name der jeweiligen Anwendung.

Schaltflächen: Ein beliebiger Ausdruck vom Typ Integer, der den Dialogtyp angibt und Anzahl und Art der angezeigten Schaltflächen sowie die Art des Symbols festlegt. Schaltflächen stellt eine Kombination von Bitmustern dar. Durch Addition ihrer jeweiligen Werte können also mehrere Dialogelemente definiert werden:

Rückgabewert:

An optional integer as detailed in above IDxx properties.

Beispiel:


    txt = s.InputBox('Please enter a phrase:', "Dear user")
    s.MsgBox(txt, s.MB_ICONINFORMATION, "Confirmation of phrase")
  
note

For in-depth information please refer to Input/Output to Screen with Python on the Wiki.


Now

Returns the current system date and time as a datetime.datetime Python native object.

Syntax:

svc.Now(): datetime

Beispiel:


    bas.MsgBox(bas.Now(), bas.MB_OK, "Now")
  

RGB

Returns an integer color value consisting of red, green, and blue components.

Syntax:

svc.RGB(red:int, green: int, blue: int): int

Parameter:

Rot: Ein beliebiger Integerausdruck, der die Rotkomponente (0-255) der zusammengesetzten Farbe angibt.

Grün: Ein beliebiger Integerausdruck, der die Grünkomponente (0-255) der zusammengesetzten Farbe angibt.

Blau: Ein beliebiger Integerausdruck, der die Blaukomponente (0-255) der zusammengesetzten Farbe angibt.

tip

Der Dialog Farbauswahl hilft bei der Berechnung der Rot-, Grün- und Blaukomponenten einer zusammengesetzten Farbe. Ändern der Textfarbe und das Auswählen von Benutzerdefinierte Farbe zeigt den Farbauswahldialog an.


Rückgabewert:

Integer

Beispiel:


    YELLOW = bas.RGB(255,255,0)
  

ThisComponent

If the current component refers to a LibreOffice document, this method returns the UNO object representing the document.

The method will return None when the current component does not correspond to a document.

Syntax:

svc.ThisComponent(): uno

Beispiel:


    comp = bas.ThisComponent
    bas.MsgBox("\n".join(comp.getSupportedServiceNames()))
  

ThisDatabaseDocument

If the script is being executed from a Base document or any of its subcomponents this method returns the main component of the Base instance.

This method returns None otherwise.

Syntax:

svc.ThisDatabaseDocument(): uno

Beispiel:


    db_doc = bas.ThisDatabaseDocument
    table_names = db_doc.DataSource.getTables().getElementNames()
    bas.MsgBox("\n".join(table_names))
  
tip

Visit the OfficeDatabaseDocument API page to learn more about Base's main component structure.


Xray

Inspect Uno objects or variables.

Syntax:

svc.Xray(obj: any)

Parameter:

obj: A variable or UNO object.

Beispiel:


    bas.Xray(bas.StarDesktop)
  
warning

All ScriptForge Basic routines or identifiers that are prefixed with an underscore character "_" are reserved for internal use. They are not meant be used in Basic macros or Python scripts.