Code Block 程式碼區塊支援的程式語言

論壇所使用的 程式碼區塊,採用的元件是 highlight.js ,以下將支援程式及顯示範例列出,供大家參考。

使用方式是在第一行的 ``` 後方,加上你想顯示的程式語法,如 python 的寫法就是 ```python ,依此類推。

支援程式語言 語法別名 (Aliases) Package
1C 1c
4D 4d highlightjs-4d
ABAP sap-abap, abap highlight-sap-abap
Abc Notation abc highlightjs-abc
ABNF abnf
Access logs accesslog
ActionScript actionscript, as
Ada ada
Aiken aiken, ak highlightjs-aiken
Alan ln highlightjs-alan
Alan IF alan, i highlightjs-alan
AngelScript angelscript, asc
Apache apache, apacheconf
Apex apex highlightjs-apex
AppleScript applescript, osascript
Arcade arcade
Arduino (C++ w/Arduino libs) arduino, ino
ARM assembler armasm, arm
AsciiDoc asciidoc, adoc
AspectJ aspectj
AutoHotkey autohotkey
AutoIt autoit
AVR assembler avrasm
Awk awk, mawk, nawk, gawk
Ballerina ballerina, bal highlightjs-ballerina
Bash bash, sh, zsh
BASIC basic
BBCode bbcode highlightjs-bbcode
Bicep bicep highlightjs-bicep
Blade (Laravel) blade highlightjs-blade
BNF bnf
BQN bqn highlightjs-bqn
Brainfuck brainfuck, bf
C c, h
C# csharp, cs
C++ cpp, hpp, cc, hh, c++, h++, cxx, hxx
C/AL cal
C3 c3 highlightjs-c3
Cache Object Script cos, cls
Candid candid, did highlightjs-motoko
Cap’n Proto capnproto, capnp
Chaos chaos, kaos highlightjs-chaos
Chapel chapel, chpl highlightjs-chapel
Cisco CLI cisco highlightjs-cisco-cli
Clojure clojure, clj
CMake cmake, cmake.in
COBOL cobol, standard-cobol highlightjs-cobol
CODEOWNERS codeowners highlightjs-codeowners
CoffeeScript coffeescript, coffee, cson, iced
Coq coq
CpcdosC+ cpc highlightjs-cpcdos
Crmsh crmsh, crm, pcmk
Crystal crystal, cr
CSP csp
CSS css
cURL curl highlightjs-curl
Cypher (Neo4j) cypher highlightjs-cypher
D d
Dafny dafny highlightjs-dafny
Dart dart
Delphi dpr, dfm, pas, pascal
Diff diff, patch
Django django, jinja
DNS Zone file dns, zone, bind
Dockerfile dockerfile, docker
DOS dos, bat, cmd
dsconfig dsconfig
DTS (Device Tree) dts
Dust dust, dst
Dylan dylan highlightjs-dylan
EBNF ebnf
Elixir elixir
Elm elm
Erlang erlang, erl
Excel excel, xls, xlsx
Extempore extempore, xtlang, xtm highlightjs-xtlang
F# fsharp, fs, fsx, fsi, fsscript
FIX fix
Flix flix highlightjs-flix
Fortran fortran, f90, f95
FunC func highlightjs-func
G-Code gcode, nc
Gams gams, gms
GAUSS gauss, gss
GDScript godot, gdscript highlightjs-gdscript
Gherkin gherkin
Gleam gleam gleam-highlight.js
Glimmer and EmberJS hbs, glimmer, html.hbs, html.handlebars, htmlbars highlightjs-glimmer
GN for Ninja gn, gni highlightjs-GN
Go go, golang
Golo golo, gololang
Gradle gradle
Grammatical Framework gf highlightjs-gf
GraphQL graphql, gql
Groovy groovy
GSQL gsql highlightjs-gsql
Haml haml
Handlebars handlebars, hbs, html.hbs, html.handlebars
Haskell haskell, hs
Haxe haxe, hx
High-level shader language hlsl highlightjs-hlsl
HTML, XML xml, html, xhtml, rss, atom, xjb, xsd, xsl, plist, svg
HTTP http, https
Hy hy, hylang
Inform7 inform7, i7
Ini, TOML ini, toml
Iptables iptables highlightjs-iptables
IRPF90 irpf90
Java java, jsp
JavaScript javascript, js, jsx
Jolie jolie, iol, ol highlightjs-jolie
JSON json, jsonc, json5
JSONata jsonata highlightjs-jsonata
Julia julia, jl
Julia REPL julia-repl
Kotlin kotlin, kt
L4 l4, legal highlightjs-l4
Lang highlightjs-lang
Lasso lasso, ls, lassoscript
LaTeX tex
LDIF ldif
Leaf leaf
Lean lean highlightjs-lean
Less less
Liquid liquid highlightjs-liquid
Lisp lisp
LiveCode Server livecodeserver
LiveScript livescript, ls
LookML lookml highlightjs-lookml
Lua lua, pluto
Luau luau highlightjs-luau
Macaulay2 macaulay2 highlightjs-macaulay2
Magik magik highlightjs-magik
Makefile makefile, mk, mak, make
Markdown markdown, md, mkdown, mkd
Mathematica mathematica, mma, wl
Matlab matlab
Maxima maxima
Maya Embedded Language mel
Mercury mercury
MetaPost metapost highlightjs-metapost
Mint mint highlightjs-mint
MIPS Assembler mips, mipsasm
mIRC Scripting Language mirc, mrc highlightjs-mirc
Mirth mirth highlightjs-mirth
Mizar mizar
MKB mkb highlightjs-mkb
MLIR mlir highlightjs-mlir
Mojolicious mojolicious
Monkey monkey
Moonscript moonscript, moon
Motoko motoko, mo highlightjs-motoko
N1QL n1ql
Never never highlightjs-never
Nginx nginx, nginxconf
Nim nim, nimrod
Nix nix
NSIS nsis
Oak oak highlightjs-oak
Object Constraint Language ocl highlightjs-ocl
Objective C objectivec, mm, objc, obj-c, obj-c++, objective-c++
OCaml ocaml, ml
Odin odin highlightjs-odinlang
OpenGL Shading Language glsl
OpenSCAD openscad, scad
Oracle Rules Language ruleslanguage
Oxygene oxygene
Papyrus papyrus, psc highlightjs-papyrus
Parser3 parser3
Perl perl, pl, pm
PF pf, pf.conf
Phix phix highlightjs-phix
PHP php
Pine Script pine, pinescript highlightjs-pine
Plaintext plaintext, txt, text
Pony pony
PostgreSQL & PL/pgSQL pgsql, postgres, postgresql
PowerOn poweron, po highlightjs-poweron
PowerShell powershell, ps, ps1
Prisma prisma highlightjs-prisma
Processing processing
Prolog prolog
Properties properties
Protocol Buffers proto, protobuf
Puppet puppet, pp
Python python, py, gyp
Python profiler results profile
Python REPL python-repl, pycon
Q k, kdb
Q# qsharp highlightjs-qsharp
QML qml
R r
Raku raku, perl6, p6, pm6, rakumod highlightjs-raku
RakuDoc pod6, rakudoc highlightjs-raku
RakuQuoting rakuquoting highlightjs-raku
RakuRegexe rakuregexe highlightjs-raku
Razor CSHTML cshtml, razor, razor-cshtml highlightjs-cshtml-razor
ReasonML reasonml, re
Rebol & Red redbol, rebol, red, red-system highlightjs-redbol
RenderMan RIB rib
RenderMan RSL rsl
ReScript rescript, res highlightjs-rescript
RISC-V Assembly riscv, riscvasm highlightjs-riscvasm
RiScript risc, riscript highlightjs-riscript
Roboconf graph, instances
Robot Framework robot, rf highlightjs-robot
RPM spec files rpm-specfile, rpm, spec, rpm-spec, specfile highlightjs-rpm-specfile
Ruby ruby, rb, gemspec, podspec, thor, irb
Rust rust, rs
RVT Script rvt, rvt-script highlightjs-rvt-script
SAS SAS, sas
Scala scala
Scheme scheme
Scilab scilab, sci
SCSS scss
SFZ sfz highlightjs-sfz
Shape Expressions shexc highlightjs-shexc
Shell shell, console
Smali smali
Smalltalk smalltalk, st
SML sml, ml
Solidity solidity, sol highlightjs-solidity
Splunk SPL spl highlightjs-spl
SQL sql
Stan stan, stanfuncs
Stata stata
STEP Part 21 p21, step, stp
Structured Text iecst, scl, stl, structured-text highlightjs-structured-text
Stylus stylus, styl
SubUnit subunit
Supercollider supercollider, sc highlightjs-supercollider
Svelte svelte highlight.svelte
Swift swift
Tcl tcl, tk
Terraform (HCL) terraform, tf, hcl highlightjs-terraform
Test Anything Protocol tap
Thrift thrift
Toit toit toit-highlight
TP tp
Transact-SQL tsql highlightjs-tsql
TTCN-3 ttcn, ttcnpp, ttcn3 highlightjs-ttcn3
Twig twig, craftcms
TypeScript typescript, ts, tsx, mts, cts
Unicorn Rails log unicorn-rails-log highlightjs-unicorn-rails-log
Unison unison, u highlightjs-unison
Vala vala
VB.Net vbnet, vb
VBA vba highlightjs-vba
VBScript vbscript, vbs
Verilog verilog, v
VHDL vhdl
Vim Script vim
VoltScript voltscript, vss, lotusscript, lss highlightjs-voltscript
WGSL wgsl highlightjs-wgsl
X# xsharp, xs, prg highlightjs-xsharp
X++ axapta, x++
x86 Assembly x86asm
x86 Assembly (AT&T) x86asmatt highlightjs-x86asmatt
XL xl, tao
XQuery xquery, xpath, xq, xqm
YAML yml, yaml
ZenScript zenscript, zs highlightjs-zenscript
Zephir zephir, zep
Zig zig highlightjs-zig

以下是常用程式語言範例:


apache

# rewrite`s rules for wordpress pretty url
LoadModule rewrite_module  modules/mod_rewrite.so
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [NC,L]

ExpiresActive On
ExpiresByType application/x-javascript  "access plus 1 days"

Order Deny,Allow
Allow from All

<Location /maps/>
  RewriteMap map txt:map.txt
  RewriteMap lower int:tolower
  RewriteCond %{REQUEST_URI} ^/([^/.]+)\.html$ [NC]
  RewriteCond ${map:${lower:%1}|NOT_FOUND} !NOT_FOUND
  RewriteRule .? /index.php?q=${map:${lower:%1}} [NC,L]
</Location>

bash

#!/bin/bash

###### CONFIG
ACCEPTED_HOSTS="/root/.hag_accepted.conf"
BE_VERBOSE=false

if [ "$UID" -ne 0 ]
then
 echo "Superuser rights required"
 exit 2
fi

genApacheConf(){
 echo -e "# Host ${HOME_DIR}$1/$2 :"
}

echo '"quoted"' | tr -d \" > text.txt

cpp

#include <iostream>

int main(int argc, char *argv[]) {

  /* An annoying "Hello World" example */
  for (auto i = 0; i < 0xFFFF; i++)
    cout << "Hello, World!" << endl;

  char c = '\n';
  unordered_map <string, vector<string> > m;
  m["key"] = "\\\\"; // this is an error

  return -2e3 + 12l;
}

css

@font-face {
  font-family: Chunkfive; src: url('Chunkfive.otf');
}

body, .usertext {
  color: #F0F0F0; background: #600;
  font-family: Chunkfive, sans;
  --heading-1: 30px/32px Helvetica, sans-serif;
}

@import url(print.css);
@media print {
  a[href^=http]::after {
    content: attr(href)
  }
}

coffeescript

grade = (student, period=(if b? then 7 else 6)) ->
  if student.excellentWork
    "A+"
  else if student.okayStuff
    if student.triedHard then "B" else "B-"
  else
    "C"

class Animal extends Being
  constructor: (@name) ->

  move: (meters) ->
    alert @name + " moved #{meters}m."

diff

Index: languages/ini.js
===================================================================
--- languages/ini.js    (revision 199)
+++ languages/ini.js    (revision 200)
@@ -1,8 +1,7 @@
 hljs.LANGUAGES.ini =
 {
   case_insensitive: true,
-  defaultMode:
-  {
+  defaultMode: {
     contains: ['comment', 'title', 'setting'],
     illegal: '[^\\s]'
   },

*** /path/to/original timestamp
--- /path/to/new      timestamp
***************
*** 1,3 ****
--- 1,9 ----
+ This is an important
+ notice! It should
+ therefore be located at
+ the beginning of this
+ document!

! compress the size of the
! changes.

  It is important to spell

xml

<!DOCTYPE html>
<title>Title</title>

<style>body {width: 500px;}</style>

<script type="application/javascript">
  function $init() {return true;}
</script>

<body>
  <p checked class="title" id='title'>Title</p>
  <!-- here goes the rest of the page -->
</body>

http

<!DOCTYPE html>
<html>
<title>HTML Tutorial</title>
<body>

<h1>This is a heading</h1>
<p>This is a paragraph.</p>

</body>
</html>

ini

; boilerplate
[package]
name = "some_name"
authors = ["Author"]
description = "This is \
a description"

[[lib]]
name = ${NAME}
default = True
auto = no
counter = 1_000

json

[
  {
    "title": "apples",
    "count": [12000, 20000],
    "description": {"text": "...", "sensitive": false}
  },
  {
    "title": "oranges",
    "count": [17500, null],
    "description": {"text": "...", "sensitive": false}
  }
]

java

/**
 * @author John Smith <john.smith@example.com>
*/
package l2f.gameserver.model;

public abstract strictfp class L2Char extends L2Object {
  public static final Short ERROR = 0x0001;

  public void moveTo(int x, int y, int z) {
    _ai = null;
    log("Should not be called");
    if (1 > 5) { // wtf!?
      return;
    }
  }
}

javascript

function $initHighlight(block, cls) {
  try {
    if (cls.search(/\bno\-highlight\b/) != -1)
      return process(block, true, 0x0F) +
             ` class="${cls}"`;
  } catch (e) {
    /* handle exception */
  }
  for (var i = 0 / 2; i < classes.length; i++) {
    if (checkCondition(classes[i]) === undefined)
      console.log('undefined');
  }

  return (
    <div>
      <web-component>{block}</web-component>
    </div>
  )
}

export  $initHighlight;

makefile

# Makefile

BUILDDIR      = _build
EXTRAS       ?= $(BUILDDIR)/extras

.PHONY: main clean

main:
	@echo "Building main facility..."
	build_main $(BUILDDIR)

clean:
	rm -rf $(BUILDDIR)/*

markdown

# hello world

you can write text [with links](http://example.com) inline or [link references][1].

* one _thing_ has *em*phasis
* two __things__ are **bold**

[1]: http://example.com

---

hello world
===========

<this_is inline="xml"></this_is>

> markdown is so cool

    so are code segments

1. one thing (yeah!)
2. two thing `i can write code`, and `more` wipee!

nginx

user  www www;
worker_processes  2;
pid /var/run/nginx.pid;
error_log  /var/log/nginx.error_log  debug | info | notice | warn | error | crit;

events {
    connections   2000;
    use kqueue | rtsig | epoll | /dev/poll | select | poll;
}

http {
    log_format main      '$remote_addr - $remote_user [$time_local] '
                         '"$request" $status $bytes_sent '
                         '"$http_referer" "$http_user_agent" '
                         '"$gzip_ratio"';

    send_timeout 3m;
    client_header_buffer_size 1k;

    gzip on;
    gzip_min_length 1100;

    #lingering_time 30;

    server {
        server_name   one.example.com  www.one.example.com;
        access_log   /var/log/nginx.access_log  main;

        rewrite (.*) /index.php?page=$1 break;

        location / {
            proxy_pass         http://127.0.0.1/;
            proxy_redirect     off;
            proxy_set_header   Host             $host;
            proxy_set_header   X-Real-IP        $remote_addr;
            charset            koi8-r;
        }

        location /api/ {
            fastcgi_pass 127.0.0.1:9000;
        }

        location ~* \.(jpg|jpeg|gif)$ {
            root         /spool/www;
        }
    }
}

objectivec

#import <UIKit/UIKit.h>
#import "Dependency.h"

@protocol WorldDataSource
@optional
- (NSString*)worldName;
@required
- (BOOL)allowsToLive;
@end

@property (nonatomic, readonly) NSString *title;
- (IBAction) show;
@end

ruby

# The Greeter class
class Greeter
  def initialize(name)
    @name = name.capitalize
  end

  def salute
    puts "Hello #{@name}!"
  end
end

g = Greeter.new("world")
g.salute

perl

# loads object
sub load
{
  my $flds = $c->db_load($id,@_) || do {
    Carp::carp "Can`t load (class: $c, id: $id): '$!'"; return undef
  };
  my $o = $c->_perl_new();
  $id12 = $id / 24 / 3600;
  $o->{'ID'} = $id12 + 123;
  #$o->{'SHCUT'} = $flds->{'SHCUT'};
  my $p = $o->props;
  my $vt;
  $string =~ m/^sought_text$/;
  $items = split //, 'abc';
  $string //= "bar";
  for my $key (keys %$p)
  {
    if(${$vt.'::property'}) {
      $o->{$key . '_real'} = $flds->{$key};
      tie $o->{$key}, 'CMSBuilder::Property', $o, $key;
    }
  }
  $o->save if delete $o->{'_save_after_load'};

  # GH-117
  my $g = glob("/usr/bin/*");

  return $o;
}

__DATA__
@@ layouts/default.html.ep
<!DOCTYPE html>
<html>
  <head><title><%= title %></title></head>
  <body><%= content %></body>
</html>
__END__

=head1 NAME
POD till the end of file

php

require_once 'Zend/Uri/Http.php';

namespace Location\Web;

interface Factory
{
    static function _factory();
}

abstract class URI extends BaseURI implements Factory
{
    abstract function test();

    public static $st1 = 1;
    const ME = "Yo";
    var $list = NULL;
    private $var;

    /**
     * Returns a URI
     *
     * @return URI
     */
    static public function _factory($stats = array(), $uri = 'http')
    {
        echo __METHOD__;
        $uri = explode(':', $uri, 0b10);
        $schemeSpecific = isset($uri[1]) ? $uri[1] : '';
        $desc = 'Multi
line description';

        // Security check
        if (!ctype_alnum($scheme)) {
            throw new Zend_Uri_Exception('Illegal scheme');
        }

        $this->var = 0 - self::$st;
        $this->list = list(Array("1"=> 2, 2=>self::ME, 3 => \Location\Web\URI::class));

        return [
            'uri'   => $uri,
            'value' => null,
        ];
    }
}

match ($key) {
    1 => 'Integer 1',
    '1' => 'String 1',
    true => 'Bool true',
    [] => 'Empty array',
    [1] => 'Array [1]',
};

enum Foo: string {
    case Test = 'test';
}

match ($key) {
    1 => 'Integer 1',
    '1' => 'String 1',
    true => 'Bool true',
    [] => 'Empty array',
    [1] => 'Array [1]',
};

echo URI::ME . URI::$st1;

__halt_compiler () ; datahere
datahere
datahere */
datahere

python

@requires_authorization(roles=["ADMIN"])
def somefunc(param1='', param2=0):
    r'''A docstring'''
    if param1 > param2: # interesting
        print 'Gre\'ater'
    return (param2 - param1 + 1 + 0b10l) or None

class SomeClass:
    pass

>>> message = '''interpreter
... prompt'''

sql

CREATE TABLE "topic" (
    "id" integer NOT NULL PRIMARY KEY,
    "forum_id" integer NOT NULL,
    "subject" varchar(255) NOT NULL
);
ALTER TABLE "topic"
ADD CONSTRAINT forum_id FOREIGN KEY ("forum_id")
REFERENCES "forum" ("id");

-- Initials
insert into "topic" ("forum_id", "subject")
values (2, 'D''artagnian');

handlebars

<div class="entry">
  {{!-- only show if author exists --}}
  {{#if author}}
    <h1>{{firstName}} {{lastName}}</h1>
  {{/if}}
</div>

心得:有些程式語言,看起來是用預設的(意思是:在論壇中的顯示,和 highlight.js 官方的不同),我再找時間看看是不是漏了什麼。

參考資料

highlight.js demo