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

This service is available from LibreOffice 7.2 onwards.


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")
  

Proprietà

Nome

Sola lettura

Tipo

Descrizione

MB_OK, MB_OKCANCEL, MB_RETRYCANCEL, MB_YESNO, MB_YESNOCANCEL

integer

Values: 0, 1, 5, 4, 3

MB_ICONEXCLAMATION, MB_ICONINFORMATION, MB_ICONQUESTION, MB_ICONSTOP

integer

Values: 48, 64, 32, 16

MB_ABORTRETRYIGNORE, MB_DEFBUTTON1, MB_DEFBUTTON2, MB_DEFBUTTON3

integer

Values: 2, 128, 256, 512

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

integer

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

StarDesktop

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.


Sintassi:

svc.CDate(expression: any): obj

Parametri:

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

Quando convertite un'espressione di stringa, la data e l'ora devono essere digitate in uno dei modelli di data accettati definiti nelle vostre impostazioni locali (si veda - Impostazioni della lingua - Lingue), oppure nel formato di data ISO (attualmente è accettato solo il formato ISO con trattini, per es. "31-12-2012"). Nelle espressioni numeriche, i valori alla sinistra del separatore decimale rappresentano la data, che parte dal 31 dicembre 1899. I valori alla destra del separatore decimale rappresentano l'ora.

Esempio:


    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.

Sintassi:

svc.CDateFromUnoDateTime(unodate: uno): obj

Parametri:

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

Esempio:

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.

Sintassi:

svc.CDateToUnoDateTime(date: obj): uno

Parametri:

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.

Esempio:


    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.

Sintassi:

svc.ConvertFromUrl(url: str): str

Parametri:

url: An absolute file: URL.

Valore restituito:

A system path file name.

Esempio:


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

ConvertToUrl

Restituisce un URL file: per il percorso di sistema specificato.

Sintassi:

svc.ConvertToUrl(systempath: str): str

Parametri:

systempath: A system file name as a string.

Valore restituito:

A file: URL as a string.

Esempio:


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

CreateUnoService

Crea un'istanza di un servizio UNO con il ProcessServiceManager.

Sintassi:

svc.CreateUnoService(servicename: str): uno

Parametri:

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

Esempio:


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

DateAdd

Aggiunge un intervallo a una data od ora per un determinato numero di volte e restituisce la data risultante.

Sintassi:

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

Parametri:

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

interval (string value)

Spiegazione

yyyy

Anno

q

Trimestre

m

Mese

y

Giorno dell'anno

w

Giorno della settimana

ww

Settimana dell'anno

d

Giorno

h

Ora

n

Minuto

s

Secondo


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.

Valore restituito:

A datetime.datetime value.

Esempio:


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

DateDiff

Restituisce il numero di intervalli di data od ora che trascorrono tra i due valori di data/ora indicati.

Sintassi:

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

Parametri:

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

Spiegazione

0

Usa il valore predefinito di sistema

1

Domenica (predefinito)

2

Lunedì

3

Martedì

4

Mercoledì

5

Giovedì

6

Venerdì

7

Sabato


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

firstweekofyear value

Spiegazione

0

Usa il valore predefinito di sistema

1

La settimana 1 è quella che comprende il 1° gennaio (predefinito)

2

La settimana 1 è la prima settimana che comprende quattro o più giorni di quell'anno

3

La settimana 1 è la prima settimana che comprende solo giorni del nuovo anno


Valore restituito:

Un numero.

Esempio:


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

DatePart

La funzione DatePart restituisce la parte specificata di una data.

Sintassi:

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

Parametri:

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

data - La data/ora dalla quale viene calcolato il risultato.

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.

Valore restituito:

The extracted part for the given date/time.

Esempio:


    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.

Sintassi:

svc.DateValue(date: str): datetime

Parametri:

Data: espressione di stringa che contiene la data da calcolare. A differenza della funzione DateSerial che passa anni, mesi e giorni come valori numerici separati, la funzione DateValue che da stringa della data sia conforme i modelli accettati per la data definiti nelle vostre impostazioni locali (si veda - Impostazioni della lingua - Lingue) o al formato di data ISO (al momento è accettato solo il formato ISO con trattino breve, ossia "31-12-2012").

Valore restituito:

The computed date.

Esempio:


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

Format

Converte un numero in una stringa e la formatta in base al formato specificato.

Sintassi:

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

Parametri:

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.

Valore restituito:

Text string.

Codici di formato

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.

.: il segnaposto decimale determina il numero di posti decimali a sinistra e a destra del separatore.

Se il codice del formato contiene solo caratteri segnaposto # a sinistra di questo simbolo, i numeri inferiori a 1 iniziano con un separatore decimale. Per visualizzare sempre uno zero all'inizio dei numeri decimali, usate 0 come segnaposto per la prima cifra a sinistra del separatore decimale.

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

Se l'esponente è negativo, viene visualizzato un segno meno direttamente davanti agli esponenti con E-, E+, e-, e+. Se l'esponente è positivo, viene visualizzato solo un segno più davanti agli esponenti con E+ o e+.

Il codice del formato può comprendere un delimitatore di migliaia racchiuso tra i segnaposto per le cifre (0 o #).

L'uso del punto come separatore per le migliaia o come separatore decimale dipende dalle impostazioni regionali. Il carattere effettivamente visualizzato come separatore decimale dipende dal formato numerico impostato nel vostro sistema. Gli esempi qui illustrati si riferiscono a un sistema con l'impostazione locale "US".

- + $ ( ) space: i caratteri più (+), meno (-), dollaro ($), spazio o parentesi inseriti direttamente nel codice del formato vengono visualizzati in modo letterale.

Per visualizzare caratteri diversi da quelli qui elencati, dovete farli precedere da una barra rovesciata (\) o racchiuderli tra virgolette (" ").

\ : La barra rovesciata visualizza il carattere successivo nel codice del formato.

I caratteri del codice del formato che possiedono un significato speciale possono essere visualizzati in modo letterale solo se sono preceduti da una barra rovesciata. In questi casi, la barra rovesciata non viene visualizzata, a meno che non sia anch'essa preceduta da una barra rovesciata (\\).

I caratteri che devono essere preceduti da una barra rovesciata nel codice del formato per essere visualizzati in modo letterale sono i caratteri di formattazione della data e dell'ora (a, c, d, h, m, n, p, q, s, t, w, y, /, :), i caratteri di formattazione dei numeri (#, 0, %, E, e, virgola, punto) e i caratteri di formattazione delle stringhe (@, &, <, >, !).

In alternativa, potete usare i seguenti formati numerici predefiniti. Ad eccezione di "Numero generale", tutti i codici di formato predefiniti restituiscono un numero decimale con due cifre dopo il separatore.

Per usare i formati predefiniti, dovete indicarne il nome tra virgolette.

Predefined Formats

General Number: i numeri sono visualizzati nella forma in cui vengono digitati.

Currency: inserisce il simbolo del dollaro davanti al numero e racchiude i numeri negativi tra parentesi.

Fixed: mostra almeno una cifra davanti al separatore decimale.

Standard:mostra i numeri con un separatore di migliaia.

Percent: moltiplica il numero per 100 e aggiunge il segno di percentuale alla fine.

Notazione scientifica: visualizza i numeri in formato scientifico (ad esempio, 1,00E+03 per 1000).

Il codice di formato può essere diviso in tre sezioni separate da punti e virgola. La prima parte definisce il formato per i valori positivi, la seconda il formato per i valori negativi, la terza il formato per lo zero. Se specificate un solo codice di formato, questo viene applicato a tutti i numeri.

Potete configurare le impostazioni di località utilizzate in LibreOffice Basic per gestire la formattazione di numeri, date e valute in - Impostazioni della lingua - Lingue. Nei codici di formato Basic, il punto decimale (.) viene sempre usato come segnaposto per il separatore dei decimali definito nella vostra area geografica e verrà sostituito dal carattere corrispondente.

Lo stesso vale per le impostazioni di data, ora e valuta. Il codice in formato Basic viene interpretato e visualizzato in base alla versione locale prescelta.

Esempio:


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

GetDefaultContext

Restituisce il contesto predefinito della fabbrica di servizio del processo, se esiste, diversamente restituisce un riferimento nullo.

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

Sintassi:

svc.GetDefaultContext(): uno

Valore restituito:

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.

Esempio:


    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.

Sintassi:

svc.GetGuiType(): int

Esempio:


    n = svc.GetGuiType()
  

GetPathSeparator

Restituisce il separatore di directory dipendente dal sistema operativo utilizzato per specificare i percorsi dei file.

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

Sintassi:

svc.GetPathSeparator(): str


    svc.GetPathSeparator(): str
  

Esempio:


    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:

Sintassi:

svc.GetSystemTicks(): int

Esempio:


    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.

Sintassi:

svc.GlobalScope.BasicLibraries(): uno

Valore restituito:

com.sun.star.script.XLibraryContainer

Esempio:

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.

Sintassi:

svc.GlobalScope.DialogLibraries(): uno

Valore restituito:

com.sun.star.comp.sfx2.DialogLibraryContainer

Esempio:

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

Sintassi:

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

Parametri:

prompt: String expression displayed as the message in the dialog box.

title (titolo): stringa visualizzata nella barra del titolo della finestra di dialogo.

default (predefinito): stringa visualizzata nella casella di testo come valore predefinito se non viene specificato nessun valore.

xpostwips: numero intero che specifica la posizione orizzontale della finestra di dialogo. La posizione è una coordinata assoluta e non fa riferimento alla finestra di LibreOffice.

ypostwips: Integer expression that specifies the vertical position of the dialog. The position is an absolute coordinate and does not refer to the window of LibreOffice.

Se xpostwips e ypostwips vengono omessi, la finestra di dialogo viene centrata sullo schermo. La posizione è specificata in twip.

Valore restituito:

string

Esempio:


    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.

Sintassi:

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

Parametri:

prompt: String expression displayed as a message in the dialog box. Line breaks can be inserted with Chr$(13).

title: String expression displayed in the title bar of the dialog. If omitted, the title bar displays the name of the respective application.

buttons: Any integer expression that specifies the dialog type, as well as the number and type of buttons to display, and the icon type. buttons represents a combination of bit patterns, that is, a combination of elements can be defined by adding their respective values:

Valore restituito:

An optional integer as detailed in above IDxx properties.

Esempio:


    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.

Sintassi:

svc.Now(): datetime

Esempio:


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

RGB

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

Sintassi:

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

Parametri:

red (rosso): numero intero che rappresenta il componente rosso (0-255) del colore composito.

green (verde): numero intero che rappresenta il componente verde (0-255) del colore composito.

blue (blu): numero intero che rappresenta il componente blu (0-255) del colore composito.

tip

La finestra di dialogo per la scelta del colore aiuta a calcolare i componenti rosso, verde e blu di un colore composito. La modifica del colore del testo e la selezione di un colore personalizzato richiama la finestra di dialogo per la scelta del colore.


Valore restituito:

integer

Esempio:


    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.

Sintassi:

svc.ThisComponent(): uno

Esempio:


    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.

Sintassi:

svc.ThisDatabaseDocument(): uno

Esempio:


    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.

Sintassi:

svc.Xray(obj: any)

Parametri:

obj: A variable or Uno object.

Esempio:


    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.