Как в visual studio code сделать файл паскаль
Recently, I switched my OS to Ubuntu. I just started with collage and I have to learn pascal for my finals. But a problem occurred.
I installed Visual Studio Code and Pascal extension for it, but I am unable to run even a simple Hello World code. I wrote code, it saved automatically as .pas, but when I enter debug & run option in VSC it displays a message that says 'Open a file which can be debugged or run.', followed by 'debug' and 'run' buttons that I am unable to click and another message that says 'To further configure Debug and Run create a launch.json file.'
I am not even sure am I supposed to post questions such as this one on stackoverflow, but I sincerelly hope that someone could give me a hint on what to do. Solve this within Visual Studio Code or switch to another IDE (and which one would you recommend for Linux user) and pretend that nothing happened? Thanks in advance.
While the Pascal extension supports the language configuration (syntax highlighting, formatting,navigation, etc.) it does not appear to support debugging the language. And I don't see any vscode extension that looks like it would. I did see an online Pascal debugger.
3 Answers 3
- download release for your OS
- under "FPC Version" & "Lazarus Version" select trunkgit (or stable for an older version)
- click the "Install/Update FPC + Lazarus" button
Have you Installed Pascal extension which is available for code to smoothly run pascal code.
If you haven't then try installing this extension using,
Launch VS Code Quick Open (Ctrl+P), paste the following command, and press enter.
ext install alefragnani.pascal
You can always check,
to install and configure pascal in vscode.
I will direct you to the debugging page from the Visual Studio Code documentation that details how to use the debugger and configure a launch.json file. VSCode is a generic IDE so you need to give it some information about your project before it knows how to run the debugger. This is what launch.json is for.
If I could make a suggestion. When you're learning how to program, it's best to start with the basics. Write a small program in a text editor (VSCode is fine, or Vim, or Nano, or Notepad, or whatever). Save the file. Compile and run the program on the command line.
Once you put an IDE in the mix, you have to learn how to use that as well. If you're stuck on both parts, it can be hard to make progress. That said, it's good to learn how to use the IDE, and you should spend some time reading the documentation and working through some of the examples. It takes some time, but it will pay you back a thousand times when you can work more quickly.
This article is about setting up things so that you can code, compile and debug Free Pascal from Visual Studio Code.
This can be useful if you’re doing non-GUI work and you don’t want to rely on the full-blown Lazarus IDE. It also allows Windows users to write and test Linux programs using the WSL, which is what I did to test this setup. Note that similar steps can be used to configure VS Code for Pascal on a Mac if that’s your poison. At the very least, this is one more tool at your disposal when working with a legacy codebase.
Special credit goes to Mr Bee from the Pascal Indonesia group, whose article was the basis for mine.
Windows
On Windows, you can download and install Free Pascal directly from the website. Note that there is no native Windows 64-bit compiler for the latest version— you’ll need the native 32-bit compiler as well as the 64-bit cross-compiler. The source can be downloaded from a separate link.
Linux
In my case, I installed Free Pascal with Lazarus by running apt-get install lazarus on my Ubuntu WSL. This put the source code under /usr/share/fpcsrc/3.0.4 and my lazbuild file under /usr/bin . To install a newer version of Free Pascal, I later followed the steps on the wiki and downloaded the laz and src .deb files made available by Lazarus (these I installed directly using apt install ).
Bonus: Installing WSL
This is a bit of an aside, but if you want to run Ubuntu the way I did, this Microsoft article does a pretty good job of explaining the steps for activating the WSL. I used the Manual Installation Steps because I didn’t want to join the Windows Insiders Program.
Once the WSL is enabled, you can install a Linux subsystem e.g. Ubuntu from the Microsoft Store. You can verify which WSL distros are installed by running wsl.exe -l -v in PowerShell.
If you install the Remote - WSL extension for VS Code, you can launch the editor straight from your Linux console by typing:
The first time you do this, the VS Code Server will be installed. After that, it will launch VS Code in the context of your Linux subsystem.
OmniPascal
This VS Code extension brings Object Pascal support to VS Code, including code completion, outlining, etc.
Давайте поговорим о Code — Visual Studio Code.
Наш VSC будет пятирогим лазеростреляющим единорогом —после того как мы снабдим его самыми полезными расширения, которыми я пользуюсь каждый день.
О, а если вы еще не используете замечательный редактор VSC, под картинкой выше есть ссылка на официальный сайт, с которого его можно загрузить.
Самая эпичная тема для Visual Studio Code:
Автоматически находит, парсит и дополняет названия методов и событий для всех доступных файлов. Поддерживает Typescript и TSX.
Это расширение отобразит в редакторе размер импортируемого пакета в одной строчке с соответствующим методом. Расширение использует Webpack с babili-webpack-plugin для обнаружения импортируемого объекта и оценки его размера.
Простое расширение, которое делает отступы более читабельными.
Расширение VSCode, которое автоматически дополняет название CSS-класса для HTML-атрибута class на основе определений, найденных в вашей рабочей области или внешних файлов, на которые ссылается элемент link .
Простой способ предпросмотра SVG.
Не могу жить без него — пакет VSCode для форматирования JavaScript / TypeScript / CSS с использованием Prettier.
Подсказки, отладка и встроенные команды для React Native.
Это расширение позволяет в VSCode использовать горячие клавиши Sublime Text 3. Попробуйте потестировать его, открыв консоль сочетанием клавиш:
cmd ⌘ + P — Mac
ctrl + P — Windows
В этой консоли можно быстро перейти к файлам, а также, если добавить символ > перед поисковой строкой, можно искать действия, такие как переключение встроенного терминал, установку расширения и так далее.
Очень удобная штука для тех из нас, кто привык к ST3. 🎉
Плагин VSCode, который автоматически дополняет имена модулей npm в операциях импорта.
Добавляет подсветку синтаксиса и поддержку разметки HTML внутри строк JavaScript и TypeScript, как это используется в lit-html и других фреймворках.
Это расширение предназначено для подсветки парных открывающих или закрывающих тегов — функциональности, отсутствующей в VSCode, но которая должна бы быть встроена в редактор из коробки.
Это расширение перезагружает встроенные возможности Visual Studio Code по работе с Git. Оно в наглядном виде предоставляет информацию об авторстве изменений в Git, а также облегчает перемещение по репозиториям и позволяет отслеживать историю изменений файлов или веток, использовать команды сравнения кода и многое другое.
Git Project Manager (GPM) — это расширение Microsoft VSCode, которое позволяет вам открыть новое окно на основе git-репозитория непосредственно из VSCode.
Просмотр логов git и истории изменения файлов и сравнение веток или коммитов.
Удобный способ создания, дублирования, перемещения, переименования и удаления файлов и каталогов.
Настраиваемое расширение для раскрашивания парных скобок. Крайне полезно при работе с большим количеством обратных вызовов.
Это расширение подсвечивает CSS / веб-цвета, найденные в вашем документе.
Переход к CSS-свойствам идентификаторов (id) и классов непосредственно из файлов HTML. Поддерживает переключение и между файлами и быстрый переход из одного в другой.
Инструмент для отладки JavaScript-кода или любого другого кода в браузере Chrome.
Выполняет JavaScript-код в консоли параллельно с тем, как вы его пишете. (Полезно для быстрых демонстраций).
Мгновенно выделяет и удаляет конечные пробелы.
Это расширение пригодится всем, кто пишет на TypeScript и хочет, чтобы VSC организовал импорты за него.
Метрики, инсайты и отслеживание времени, автоматически генерируемые на основании статистики вашей работы по программированию.
Поддержка Vue для VSCode
Запустите фрагмент кода или целый файл сразу в нескольких языках.
Расширенная поддержка автозаполнения и рефакторинга кода на PHP.
Иконки для редактора VSCode.
Пользуйтесь Jest от Facebook с удовольствием.
Сниппеты кода для разработки на React.js в синтаксисе ES6.
Благодарю вас за то, что прочитали эту статью! Переходите по ссылке в твиттере, чтобы узнать о других расширениях VSCode. Знаете еще какие-то полезные плагины, которые не упомянуты здесь? Пожалуйста, пишите их в комментариях❤
Если статья оказалась полезной для вас, не забудьте поаплодировать оригиналу и переводу. Вы также можете подписаться на твиттер автора , где он часто публикует другие полезные подборки.
It adds support for the Pascal language and its dialects like Delphi and FreePascal.
Here are some of the features that Pascal provides:
- Syntax highlighting for files, forms and projects
- A huge set of Snippets
- Source code navigation
Coding with style
Syntax Highlighting
Pascal supports full syntax highlighting for Delphi and FreePascal
Snippets
Almost 40 snippets are available
Format Code
Check out Pascal Formatter documentation.
Code Navigation
Navigate to any language element (methods, attributes, classes, interfaces, and so on) inside Pascal files. It supports native VS Code commands like:
- Go to Symbol
- Go to Definition
- Peek Definition
- Find All References
It uses GNU Global, a source code tagging system, which means that it has some limitations if you compare with an AST parsing.
Installing and Configuring GNU Global
Let's say you extract GNU Global and CTags in C:\gnu folder. The two new entries in %PATH% should be:
- GNU Global: C:\gnu\glo653wb\bin
- Excuberant Tags: C:\gnu\ctags58\ctags58
Also make sure Python is in %PATH%
GNU Global uses CTags + Python Pygments as plugin in order to recognizes Pascal source code, so you have to configure them.
- GTAGSCONF : C:\gnu\glo653wb\share\gtags\gtags.conf
- GTAGSLABEL : pygments
NOTE: For now, it was tested only on Windows, but since these tools are multiplatform (in fact, it comes from Unix), it should work on Linux and Mac.
Code Navigation
To enable Code Navigation, the extension depends on GNU Global and Exuberant Tags and for that, you must run gtags on the Root folder, so the tags are created. In order to make life easier, two commands where added:
- Pascal: Generate Tags: Use this to create or reset the tags in the current project. You just have to do it once.
- Pascal: Update Tags: Use this to update the tags for current project. You should use this command to update the references when any source code is updated.
Available Settings
Controls how the code navigation should work. Specially useful if you work with huge projects
- workspace : Full featured code navigation
- file : Limited to Go to Symbol in File command
- Controls if the extension should automatically generate tags in projects opened for the first time
For huge projects, its recommended to use:
Use this Task Examples, so you can:
- Compile Delphi and FreePascal projects:
- Navigate to Errors/Warnings/Hints, using the native View / Errors and Warnings command
Building Tasks
If you want to build tasks (Task: Run Task Build) you can use the snippets below.
What's new in Pascal 9.5
- Adds Web support
- Adds Getting Started / Walkthrough
- Adds Virtual Workspaces support
- Adds Workspace Trust support
Pascal is an open source extension created for Visual Studio Code. While being free and open source, if you find it useful, please consider supporting it
It adds support for the Pascal language and its dialects like Delphi and FreePascal.
Here are some of the features that Pascal provides:
- Syntax highlighting for files, forms and projects
- A huge set of Snippets
- Source code navigation
Coding with style
Pascal supports full syntax highlighting for Delphi and FreePascal
Almost 40 snippets are available
Check out Pascal Formatter documentation.
Navigate to any language element (methods, attributes, classes, interfaces, and so on) inside Pascal files. It supports native VS Code commands like:
- Go to Symbol
- Go to Definition
- Peek Definition
- Find All References
It uses GNU Global, a source code tagging system, which means that it has some limitations if you compare with an AST parsing.
Installing and Configuring GNU Global
Let's say you extract GNU Global and CTags in C:\gnu folder. The two new entries in %PATH% should be:
- GNU Global: C:\gnu\glo653wb\bin
- Excuberant Tags: C:\gnu\ctags58\ctags58
Also make sure Python is in %PATH%
GNU Global uses CTags + Python Pygments as plugin in order to recognizes Pascal source code, so you have to configure them.
- GTAGSCONF : C:\gnu\glo653wb\share\gtags\gtags.conf
- GTAGSLABEL : pygments
NOTE: For now, it was tested only on Windows, but since these tools are multiplatform (in fact, it comes from Unix), it should work on Linux and Mac.
To enable Code Navigation, the extension depends on GNU Global and Exuberant Tags and for that, you must run gtags on the Root folder, so the tags are created. In order to make life easier, two commands where added:
- Pascal: Generate Tags: Use this to create or reset the tags in the current project. You just have to do it once.
- Pascal: Update Tags: Use this to update the tags for current project. You should use this command to update the references when any source code is updated.
Controls how the code navigation should work. Specially useful if you work with huge projects
- workspace : Full featured code navigation
- file : Limited to Go to Symbol in File command
- Controls if the extension should automatically generate tags in projects opened for the first time
For huge projects, its recommended to use:
Use this Task Examples, so you can:
- Compile Delphi and FreePascal projects:
- Navigate to Errors/Warnings/Hints, using the native View / Errors and Warnings command
If you want to build tasks (Task: Run Task Build) you can use the snippets below.
Читайте также: