Visual Studio Code

1. Introduction

Visual Studio Code is a powerful, free and open-source, cross-platform text editor for programmers.

Below we describe how to configure it to be a perfect code editor for Pascal, and in particular for your Castle Game Engine projects. We’re proud to provide an LSP server that will make VS Code do intelligent code completion that works great with Pascal and automatically completes all Castle Game Engine API.

Visual Studio Code completing CGE code
Note
The configuration described here also works with VSCodium, a version of VS Code built using 100% open-source code (without e.g. Microsoft telemetry).

2. Make Castle Game Engine invoke VS Code

Go to Castle Game Engine editor preferences, "Code Editor" tab, and select the "Visual Studio Code".

Configure VS Code in CGE Preferences

This will make CGE automatically open VS Code when you open Pascal file

  • by double-clicking Pascal unit from CGE editor "Files" panel,

  • by double-clicking a message in the "Output" window referencing some Pascal file,

  • using menu item "Code → Open Project in Code Editor",

  • and in all other cases when CGE wants to open Pascal file.

3. Pascal syntax highlighting

We recommend installing Pascal magic extension to get Pascal code highlighting.

It’s available in the VS Code marketplace, so you can just search for it and install right inside the VS Code "Extensions" panel.

Note

Searching extensions' marketplace for "Pascal" will yield a number of alternatives. They will likely work just as well for your Pascal and CGE editing, go ahead and try them. We just recommend choosing any "simple" extension that adds Pascal highlighting but doesn’t do code completion and parsing (because the LSP server will take care of it).

E.g. Pascal Language Basics is also a solid choice. We recommended it in the past. We switched to "Pascal magic" mainly because it handles better difficult long code in tools/castle-editor/code/framedesign.pas.

4. Pascal code completion

We provide an LSP server that implements an intelligent code completion for Pascal and is aware of Castle Game Engine units and default syntax options (e.g. FPC ObjFpc mode).

Note
Our LSP server is based on Philip Zander's LSP server which in turn relies on Lazarus CodeTools to do the code completion. So inside there is really a lot of work and testing from many people in the Pascal ecosystem to make it powerful.

To use it with VS Code:

  1. Install the Pascal Language Server Extension for Visual Studio Code. It’s easiest to do this by:

    • Downloading this VSIX file.

    • Use "Install from VSIX…​" menu item in VS Code to install it:

      Install from VSIX
    • Once done, you will see "Pascal Language Server" extension installed. Make sure it is enabled.

  2. Configure the extension, pointing it to your FPC, Lazarus, and pasls (our LSP server).

    VS Code Extension configuration
    • Open the extension settings.

    • Set Env: FPCDIR to point to the FPC source code. If you use FPC bundled with CGE, this should look like <cgepath>/tools/contrib/fpc/src/.

    • Set Env: FPCTARGET to your OS, like linux or win64.

      Note

      Use operating system names that match FPC and CGE. You can see valid OS names:

      • In CGE editor menu "Run → Platform (To Compile And Run) → …​".

      • If you execute on the command-line build tool as castle-engine --help. Look for possible arguments for the --os option.

      You can also leave it empty, our LSP will autodetect it.

    • Set Env: FPCTARGETCPU to your CPU, like x86_64.

      Note

      Use processor names that match FPC and CGE. You can see valid CPU names:

      • In CGE editor menu "Run → Platform (To Compile And Run) → …​".

      • If you execute on the command-line build tool as castle-engine --help. Look for possible arguments for the --cpu option.

      You can also leave it empty, our LSP will autodetect it.

    • Set Env: LAZARUSDIR to your Lazarus (source) directory. This is optional, fill it if you have Lazarus installed. It will enable to find LCL units and do the code completion for LCL components too.

    • Set Env: PP to your FPC executable. If you use FPC bundled with CGE, this should look like <cgepath>/tools/contrib/fpc/bin/fpc-cge. Add .exe extension on Windows. If you use regular FPC, this is a path to your regular FPC executable (fpc, fpc.exe, fpc.sh).

    • Finally, set Executable to point to our LSP server, inside CGE bin subdirectory. This should look like <cgepath>/bin/pasls. Add .exe extension on Windows.

  1. Enjoy!

    • Open any Castle Game Engine project.

    • You can open it from Castle Game Engine editor (e.g. by "Code → Open Project in Code Editor" menu item).

    • Or you can open it from VS Code, using "File → Open Folder".

    • Place your cursor somewhere, hit Ctrl + Space and enjoy a proper code completion.

      VS Code Extension configuration
    • Right click on any Pascal item and use "Go To Definition", "Go To Declaration" or just Ctrl + click on it to move around. You can also peek at definition and declaration using "Peek → …​".

Note
There are more VS Code extension settings, but most of them are not handled (and not necessary) for our LSP server, they are only handled by the alternative Ryan Joseph's Pascal LSP server.
Note

If you have installed FPC yourself using fpcupdeluxe on Unix, remember to point Env: PP to the fpc.sh script (and not to the fpc binary) that should always be used to execute FPC managed by fpcupdeluxe on Unix.

In general, the Env: PP executable may be run by CodeTools, which may assume this FPC version "knows" standard RTL paths. That’s why it’s important to pass fpc.sh (in case of fpcupdeluxe) or fpc-cge (in case of FPC bundled with CGE) and not the "bare" fpc executable.

5. Compiling and Running

You can configure VS Code to compile and run CGE applications.

Note
The proces below allows for many tweaks for advanced VS Code users but it may look intimidating. Remember this is optional. You can always just compile and run CGE applications from Castle Game Engine editor (use F9, or "Run → Compile And Run" menu item).

5.1. Tasks

To compile and run CGE projects from VS Code, you can define a tasks.json file with contents like this: sample_vs_code_tasks.json (use raw version of sample_vs_code_tasks.json for easy copy-paste).

This file defines a few CGE tasks and makes the task "(CGE) Compile And Run" the default.

Use this sample as:

  • your personal (user-specific, apply to all projects) tasks. Use command "Tasks: Open User Tasks" from the palette (Ctrl + Shift + P) to edit this file.

  • or place these tasks inside the .vscode folder of your project. Use menu item "Terminal → Configure Tasks" to edit this file.

5.2. Environment for tasks

The above sample tasks.json assumes that the CGE build tool called castle-engine can be found on environment variable PATH.

Make sure your environment is set correctly to make it work:

  • Extend the PATH environment variable to contain the bin subdirectory of your CGE directory. This is where castle-engine[.exe] file should be. If you don’t know how to set the environment variable, search the Internet (e.g. these are quick instructions how to do it on various Windows versions).

    Alternative: Edit the sample tasks.json to provide full path to the build tool exe, like /home/example/castle_game_engine/bin/castle-engine instead of just castle-engine.

  • (Optional) Make sure that compiler (FPC or Delphi) is on PATH, so that our build tool can find it.

    This is not necessary in the common case, when you use FPC bundled with CGE.

  • (Optional) Set CASTLE_ENGINE_PATH environment variable to point to the root of CGE.

    This is not necessary if you run the build tool from CGE subdirectory bin/, it will auto-detect CGE path then correctly.

  • Remember to restart all applications (like VS Code) that need to be aware of new environment variables' values.

5.3. Keybindings for tasks

You can bind keys to the CGE tasks, to have a similar experience in VS Code as in CGE editor:

  • F9 should do "(CGE) Compile And Run"

  • Ctrl+F9 should do "(CGE) Compile"

  • Shift+F9 should do "(CGE) Run"

To adjust keybindings for tasks, you have to edit your keybindings.json file. See adding shortcuts to tasks and editing keybindings for information how to do this.

Define keys like this in keybindings.json:

    {
        "key": "ctrl+f9",
        "command": "workbench.action.tasks.runTask",
        "args": "(CGE) Compile"
    },
    {
        "key": "shift+f9",
        "command": "workbench.action.tasks.runTask",
        "args": "(CGE) Run"
    }

To define key shortcut for default task "(CGE) Compile And Run" just adjust the "Tasks: Run Build Task" shortcut to F9 in VS Code key shortcuts settings. You can also adjust it by editing keybindings.json, as above.

5.4. Debugging

CGE applications compiled in debug mode contain debug symbols compatible with GDB. Any debugger extension in VS Code based on GDB should work, like Native Debug.

This is a sample launch.json you can use (edit app_name as necessary):

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Debug",
            "type": "gdb",
            "request": "launch",
            "target": "./app_name",
            "cwd": "${workspaceFolder}",
            "valuesFormatting": "parseText"
        }
    ]
}

For debugging code compiled with FPC, it’s very useful to set a breakpoint at fpc_raiseexception. Just define a breakpoint at such function name (don’t worry that it may seem like it doesn’t work — it will actually work once you run the project).

Note

The keybindings are of course your personal choice. Personally I use these:

  • F5 - Debug: Toggle Breakpoint (consistent with Delphi / Lazarus)

  • Shift + F5 - Debug: Start Debugging

  • Ctrl + F2 - Debug: Stop (consistent with Delphi / Lazarus)

6. More Information and Credits

7. Other text editors

The LSP server is fully useful with any text editor that supports LSP, not only VS Code.

7.1. Emacs

The short version is:

  • Install lsp-pascal, lsp-mode, company Emacs packages,

  • Configure it like this in your ~/.emacs:

    (require 'lsp-pascal)
    
    ;; choose LSP server binary
    (setq lsp-pascal-command "/home/michalis/sources/castle-engine/castle-engine/bin/pasls")
    
    ;; pass basic info to LSP server, all LSP Pascal servers above support these:
    (setq lsp-pascal-fpcdir "/home/michalis/cge/tools/contrib/fpc/src")
    (setq lsp-pascal-lazarusdir "/home/michalis/lazarus")
    (setq lsp-pascal-pp "/home/michalis/cge/tools/contrib/fpc/bin/fpc-cge")
    (setq lsp-pascal-fpctarget "linux")
    (setq lsp-pascal-fpctargetcpu "x86_64")

7.2. NeoVim

The LSP server can be used with NeoVim. See the client/nvim subdirectory of Philip Zander's repository.

8. Plans, TODOs

  • "Castle Game Engine" extension, in both VS Code and VS Codium extensions marketplaces. Features:

    • Depend on one of Pascal syntax highlighters mentioned above, so it automatically makes Pascal code highlighted.

    • Connect to CGE LSP server automatically.

    • Give simple settings option to set CGE location (with CGE sources, and CGE pasls, and CGE build tool used by tasks).

    • Remove unnecessary settings (current pasls-vscode that we recommend has a few settings that are actually ignored by our LSP server).

    • Define tasks to make Compile / Compile+Run / Run automatic when you’re inside CGE project (at least when workspace has CastleEngineManifest.xml, but preferably try to make it work out-of-the-box also when you visit any file, in case workspace contains multiple CGE projects). Maybe even propose to define F9 / Ctrl+F9 / Shift+F9 shortcuts to be consistent with CGE editor?

    • Define useful debugger experience (run GDB, setup breakpoint at fpc_raiseexception etc.) when the workspace contains CGE project.

  • Bundle CGE with VS Code.

    If you just install (unpack) CGE you should have a ready setup with CGE + VS Code. This is practically just VS Code with automatically enabled (or suggested?) "Castle Game Engine" extension mentioned above.

    Of course we will still make everything such that you don’t have to use this "bundled" VS Code and instead can use your existing VS Code installation, or really any other text editor / IDE, like Lazarus, Emacs, NeoVim etc.

  • The LSP server should require less (or even zero) configuration. All the parameters required now by LSP configuration are things that CGE editor knows, after all.

  • Can we have "Code Completion" (that happens in Lazarus when you Ctrl + Shift + C) that can automatically insert e.g. method declarations or complete property declarations?

  • There is DAP (Debug Adapter Protocol) with similar goals as LSP, but for debuggers. Maybe someone will wrap Lazarus debugger (GDB with Pascal specific interpretations) in DAP?


To improve this documentation just edit this page and create a pull request to cge-www repository.