Plantuml visual studio code как пользоваться
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
Rich PlantUML support for Visual Studio Code.
The server render is now very recommended by this extension, since it's much faster and much easier to setup, while the major weakness has been improved:
- Enables POST method, you can now render very-large diagrams
- The extension comes with a new include processor , you won't encounter include problems again.
To make sure you can benifit from this update, make sure your plantuml server enables POST support.
- Preview Diagram, Press Alt + D to start PlantUML preview ( option + D on MacOS).
- Auto update.
- Zoom & scroll support.
- Multi-Page Diagram support.
- Instant preview, if diagram's been exported.
- From local or server.
- Snap to Border
- At cursor, in current file, in whole workspace, in workspace selected.
- Concurrent export.
- Generate URLs.
- Multi-Page Diagram support.
- From local or server.
- Image map (cmapx) support.
- Format PlantUML code. (Deprecated)
- All type syntax highlight.
- All type snippets.
- Basic auto completion & macro signature support
- Symbol List support.
- Multi-root Workspace Support.
- MarkDown integrating support. View Demo
- Extracting source from images support.
Notice: If you use customize plantuml.jar , please update to the latest version to enable Multi-Page Diagram support . (Later than V1.2017.15 )
Format PlantUML code is Deprecated. Don't depend on it, use it only when it works right. I had force disable it in auto-format cases (format on save).
*.wsd , *.pu , *.puml , *.plantuml , *.iuml
Launch VS Code Quick Open (Ctrl+P), paste the following command, and press enter.
ext install plantuml
Depend on which render you choose, plugin has diffrerent requirements.
Requirements for PlantUMLServer render
Requirements for Local render
It's necessary to have following installed:
-
: Platform for PlantUML running. : PlantUML requires it to calculate positions in diagram.
Quick Install for Mac
Quick Install for Windows
The plugin has an integrated copy of plantuml.jar and GraphViz, so you are normally good to go. But if you want to use your own jar or a different version of GraphViz (maybe a newer version, or with many dependent jars):
- download the latest plantuml.jar or install it using chocolatey (see below).
- specify the jar location with the extension setting plantuml.jar .
- specify the GraphViz installation by defining the Windows environment variable GRAPHVIZ_DOT , e.g., c:\program files\graphviz\bin\dot.exe if you installed plantuml with chocolatey, which automatically installs the latest GraphViz as a dependency.
For windows users, majkinetor introduced a way to install plantuml and its dependencies easily. Run cmd.exe as Administrator, and run two commands as follows (the first command is not needed and will fail if you already have chocolatey installed).
If you've installed java, but still prompts "java not installed", please add java bin path to PATH environment variable.
Typical Files Organization
- Default extension settings works for independent Plantuml projects.
- If Plantuml files are only part of your project (as documetation), use plantuml.diagramsRoot and plantuml.exportOutDir to setting up the organization, for example:
You'll get export results like:
Include Files Search Logic
Latest version has changed the include files search logic once again. It is possible to configure includepaths now in settings.json.
The new search order is as follows:
- The folder of the rendered file
- The includepaths as configured in settings.json
The setting includeSearch is not needed anymore, since the folder of the plantuml file and the diagramsRoot are always both in the include path.
To new projects, it's recommended not to rely on diagramsRoot and configure all required includepaths explicitly.
Thanks anotherandi for the brilliant idea and implementation!
- Zoom operations (since version 2.7.0):
- Zoom to select area
- Pinch to zoom (TouchPad)
- Click to zoom in, alt + click to zoom out
- Ctrl + mouse scroll to zoom in/out
- Middle mouse button click to toggle zoom
- Zoom in / zoom out / toggle buttons of the controls bar.
- Right mouse button drag
- Two-finger move to pan (TouchPad)
- Mouse scroll
- Scroll to most bottom/right/top/left, preview will snap to that border.
e.g. Snap to Bottom is useful while writing long activity diagrams, which helps you keep focus in the latest part in the bottom.
Extract Diagram Source
PlantUML formatter is disabled (since v2.8.3) if editor.formatOnSave is on. Because the formatter is not reliable enough according to user feedbacks.
This plugin integrates all type diagram snippets. They are splitted into 9 sections:
- diagram : snippets for general diagrams elements.
- activity : snippets for activity diagrams.
- class : snippets for class diagrams.
- component : snippets for component diagrams.
- state : snippets for state diagrams.
- usecase : snippets for usecase diagrams.
- sequence : snippets for sequence diagrams.
- ui : snippets for salt diagrams.
- egg : snippets for some funny diagrams, like sudoku, earth.
For exsample, type acife (short version) to trigge following snippet ( activity➤if・else ):
About Symbol List (List diagrams of file)
Press Ctrl+Shift+O to list all diagrams in the file. You can name the diagram when diagram starts.
@startuml diagram name sudoku @enduml
Plugin supports two renders: Local and PlantUMLServer .
Local is the default and traditional way. If you care more about export speed, you should try PlantUMLServer.
Advantages and Disadvantages of PlantUMLServer Render
- 15X times faster export and much quicker preview response.
- Don't have to set local enviroments if you have a server in your team.
- You don't need plantuml.exportConcurrency , because it's unlimited in concurrency.
Use PlantUML Server as Render
Open user setting, and configure like:
Multiple languages support
@startuml / @enduml is still recommended, so that PlantUML code in Markdown can be managed by other function of this plugin.
This extension contributes the following settings.
- plantuml.render : Select diagram render for both export and preview.
PlantUMLServer Render Settings:
- plantuml.server : PlantUML server to generate UML diagrams on-the-fly.
Local Render Settings:
- plantuml.diagramsRoot : Specifies where all diagram files located (relative to workspace folder).
- plantuml.exportOutDir : Exported workspace diagrams will be organized in this directory (relative path to workspace folder).
- plantuml.fileExtensions : File extensions that find to export. Especially in workspace settings, you may add your own extensions so as to export diagrams in source code files, like ".java".
- plantuml.exportFormat : format to export. default is not set, user may pick one format everytime exports. You can still set a format for it if you don't want to pick.
- plantuml.exportSubFolder : export diagrams to a folder which has same name with host file.
- plantuml.exportConcurrency : decides concurrency count when export multiple diagrams.
- plantuml.exportMapFile : Determine whether export image map (.cmapx) file when export.
- plantuml.previewAutoUpdate : Dedecides if automatically update the preview window.
- plantuml.urlFormat : URL format. Leave it blank to pick format everytime you generate a URL.
- plantuml.urlResult : URL result type. Simple URL or ready for MarkDown use.
- plantuml.lintDiagramNoName : Decides if it should lint when diagram is unmaned.
Please post and view issues on GitHub
- Japanese: Kohei Arao, kannkyo
- Tranditional Chinese: Alan Tsai
- German: Fabian F.
- French: Zepmanbc, FlorianKempenich
- Danish: Mikkel O. Laursen
Thanks for your encouragements!
Claus Appel, 三島木一磨, 富吉佑季, 黒田悦成, Jared Birdsall, Suleyman Cabir Ciplak, Malcolm Learner, Сысоев Максим, Gokan Kenichi, anb0s, Lawrence Yarian, Ahmad Ragab, 山田暁通
Enjoy!
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
В Visual Studio 2017 с удивлением обнаружил отсутствие проектов для моделирования (UML). Нет, можно запустить 2015, но держать две студии как-то не комильфо, да и при параллельном изменении диаграмм появляется проблема с потерей изменений того, кто сохранил не последним.
Озадачившись вопросом что можно использовать для построения UML диаграмм, наткнулся на PlanUML. Что это такое? Да много чего. Нотация, парсер и куча плагинов к наиболее распространенным средам разработки. Существенным достоинством данного подхода является хранение диаграмм в виде plan-text. Т.е. файл с моделью, это просто текстовый файл, при изменении файла несколькими людьми в параллели, даже если в результате коммитов он разъедется, всегда можно будет посмотреть кто и какие изменения внес и смержить их руками. Не все, к сожалению радужно. Применить PlantUML для хоть немного серьезной ArchiMate диаграммы (да, он и это умеет) не получилось. То ли я не владею дао, то ли в случаях, когда расположение элементов играет существенную роль, его применять не получится. Но не суть, мы сегодня про UML. Поэтому, устанавливаем и начинаем работать с PlantUml. Поехали.
Установка1. В Visual Studi Code переходим в расширения и поиском находим PlantUML от jebbs-а. Ставим его.
2. Устанавливаем Java.
3. Перезагружаем компьютер.
4. Устанавливаем Graphviz.Использование
Начнем с самого простого примера. В Visual Studio Code создаем новый файл и сохраняем его как Diagram с расширением, например, wsd.
В файле пишем:Открываем Command Palette (F1 или Ctrl+Shift+P) и набираем команду:
>PlantUML: Export Current Diagram
Выбираем png и в директории где находился исходный файл будет создана папка с именем диаграммы, в которой появится файл с расширением png содержащий нашу диаграмму:3 комментария:
божественно, особенно то, что можно руками всё написать, не рисуя все эти прямоугольники адские, стрелки и прочую муру
Особенно хорошо, то что в отличии от нетекстовых форматов, это и мерджится нормально.
Стоит еще указать, что после инсталяции Graphviz надо еще сделать пост инсталл. В командной строке под админ правами набрать C:\Program Files\Graphviz 2.44.1\bin>dot -c
Только после этого заработаетПоговорим про высокоуровневые концепции распределенных систем, их типы, как такие системы строятся, и где нужно подстелить соломку.
Оценивать эффективность процесса программирования количеством написанных строк кода — то же самое, что оценивать процесс создания самолёта по его весу.
© Бил Гейтс
В предыдущей статье инструкция что устанавливать и как начать работать. Сегодня поговорим про нотацию, используемую в PlantUML для построения диаграмм классов. Напоминаю, что диаграмма классов (англ. Static Structure diagram) – это структурная диаграмма нотации UML, демонстрирующая общую структуру иерархии классов системы, их кооперацию, атрибуты (поля), методы, интерфейсы и взаимосвязи между ними. Широко применяется не только для документирования и визуализации, но также для конструирования посредством прямого или обратного проектирования.
Итак, начинаем.Задание класса
Класс и его элементы в PlantUML можно задать двумя способами: указав имя класса и через двоеточие член класса или указав перед именем ключевое слово class:
Первый способ избыточен (нам для каждого свойства придется указывать, к какому классу оно относится), да и неприменим, когда мы хотим промоделировать отношения классов без их внутреннего устройства. Поэтому далее я буду использовать нотацию с применением ключевого слова class. Для того чтобы редактору дать понять, какие члены относятся к классу, используются фигурные скобки. Дальше редактор определяет: данные или метод находятся перед ним на основе круглых скобок. Пусть у нас есть самолет, который умеет взлетать, и у него есть некоторая коллекция двигателей. Текст такой диаграммы может иметь вид:
В Visual Studio 2017 с удивлением обнаружил отсутствие проектов для моделирования (UML). Нет, можно запустить 2015, но держать две студии как-то не комильфо, да и при параллельном изменении диаграмм появляется проблема с потерей изменений того, кто сохранил не последним.
Оценивать эффективность процесса программирования количеством написанных строк кода — то же самое, что оценивать процесс создания самолёта по его весу.
© Бил Гейтс
В Visual Studio 2017 с удивлением обнаружил отсутствие проектов для моделирования (UML). Нет, можно запустить 2015, но держать две студии как-то не комильфо, да и при параллельном изменении диаграмм появляется проблема с потерей изменений того, кто сохранил не последним.
Озадачившись вопросом, что можно использовать для построения UML диаграмм, наткнулся на PlanUML. Что это такое? Да много чего. Нотация, парсер и куча плагинов к наиболее распространенным средам разработки. Существенным достоинством данного подхода является хранение диаграмм в виде plan-text, т.е. файл с моделью – это просто текстовый файл. При изменении файла несколькими людьми в параллели, даже если в результате коммитов он разъедется, всегда можно будет посмотреть, кто и какие изменения внес, и смержить их руками. Не все, к сожалению, радужно. Применить PlantUML для хоть немного серьезной ArchiMate диаграммы (да, он и это умеет) не получилось. То ли я не владею дао, то ли в случаях, когда расположение элементов играет существенную роль, его применять не получится. Но не суть, мы сегодня про UML, поэтому, устанавливаем и начинаем работать с PlantUml. Поехали.Установка
1. В Visual Studi Code переходим в расширения и поиском находим PlantUML от jebbs-а. Ставим его.
2. Устанавливаем Java.
3. Перезагружаем компьютер.
4. Устанавливаем Graphviz.Использование
Начнем с самого простого примера. В Visual Studio Code создаем новый файл и сохраняем его как Diagram с расширением, например, wsd.
В файле пишем:The server render is now very recommended by this extension, since it's much faster and much easier to setup, while the major weakness has been improved:
- Enables POST method, you can now render very-large diagrams
- The extension comes with a new include processor , you won't encounter include problems again.
To make sure you can benifit from this update, make sure your plantuml server enables POST support.
Features
- Preview Diagram, Press Alt + D to start PlantUML preview (option + D on MacOS).
- Auto update.
- Zoom & scroll support.
- Multi-Page Diagram support.
- Instant preview, if diagram's been exported.
- From local or server.
- Snap to Border
- At cursor, in current file, in whole workspace, in workspace selected.
- Concurrent export.
- Generate URLs.
- Multi-Page Diagram support.
- From local or server.
- Image map (cmapx) support.
- Format PlantUML code. (Deprecated)
- All type syntax highlight.
- All type snippets.
- Basic auto completion & macro signature support
- Symbol List support.
- Multi-root Workspace Support.
- MarkDown integrating support. View Demo
- Extracting source from images support.
Notice: If you use customize plantuml.jar , please update to the latest version to enable Multi-Page Diagram support . (Later than V1.2017.15 )
Format PlantUML code is Deprecated. Don't depend on it, use it only when it works right. I had force disable it in auto-format cases (format on save).
Supported Formats
*.wsd , *.pu , *.puml , *.plantuml , *.iuml
How to install
Launch VS Code Quick Open (Ctrl+P), paste the following command, and press enter.
ext install plantuml
Requirements
Depend on which render you choose, plugin has diffrerent requirements.
Requirements for PlantUMLServer render
Requirements for Local render
It's necessary to have following installed:
-
: Platform for PlantUML running. : PlantUML requires it to calculate positions in diagram.
Quick Install for Mac
Quick Install for Windows
The plugin has an integrated copy of plantuml.jar and GraphViz, so you are normally good to go. But if you want to use your own jar or a different version of GraphViz (maybe a newer version, or with many dependent jars):
- download the latest plantuml.jar or install it using chocolatey (see below).
- specify the jar location with the extension setting plantuml.jar .
- specify the GraphViz installation by defining the Windows environment variable GRAPHVIZ_DOT , e.g., c:\program files\graphviz\bin\dot.exe if you installed plantuml with chocolatey, which automatically installs the latest GraphViz as a dependency.
Choco install
For windows users, majkinetor introduced a way to install plantuml and its dependencies easily. Run cmd.exe as Administrator, and run two commands as follows (the first command is not needed and will fail if you already have chocolatey installed).
If you've installed java, but still prompts "java not installed", please add java bin path to PATH environment variable.
Typical Files Organization
- Default extension settings works for independent Plantuml projects.
- If Plantuml files are only part of your project (as documetation), use plantuml.diagramsRoot and plantuml.exportOutDir to setting up the organization, for example:
You'll get export results like:
Include Files Search Logic
Latest version has changed the include files search logic once again. It is possible to configure includepaths now in settings.json.
The new search order is as follows:
- The folder of the rendered file
- The includepaths as configured in settings.json
- The diagramsRoot
The setting includeSearch is not needed anymore, since the folder of the plantuml file and the diagramsRoot are always both in the include path.
To new projects, it's recommended not to rely on diagramsRoot and configure all required includepaths explicitly.
Thanks anotherandi for the brilliant idea and implementation!
Preview Demos
- Zoom operations (since version 2.7.0):
- Zoom to select area
- Pinch to zoom (TouchPad)
- Click to zoom in, alt + click to zoom out
- Ctrl + mouse scroll to zoom in/out
- Middle mouse button click to toggle zoom
- Zoom in / zoom out / toggle buttons of the controls bar.
- Right mouse button drag
- Two-finger move to pan (TouchPad)
- Mouse scroll
- Scroll to most bottom/right/top/left, preview will snap to that border.
e.g. Snap to Bottom is useful while writing long activity diagrams, which helps you keep focus in the latest part in the bottom.
Читайте также: