Preprocessing

Einige Preprocessing-Funktionen sind in PlantUML enthalten und für alle Diagramme verfügbar.

Diese Funktionalitäten sind sehr ähnlich wie der C-Sprache Preprozessor, mit dem Unterschied, dass das spezielle Zeichen # durch das Ausrufezeichen ! ersetzt wurde.

Variablendefinition [=, ?=]

Obwohl dies nicht verpflichtend ist, empfehlen wir dringend, dass Variablennamen mit einem $ beginnen.

Es gibt drei Arten von Daten:
  • Ganzzahl(int);
  • String(str) - diese müssen von einem einfachen oder doppelten Anführungszeichen umgeben sein;
  • JSON(JSON) - diese müssen von geschweiften Klammern umgeben sein.
(Für die Definition und Verwendung von JSON-Variablen, siehe mehr Details auf der Preprocessing-JSON Seite)

Variablen, die außerhalb von Funktionen erstellt werden, sind global, das heißt, Sie können von überall darauf zugreifen (einschließlich aus Funktionen). Dies können Sie durch Verwendung des optionalen Schlüsselworts global bei der Definition einer Variablen betonen.

🎉 Copied!

@startuml
!$a  = 42
!$ab = "foo1"
!$cd = "foo2"
!$ef = $ab + $cd
!$foo = { "name": "John", "age" : 30 }

Alice -> Bob : $a
Alice -> Bob : $ab
Alice -> Bob : $cd
Alice -> Bob : $ef
Alice -> Bob : Kennst du **$foo.name** ?
@enduml

Sie können auch einer Variablen einen Wert zuweisen, nur wenn sie noch nicht definiert ist, mit der Syntax: !$a ?= "foo"

🎉 Copied!

@startuml
Alice -> Bob : 1. **$name** sollte leer sein

!$name ?= "Charlie"
Alice -> Bob : 2. **$name** sollte Charlie sein

!$name = "David"
Alice -> Bob : 3. **$name** sollte David sein

!$name ?= "Ethan"
Alice -> Bob : 4. **$name** sollte David sein
@enduml

Boolescher Ausdruck

Boolesche Darstellung [0 ist false]

Es gibt keinen echten Booleschen Typ, aber PlantUML verwendet diese Integer-Konvention:

  • Integer 0 bedeutet false
  • und jede nicht-null Zahl (wie 1) oder jeder String (wie "1", oder sogar "0") bedeutet true.

[Ref. QA-9702]

Boolesche Operation und Operator [&&, ||, ()]

Sie können boolesche Ausdrücke in Tests verwenden, mit:
  • Klammern();
  • und Operator&&;
  • oder Operator||.

(Siehe nächstes Beispiel innerhalb des if Tests.)

Boolesche eingebaute Funktionen [%false(), %true(), %not(<exp>)]

Zur Vereinfachung können Sie diese booleschen eingebauten Funktionen verwenden:

  • %false()
  • %true()
  • %not(<exp>)

[Siehe auch Eingebaute Funktionen]

Bedingungen [!if, !else, !elseif, !endif]

  • Sie können Ausdrücke in Bedingungen verwenden.
  • else und elseif sind ebenfalls implementiert

🎉 Copied!

@startuml
!$a = 10
!$ijk = "foo"
Alice -> Bob : A
!if ($ijk == "foo") && ($a+10>=4)
Alice -> Bob : ja
!else
Alice -> Bob : Das sollte nicht erscheinen
!endif
Alice -> Bob : B
@enduml

Wiederholschleife [!while, !endwhile]

Sie können die Schlüsselwörter !while und !endwhile verwenden, um Wiederholschleifen zu erstellen.

Wiederholschleife (im Aktivitätsdiagramm)

🎉 Copied!

@startuml
!procedure $foo($arg)
  :procedure start;
  !while $arg!=0
    !$i=3
    #palegreen:arg=$arg;
    !while $i!=0
      :arg=$arg und i=$i;
      !$i = $i - 1
    !endwhile
    !$arg = $arg - 1
  !endwhile
  :procedure end;
!endprocedure

start
$foo(2)
end
@enduml

[Angepasst von QA-10838]

Wiederholschleife (im Mindmap-Diagramm)

🎉 Copied!

@startmindmap
!procedure $foo($arg)
  !while $arg!=0
    !$i=3
    **[#palegreen] arg = $arg
    !while $i!=0
      *** i = $i
      !$i = $i - 1
    !endwhile
    !$arg = $arg - 1
  !endwhile
!endprocedure

*:While
Loop;
$foo(2)
@endmindmap

Wiederholschleife (im Komponenten-/Deployment-Diagramm)

🎉 Copied!

@startuml
!procedure $foo($arg)
  !while $arg!=0
    [Komponente $arg] as $arg
    !$arg = $arg - 1
  !endwhile
!endprocedure

$foo(4)

1->2
3-->4
@enduml

[Ref. QA-14088]

Prozedur [!procedure, !endprocedure]

  • Prozedurnamen sollten mit einem $ beginnen
  • Argumentnamen sollten mit einem $ beginnen
  • Prozeduren können andere Prozeduren aufrufen

Beispiel:

🎉 Copied!

@startuml
!procedure $msg($source, $destination)
  $source --> $destination
!endprocedure

!procedure $init_class($name)
  class $name {
    $addCommonMethod()
  }
!endprocedure


!procedure $addCommonMethod()
  toString()
  hashCode()
!endprocedure


$init_class("foo1")
$init_class("foo2")
$msg("foo1", "foo2")
@enduml

Variablen, die in Prozeduren definiert werden, sind lokal. Das bedeutet, dass die Variable zerstört wird, wenn die Prozedur endet.

Rückgabefunktion [!function, !endfunction]

Eine Rückgabefunktion gibt keinen Text aus. Sie definiert lediglich eine Funktion, die Sie aufrufen können:
  • direkt in der Variablendefinition oder im Diagrammtext
  • von anderen Rückgabefunktionen
  • von Prozeduren

  • Funktionsnamen sollten mit einem $ beginnen
  • Argumentnamen sollten mit einem $ beginnen

🎉 Copied!

@startuml
!function $double($a)
!return $a + $a
!endfunction

Alice -> Bob : Das Doppelte von 3 ist $double(3)
@enduml

Es ist möglich, einfache Funktionsdefinitionen in einer Zeile zu verkürzen:

🎉 Copied!

@startuml
!function $double($a) !return $a + $a

Alice -> Bob : Das Doppelte von 3 ist $double(3)
Alice -> Bob : $double("Das funktioniert auch für Strings.")
@enduml

Wie in einer Prozedur (void-Funktion) sind Variablen standardmäßig lokal (sie werden zerstört, wenn die Funktion beendet wird). Sie können jedoch auf globale Variablen aus der Funktion zugreifen. Sie können jedoch das Schlüsselwort local verwenden, um eine lokale Variable zu erstellen, falls bereits eine globale Variable mit demselben Namen existiert.

🎉 Copied!

@startuml
!function $dummy()
!local $ijk = "local"
!return "Alice -> Bob : " + $ijk
!endfunction

!global $ijk = "foo"

Alice -> Bob : $ijk
$dummy()
Alice -> Bob : $ijk
@enduml

Standardwert für Argumente

Sowohl in Prozeduren als auch in Rückgabefunktionen können Sie Standardwerte für Argumente definieren.

🎉 Copied!

@startuml
!function $inc($value, $step=1)
!return $value + $step
!endfunction

Alice -> Bob : Nur eins mehr $inc(3)
Alice -> Bob : Zwei zu drei addieren: $inc(3, 2)
@enduml

Nur Argumente am Ende der Parameterliste können Standardwerte haben.

🎉 Copied!

@startuml
!procedure defaulttest($x, $y="DefaultY", $z="DefaultZ")
note over Alice
  x = $x
  y = $y
  z = $z
end note
!endprocedure

defaulttest(1, 2, 3)
defaulttest(1, 2)
defaulttest(1)
@enduml

Unzitierte Prozedur oder Funktion [!unquoted]

Standardmäßig müssen Sie Anführungszeichen setzen, wenn Sie eine Funktion oder eine Prozedur aufrufen. Es ist möglich, das Schlüsselwort unquoted zu verwenden, um anzugeben, dass eine Funktion oder eine Prozedur keine Anführungszeichen für ihre Argumente benötigt.

🎉 Copied!

@startuml
!unquoted function id($text1, $text2="FOO") !return $text1 + $text2

alice -> bob : id(aa)
alice -> bob : id(ab,cd)
@enduml

Schlüsselwortargumente

Wie in Python können Sie Schlüsselwortargumente verwenden:

🎉 Copied!

@startuml

!unquoted procedure $element($alias, $description="", $label="", $technology="", $size=12, $colour="green")
rectangle $alias as "
<color:$colour><<$alias>></color>
==$label==
//<size:$size>[$technology]</size>//

  $description"
!endprocedure

$element(myalias, "Diese Beschreibung ist %newline()über mehrere Zeilen", $size=10, $technology="Java")
@enduml

Dateien oder URLs einbinden [!include, !includemany, !includeonce]

Verwenden Sie die Direktive !include, um Dateien in Ihr Diagramm einzubinden. Mit URLs können Sie auch Dateien aus dem Internet/Intranet einbinden. Geschützte Internetressourcen können ebenfalls zugegriffen werden, dies wird in URL-Authentifizierung beschrieben.

Stellen Sie sich vor, Sie haben dieselbe Klasse, die in vielen Diagrammen erscheint. Anstatt die Beschreibung dieser Klasse zu duplizieren, können Sie eine Datei definieren, die die Beschreibung enthält.

🎉 Copied!

@startuml

interface List
List : int size()
List : void clear()
List <|.. ArrayList
@enduml

Datei List.iuml

interface List
List : int size()
List : void clear()

Die Datei List.iuml kann in vielen Diagrammen eingebunden werden, und jede Änderung in dieser Datei wird alle Diagramme ändern, die sie einbinden.

Sie können auch mehrere @startuml/@enduml Textblöcke in einer eingebundenen Datei haben und dann angeben, welchen Block Sie einbinden möchten, indem Sie !0 hinzufügen, wobei 0 die Blocknummer ist. Die Notation !0 bezeichnet das erste Diagramm.

Zum Beispiel, wenn Sie !include foo.txt!1 verwenden, wird der zweite @startuml/@enduml Block innerhalb von foo.txt eingebunden.

Sie können auch einer bestimmten @startuml/@enduml Textblock in einer eingebundenen Datei eine ID geben, indem Sie die Syntax @startuml(id=MY_OWN_ID) verwenden und dann den Block hinzufügen, indem Sie !MY_OWN_ID beim Einbinden der Datei hinzufügen, also etwas wie !include foo.txt!MY_OWN_ID verwenden.

Standardmäßig kann eine Datei nur einmal eingebunden werden. Sie können !include_many anstelle von !include verwenden, wenn Sie eine Datei mehrmals einbinden möchten. Beachten Sie, dass es auch eine Direktive !include_once gibt, die einen Fehler auslöst, wenn eine Datei mehrmals eingebunden wird.

Including Subpart [!startsub, !endsub, !includesub]

You can also use !startsub NAME and !endsub to indicate sections of text to include from other files using !includesub. For example:

file1.puml:

@startuml

A -> A : stuff1
!startsub BASIC
B -> B : stuff2
!endsub
C -> C : stuff3
!startsub BASIC
D -> D : stuff4
!endsub
@enduml

file1.puml would be rendered exactly as if it were:

@startuml

A -> A : stuff1
B -> B : stuff2
C -> C : stuff3
D -> D : stuff4
@enduml

However, this would also allow you to have another file2.puml like this:

file2.puml

@startuml

title this contains only B and D
!includesub file1.puml!BASIC
@enduml

This file would be rendered exactly as if:

@startuml

title this contains only B and D
B -> B : stuff2
D -> D : stuff4
@enduml

Builtin functions [%]

Some functions are defined by default. Their name starts by %

Name Description Example Return
%chr Return a character from a give Unicode value %chr(65)A
%darken Return a darken color of a given color with some ratio %darken("red", 20)#CC0000
%date Retrieve current date. You can provide an optional format for the date%date("yyyy.MM.dd' at 'HH:mm") current date
You can provide another optional time (on epoch format) %date("YYYY-MM-dd", %now() + 1*24*3600) tomorrow date
%dec2hex Return the hexadecimal string (String) of a decimal value (Int) %dec2hex(12)c
%dirpath Retrieve current dirpath %dirpath() current path
%feature Check if some feature is available in the current PlantUML running version %feature("theme")true
%false Return always false%false()false
%file_exists Check if a file exists on the local filesystem %file_exists("c:/foo/dummy.txt")true if the file exists
%filename Retrieve current filename %filename() current filename
%function_exists Check if a function exists %function_exists("$some_function")true if the function has been defined
%get_variable_value Retrieve some variable value %get_variable_value("$my_variable") the value of the variable
%getenv Retrieve environment variable value %getenv("OS") the value of OS variable
%hex2dec Return the decimal value (Int) of a hexadecimal string (String) %hex2dec("d") or %hex2dec(d)13
%hsl_color Return the RGBa color from a HSL color %hsl_color(h, s, l) or %hsl_color(h, s, l, a)%hsl_color(120, 100, 50)#00FF00
%intval Convert a String to Int %intval("42") 42
%is_dark Check if a color is a dark one %is_dark("#000000")true
%is_light Check if a color is a light one %is_light("#000000")false
%lighten Return a lighten color of a given color with some ratio %lighten("red", 20)#CC3333
%load_jsonLoad JSON data from local file or external URL%load_json("http://localhost:7778/management/health") JSON data
%lower Return a lowercase string %lower("Hello")hello in that example
%newline Return a newline %newline() a newline
%not Return the logical negation of an expression %not(2+2==4)false in that example
%now Return the current epoch time %now()1685547132 in that example (when updating the doc.)
%ord Return a Unicode value from a given character %ord("A")65
%lighten Return a lighten color of a given color with some ratio %lighten("red", 20)#CC3333
%reverse_color Reverse a color using RGB %reverse_color("#FF7700")#0088FF
%reverse_hsluv_color Reverse a color using HSLuv%reverse_hsluv_color("#FF7700")#602800
%set_variable_value Set a global variable %set_variable_value("$my_variable", "some_value") an empty string
%size Return the size of any string or JSON structure %size("foo")3 in the example
%string Convert an expression to String %string(1 + 2)3 in the example
%strlen Calculate the length of a String %strlen("foo")3 in the example
%strpos Search a substring in a string %strpos("abcdef", "ef") 4 (position of ef)
%substr Extract a substring. Takes 2 or 3 arguments %substr("abcdef", 3, 2)"de" in the example
%true Return always true%true()true
%upper Return an uppercase string %upper("Hello")HELLO in that example
%variable_exists Check if a variable exists %variable_exists("$my_variable")true if the variable has been defined exists
%version Return PlantUML current version %version()1.2020.8 for example
%invoke_procedure() Dynamically invoke a procedure by its name, passing optional arguments to the called procedure. %invoke_procedure("$go", "hello from Bob...") Depends on the invoked procedure
%call_user_func() Invoke a return function by its name with given arguments. %call_user_func("bold", "Hello") Depends on the called function
%splitstr Split a string into an array based on a specified delimiter. %splitstr("abc~def~ghi", "~")["abc", "def", "ghi"]

Logging [!log]

You can use !log to add some log output when generating the diagram. This has no impact at all on the diagram itself. However, those logs are printed in the command line's output stream. This could be useful for debug purpose.

🎉 Copied!

@startuml
!function bold($text)
!$result = "<b>"+ $text +"</b>"
!log Calling bold function with $text. The result is $result
!return $result
!endfunction

Alice -> Bob : This is bold("bold")
Alice -> Bob : This is bold("a second call")
@enduml

Memory dump [!dump_memory]

You can use !dump_memory to dump the full content of the memory when generating the diagram. An optional string can be put after !dump_memory. This has no impact at all on the diagram itself. This could be useful for debug purpose.

🎉 Copied!

@startuml
!function $inc($string)
!$val = %intval($string)
!log value is $val
!dump_memory
!return $val+1
!endfunction

Alice -> Bob : 4 $inc("3")
!unused = "foo"
!dump_memory EOF
@enduml

Assertion [!assert]

You can put assertions in your diagram.

🎉 Copied!

@startuml
Alice -> Bob : Hello
!assert %strpos("abcdef", "cd")==3 : "This always fails"
@enduml

Building custom library [!import, !include]

It's possible to package a set of included files into a single .zip or .jar archive. This single zip/jar can then be imported into your diagram using !import directive.

Once the library has been imported, you can !include file from this single zip/jar.

Example:

@startuml

!import /path/to/customLibrary.zip
' This just adds "customLibrary.zip" in the search path

!include myFolder/myFile.iuml
' Assuming that myFolder/myFile.iuml is located somewhere
' either inside "customLibrary.zip" or on the local filesystem

...

Search path

You can specify the java property plantuml.include.path in the command line.

For example:

java -Dplantuml.include.path="c:/mydir" -jar plantuml.jar atest1.txt

Note the this -D option has to put before the -jar option. -D options after the -jar option will be used to define constants within plantuml preprocessor.

Argument concatenation [##]

It is possible to append text to a macro argument using the ## syntax.

🎉 Copied!

@startuml
!unquoted procedure COMP_TEXTGENCOMP(name)
[name] << Comp >>
interface Ifc << IfcType >> AS name##Ifc
name##Ifc - [name]
!endprocedure
COMP_TEXTGENCOMP(dummy)
@enduml

Dynamic invocation [%invoke_procedure(), %call_user_func()]

You can dynamically invoke a procedure using the special %invoke_procedure() procedure. This procedure takes as first argument the name of the actual procedure to be called. The optional following arguments are copied to the called procedure.

For example, you can have:

🎉 Copied!

@startuml
!procedure $go()
  Bob -> Alice : hello
!endprocedure

!$wrapper = "$go"

%invoke_procedure($wrapper)
@enduml

🎉 Copied!

@startuml
!procedure $go($txt)
  Bob -> Alice : $txt
!endprocedure

%invoke_procedure("$go", "hello from Bob...")
@enduml

For return functions, you can use the corresponding special function %call_user_func() :

🎉 Copied!

@startuml
!function bold($text)
!return "<b>"+ $text +"</b>"
!endfunction

Alice -> Bob : %call_user_func("bold", "Hello") there
@enduml

Evaluation of addition depending of data types [+]

Evaluation of $a + $b depending of type of $a or $b

🎉 Copied!

@startuml
title
<#LightBlue>|= |=  $a |=  $b |=  <U+0025>string($a + $b)|
<#LightGray>| type | str | str | str (concatenation) |
| example |= "a" |= "b" |= %string("a" + "b") |
<#LightGray>| type | str | int | str (concatenation) |
| ex.|= "a" |=  2  |= %string("a" + 2)   |
<#LightGray>| type | str | int | str (concatenation) |
| ex.|=  1  |= "b" |= %string(1 + "b")   |
<#LightGray>| type | bool | str | str (concatenation) |
| ex.|= <U+0025>true() |= "b" |= %string(%true() + "b") |
<#LightGray>| type | str | bool | str (concatenation) |
| ex.|= "a" |= <U+0025>false() |= %string("a" + %false()) |
<#LightGray>| type |  int  |  int | int (addition of int) |
| ex.|=  1  |=  2  |= %string(1 + 2)     |
<#LightGray>| type |  bool  |  int | int (addition) |
| ex.|= <U+0025>true() |= 2 |= %string(%true() + 2) |
<#LightGray>| type |  int  |  bool | int (addition) |
| ex.|=  1  |= <U+0025>false() |= %string(1 + %false()) |
<#LightGray>| type |  int  |  int | int (addition) |
| ex.|=  1  |=  <U+0025>intval("2")  |= %string(1 + %intval("2")) |
end title
@enduml

Preprocessing JSON

You can extend the functionality of the current Preprocessing with JSON Preprocessing features:

  • JSON Variable definition
  • Access to JSON data
  • Loop over JSON array

(See more details on Preprocessing-JSON page)

Including theme [!theme]

Use the !theme directive to change the default theme of your diagram.

🎉 Copied!

@startuml
!theme spacelab
class Example {
  Theme spacelab
}
@enduml

You will find more information on the dedicated page.

Migration notes

The current preprocessor is an update from some legacy preprocessor.

Even if some legacy features are still supported with the actual preprocessor, you should not use them any more (they might be removed in some long term future).

  • You should not use !define and !definelong anymore. Use !function, !procedure or variable definition instead.
    • !define should be replaced by return !function
    • !definelong should be replaced by !procedure.
  • !include now allows multiple inclusions : you don't have to use !include_many anymore
  • !include now accepts a URL, so you don't need !includeurl
  • Some features (like %date%) have been replaced by builtin functions (for example %date())
  • When calling a legacy !definelong macro with no arguments, you do have to use parenthesis. You have to use my_own_definelong() because my_own_definelong without parenthesis is not recognized by the new preprocessor.

Please contact us if you have any issues.

%splitstr builtin function

🎉 Copied!

@startmindmap
!$list = %splitstr("abc~def~ghi", "~")

* root
!foreach $item in $list
  ** $item
!endfor
@endmindmap

Similar to:

🎉 Copied!

@startmindmap
* root
!foreach $item in ["abc", "def", "ghi"]
  ** $item
!endfor
@endmindmap

[Ref. QA-15374]

%get_all_theme() builtin function

You can use the %get_all_theme() builtin function to retreive a JSON array of all PlantUML theme.

🎉 Copied!

@startjson
%get_all_theme()
@endjson

[from version 1.2024.4]

%get_all_stdlib builtin function

Compact version (only standard library name)

You can use the %get_all_stdlib() builtin function to retreive a JSON array of all PlantUML stdlib names.

🎉 Copied!

@startjson
%get_all_stdlib()
@endjson

Detailed version (with version and source)

With whatever parameter, you can use %get_all_stdlib(detailed) to retreive a JSON object of all PlantUML stdlib.

🎉 Copied!

@startjson
%get_all_stdlib(detailed)
@endjson

[from version 1.2024.4]

%random builtin function

You can use the %random builtin function to retreive a random integer.

Nb param. Input Output
0 %random() returns 0 or 1
1 %random(n) returns an interger between 0 and n - 1
2 %random(min, max) returns an interger between min and max - 1

🎉 Copied!

@startcreole
| Nb param. | Input | Output |
| 0 | <U+0025>random()      | %random()     |
| 1 | <U+0025>random(5)     | %random(5)    |
| 2 | <U+0025>random(7, 15) | %random(7, 15) |
@endcreole

[from version 1.2024.2]


Privacy Policy      Advertise