Hexo codeblock 插入程式碼區塊與各種程式語言預覽

目錄
  1. 1. Hexo 插入程式碼區塊 codeblock 的方法
  2. 2. 各種程式語言預覽
  3. 3. Bash
  4. 4. C++
  5. 5. C sharp
  6. 6. CSS
  7. 7. Diff
  8. 8. HTTP
  9. 9. Ini, TOML
  10. 10. Java
  11. 11. JavaScript
  12. 12. JSON
  13. 13. Makefile
  14. 14. Markdown
  15. 15. Objective-C
  16. 16. PHP
  17. 17. Properties
  18. 18. Python
  19. 19. Shell Session
  20. 20. HTML, XML

本篇紀錄在 Hexo 插入程式碼區塊 codeblock 的方法,以及 Hexo 使用的 highlight.js 支援各種程式語言的預覽,

Hexo 插入程式碼區塊 codeblock 的方法

使用方法為兩種
方法一︰
```
程式碼
```

方法二︰

1
2
3
{% codeblock lang:objc %}
程式碼
{% endcodeblock %}

詳細說明如下︰

1
2
3
{% codeblock [title] [lang:language] [url] [link text] %}
code snippet
{% endcodeblock %}

Code Block 在 markdown 中使用可以參考這裡

各種程式語言預覽

普通的程式碼區塊 codeblock

1
alert('Hello World!');

指定語言 objc

1
[rectangle setX: 10 y: 10 width: 20 height: 20];

加上說明

Array.map
1
array.map(callback[, thisArg])

加上說明和網址

_.compactUnderscore.js
1
2
_.compact([0, 1, false, 2, '', 3]);
=> [1, 2, 3]

Hexo 支援程式語言可以看 node_modules/highlight.js/lib/languages/index.js,效果如下︰

Bash

lang:bash

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/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 :"
}

C++

lang:cpp (不行用lang:c++)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#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;
}

C sharp

lang:cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using System.IO.Compression;

#pragma warning disable 414, 3021

namespace MyApplication
{
[Obsolete("...")]
class Program : IInterface
{
public static List<int> JustDoIt(int count)
{
Console.WriteLine($"Hello {Name}!");
return new List<int>(new int[] { 1, 2, 3 })
}
}
}

CSS

lang:css

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@font-face {
font-family: Chunkfive; src: url('Chunkfive.otf');
}

body, .usertext {
color: #F0F0F0; background: #600;
font-family: Chunkfive, sans;
}

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

Diff

lang:diff (好像還差了一點 ++– 顏色沒有顯示出來)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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

HTTP

lang:http

1
2
3
4
5
6
7
8
9
10
11
12
13
POST /task?id=1 HTTP/1.1
Host: example.org
Content-Type: application/json; charset=utf-8
Content-Length: 137

{
"status": "ok",
"extended": true,
"results": [
{"value": 0, "type": "int64"},
{"value": 1.0e+3, "type": "decimal"}
]
}

Ini, TOML

lang:ini

1
2
3
4
5
6
7
8
9
10
11
12
; boilerplate
[package]
name = "some_name"
authors = ["Author"]
description = "This is \
a description"

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

Java

lang:java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* @author John Smith <john.smith@example.com>
*/
package l2f.gameserver.model;

public abstract 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

lang:javascript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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');
}
}

export $initHighlight;

JSON

lang:json

1
2
3
4
5
6
7
8
9
10
11
12
[
{
"title": "apples",
"count": [12000, 20000],
"description": {"text": "...", "sensitive": false}
},
{
"title": "oranges",
"count": [17500, null],
"description": {"text": "...", "sensitive": false}
}
]

Makefile

lang:makefile

1
2
3
4
5
6
7
8
9
10
11
12
13
# Makefile

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

.PHONY: main clean

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

clean:
rm -rf $(BUILDDIR)/*

Markdown

lang:markdown

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 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!

Objective-C

lang:objectivec

1
2
3
4
5
6
7
8
9
10
11
12
13
#import <UIKit/UIKit.h>
#import "Dependency.h"

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

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

PHP

lang:php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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,
];
}
}

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

__halt_compiler () ; datahere
datahere
datahere */
datahere

Properties

lang:properties (沒效)

1
2
3
4
5
6
7
8
9
10
11
# .properties
! Exclamation mark = comments, too

key1 = value1
key2 : value2
key3 value3
key\ spaces multiline\
value4
empty_key
! Key can contain escaped chars
\:\= = value5

Python

lang:python

1
2
3
4
5
6
7
8
9
10
11
12
@requires_authorization
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'''

Shell Session

lang:shell

1
2
3
4
5
6
7
8
9
10
11
$ echo $EDITOR
vim
$ git checkout master
Switched to branch 'master'
Your branch is up-to-date with 'origin/master'.
$ git push
Everything up-to-date
$ echo 'All
> done!'
All
done!

HTML, XML

lang:xml

1
2
3
4
5
6
7
8
9
10
11
12
13
<!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>

參考
https://hexo.io/zh-tw/docs/tag-plugins.html#Code-Block
highlight.js demo

相關文章
Hexo 使用 Google Analytics 進行網站流量分析
Hexo 本機測試時如何關閉 Google Analytics
升級更新 Hexo upgrade
Hexo 熱門主題列表
Ubuntu 安裝 Hexo
Mac OS 安裝 Hexo