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.

note

Deze service is beschikbaar vanaf LibreOffice 7.2.


Typical example:


   svc.MsgBox('This has to be displayed in a message box')
  
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
    svc = CreateScriptService("Basic")
  

Properties

Name

ReadOnly

Type

Description

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.


Syntaxis:

svc.CDate(expression: any): obj

Parameters:

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

Als u een tekst expressie converteert, moeten de datum en tijd ingevuld worden in een van de geaccepteerde patronen die in uw lokale instellingen is gedefinieerd (lees - Taalinstellingen - Talen) of in ISO-datumformaat (nu is alleen het ISO-formaat met streepjes, bijv.. "2012-12-31" toegestaan). In numerieke expressies, waarden links van de decimaal representeren de datum, vanaf 31 december 1899. Waarden rechts van de decimaal representeren de tijd.

Voorbeeld:


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

CDateFromUnoDateTime

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

Syntaxis:

svc.CDateFromUnoDateTime(unodate: uno): obj

Parameters:

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

Voorbeeld:

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 = svc.CDateFromUnoDateTime(uno_date)
    svc.MsgBox(str(new_date)) # 1983-02-23 00:00:00
  

CDateToUnoDateTime

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

Syntaxis:

svc.CDateToUnoDateTime(date: obj): uno

Parameters:

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.

Voorbeeld:


    from datetime import datetime
    current_datetime = datetime.now()
    uno_date = svc.CDateToUnoDateTime(current_datetime)
    svc.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.

Syntaxis:

svc.ConvertFromUrl(url: str): str

Parameters:

url: An absolute file: URL.

Geretourneerde waarde:

A system path file name.

Voorbeeld:


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

ConvertToUrl

Returns a file: URL for the given system path.

Syntaxis:

svc.ConvertToUrl(systempath: str): str

Parameters:

systempath: A system file name as a string.

Geretourneerde waarde:

A file: URL as a string.

Voorbeeld:


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

CreateUnoService

Instantiates a UNO service with the ProcessServiceManager.

Syntaxis:

svc.CreateUnoService(servicename: str): uno

Parameters:

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

Voorbeeld:


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

DateAdd

Voegt een datum of tijdsperiode een aantal keren toe aan een gegeven datum/tijd en retourneert de resulterende datum.

Syntaxis:

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

Parameters:

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

interval (Tekst)

Uitleg

jjjj

Jaar

q

Kwartaal

m

Maand

y

Dag van het jaar

w

Dag van de week

ww

Week van het jaar

d

Dag

h

Uur

n

Minuut

s

Seconde


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 date/time value.

Geretourneerde waarde:

A datetime.datetime value.

Voorbeeld:


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

DateDiff

Retourneert het aantal dagen of het aantal tijdsintervallen tussen twee opgegeven datums/tijden.

Syntaxis:

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

Parameters:

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

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

eerstedagvandeweek: Een optionele parameter die de eerste dag van de week aangeeft.

eerstedagvandeweek waarde

Uitleg

0

Standaardwaarde van het systeem gebruiken

1

Zondag (standaard)

2

Maandag

3

Dinsdag

4

Woensdag

5

Donderdag

6

Vrijdag

7

Zaterdag


eersteweekvanhetjaar: Een optionele parameter die de eerste week van het jaar aangeeft.

eersteweekvanhetjaar waarde

Uitleg

0

Standaardwaarde van het systeem gebruiken

1

Week 1 is de week waarin 1 januari valt (standaard)

2

Week 1 is de eerste week waarin vier of meer dagen van dat jaar vallen

3

Week 1 is de eerste week waarin alleen dagen van het nieuwe jaar vallen


Geretourneerde waarde:

A number.

Voorbeeld:


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

DatePart

The DatePart function returns a specified part of a date.

Syntaxis:

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

Parameters:

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.

Geretourneerde waarde:

The extracted part for the given date/time.

Voorbeeld:


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

DateValue

Computes a date value from a date string.

Syntaxis:

svc.DateValue(date: str): datetime

Parameters:

Datum: Expressie die de datum bevat die u wilt berekenen. Anders dan bij de functie DateSerial die de jaren, maanden en dagen als losse numerieke velden doorgeeft, moet hier bij de functie DateValue de datum in een van de toegestane patronen worden doorgegeven. De patronen worden bepaald door uw lokale instellingen (bekijk - Taalinstellingen - Talen) of in een ISO-formaat voor datumopmaak (nu wordt alleen het formaat met streepjes geaccepteerd, "2012-12-31").

Geretourneerde waarde:

De berekende datum.

Voorbeeld:


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

Format

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

Syntaxis:

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

Parameters:

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.

Geretourneerde waarde:

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.

.: Het decimaalteken bepaalt het aantal decimale posities aan de linker- en rechterkant van het decimale scheidingsteken.

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.

Als de exponent negatief is, wordt een minteken vlak voor een exponent met E-, E+, e-, e+ geplaatst. Als de exponent positief is wordt een plusteken alleen voor exponenten met E+ of e+ geplaatst.

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

Het gebruik van de punt als scheidingsteken voor duizendtallen en decimalen is afhankelijk van de landinstellingen. Als u een getal direct in BASIC-broncode invoert, gebruik dan altijd een punt als decimaal scheidingsteken. Het feitelijke teken dat wordt weergegeven als decimaal scheidingsteken is afhankelijk van uw systeeminstellingen.

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

Om andere tekens dan die hier opgesomd werden weer te geven, moet u het laten voorafgaan door een backslash (\), of het tussen aanhalingstekens plaatsen (" ").

\ : 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.

Tekens die moeten worden voorafgegaan door een backslash in de opmaakcode om te worden weergegeven als letterlijke tekens zijn de datum- en tijdopmaaktekens (a, c, d, h, m, n, p, q, s, t, w, y, /, :), numerieke opmaaktekens (#, 0, %, E, e, komma, punt) en tekenreeksopmaaktekens (@, &, <, >, !).

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.

Als u voorgedefinieerde opmaak gebruikt, moet de naam van de opmaak tussen aanhalingstekens staan.

Predefined Formats

Getallen: Getallen worden getoond zoals ingevoerd.

Valuta: Er wordt een dollarteken vóór het getal geplaatst en negatieve getallen worden tussen ronde haakjes gezet.

Vast: Tenminste één cijfer wordt getoond vóór het decimale scheidingsteken.

Standaard: Toont getallen met een scheidingsteken voor duizendtallen.

Percent: Het getal wordt vermenigvuldigd met 100 en een procentteken wordt achter het getal geplaatst.

Wetenschappelijk: Toont getallen in wetenschappelijke opmaak (bijv., 1,00E+03 voor 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.

U kunt de locale instellingen die worden gebruikt voor het beheren van de opmaak van getallen, datums en valuta instellen in LibreOffice BASIC in - Taalinstellingen - Talen. In opmaakcodes in BASIC wordt altijd de decimale punt (.) gebruikt als tijdelijke aanduiding voor het decimale scheidingsteken dat is gedefinieerd in uw lokale instellingen en zal door het overeenkomende teken worden vervangen.

Hetzelfde geldt voor de landinstellingen voor datum-, tijd- en valuta-opmaak. De BASIC-notatiecode wordt geĆÆnterpreteerd en weergegeven volgens uw landinstelling.

Voorbeeld:


    txt = svc.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.

Syntaxis:

svc.GetDefaultContext(): uno

Geretourneerde waarde:

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.

Voorbeeld:


    ctx = svc.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.

Syntaxis:

svc.GetGuiType(): int

Voorbeeld:


    n = svc.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.

Syntaxis:

svc.GetPathSeparator(): str


    svc.GetPathSeparator(): str
  

Voorbeeld:


    sep = svc.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:

Syntaxis:

svc.GetSystemTicks(): int

Voorbeeld:


    ticks_ini = svc.GetSystemTicks()
    time.sleep(1)
    ticks_end = svc.GetSystemTicks()
    svc.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.

Syntaxis:

svc.GlobalScope.BasicLibraries(): uno

Geretourneerde waarde:

com.sun.star.script.XLibraryContainer

Voorbeeld:

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


    libs = svc.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.

Syntaxis:

svc.GlobalScope.DialogLibraries(): uno

Geretourneerde waarde:

com.sun.star.comp.sfx2.DialogLibraryContainer

Voorbeeld:

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


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

InputBox

Syntaxis:

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

Parameters:

prompt:Tekst die wordt getoond als het bericht in het dialoogvenster.

titel: Tekst die getoond wordt in de titelbalk van het dialoogvenster.

standaardwaarde: Tekst die in het tekstvak wordt getoond als er geen invoer wordt ingevuld.

xpostwips: Getal die de horizontale positie aangeeft van de dialoog. De positie is een absolute coƶrdinaat en staat los van het venster van LibreOffice.

ypostwips: Getal die de verticale positie aangeeft van de dialoog. De positie is een absolute coƶrdinaat en staat los van het venster van LibreOffice.

Als xpostwips en ypostwips worden weggelaten, dan wordt de dialoog op het scherm gecentreerd. De positie wordt gespecificeerd in twips.

Geretourneerde waarde:

string

Voorbeeld:


    txt = s.InputBox('Please enter a phrase:', "Dear user")
    s.MsgBox(txt, 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.

Syntaxis:

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

Parameters:

prompt: De tekst die wordt getoond in het dialoogvenster. Een regeleinde kan worden toegevoegd met Chr$(13).

title: tekenreeks die wordt weergegeven in de titelbalk van het dialoogvenster. Indien weggelaten, wordt daar de naam van de toepassing weergegeven.

buttons: Een geheel getal die het dialoogtype aangeeft, als ook het aantal en type van de te tonen knoppen en het icoon-type. buttons staat voor een combinatie van patronen van bits, daar mee wordt bedoeld, een combinatie van elementen kan worden gedefinieerd bij optellen van de respectievelijke waarden:

Geretourneerde waarde:

An optional integer as detailed in above IDxx properties.

Voorbeeld:


    txt = s.InputBox('Please enter a phrase:', "Dear user")
    s.MsgBox(txt, 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.

Syntaxis:

svc.Now(): datetime

Voorbeeld:


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

RGB

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

Syntaxis:

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

Parameters:

rood: Een getal dat de rode component (0-255) aangeeft van de samengestelde kleur.

groen: Een getal dat de groene component (0-255) aangeeft van de samengestelde kleur.

blauw: Een getal dat de blauwe component (0-255) aangeeft van de samengestelde kleur.

tip

De dialoog kleurkiezer helpt het bepalen van de rode, groene en blauwe componenten van een samengestelde kleur. De dialoog wordt gebruikt bij het wijzigen van de kleurtekst en het kiezen van een eigen kleur.


Geretourneerde waarde:

integer

Voorbeeld:


    YELLOW = svc.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.

Syntaxis:

svc.ThisComponent(): uno

Voorbeeld:


    comp = svc.ThisComponent
    svc.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.

Syntaxis:

svc.ThisDatabaseDocument(): uno

Voorbeeld:


    db_doc = svc.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.

Syntaxis:

svc.Xray(obj: any)

Parameters:

obj: A variable or Uno object.

Voorbeeld:


    svc.Xray(svc.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.