How do I include sourcecode in my post?

Well, you can just paste it in like any text, but that usually results in losing all your indenting. Instead you can get discourse to format it nicely for you. Here are the basics using markdown format:


Code Inline

If you want to format some code in the middle of a line of normal text, wrap the code in single backticks (note backticks are not single quotes. They look like this ` while single quotes look like this '. Subtle difference I know. On my keyboard backticks are to the left of the 1 key).

So typing in the following:

Some text with `Listbox1.Add(‘Hello World’);` in it

will get formatted as

Some text with Listbox1.Add('Hello World'); in it


Whole Line of Code

If your code will take up the whole line, then just start the line with 4 spaces. Everything after that until the linebreak will be treated as code.

TMyObject = class(TObject)

Code Block

If you want to have multiple lines of code, and don’t feel like putting 4 spaces at the start of every line, then put 3 backticks before and after the whole block.

So this:

```
procedure TStateMachine<TState, TTrigger>.TransitionToState
(const AState: TState; AFirstTime: boolean);
begin
if not Active then
raise EStateMachineException.Create(‘StateMachine not active’);
```

gets formatted as this:

procedure TStateMachine<TState, TTrigger>.TransitionToState
  (const AState: TState; AFirstTime: boolean);
begin
  if not Active then
    raise EStateMachineException.Create('StateMachine not active');

Discourse will try and figure out what language the sourcecode is, but if it gets it wrong, you can specify the language after the opening 3 backticks, like this:

```delphi

or

```javascript

The list of supported languages for syntax highlighting is

delphi, pascal, bash, cs, cpp, css, coffeescript, diff, xml, http, ini, json, java, javascript, makefile, markdown, nginx, objectivec, ruby, perl, php, python, sql, csharp, vbscipt

2 Likes