Hexo怎么优雅地插入图片

发现懒得更新博客的一个很大原因是,写一个图文博文实在是有点麻烦。这两天研究了下如何优雅的在写hexo博客的时候优雅地插入图片。

环境

我的环境:win10 gvim7.4 hexo3.1.1, 此方案对环境无要求。

gvim 编写markdown。

开始

最终结果

  • 在执行 hexo new [layout] <title> 后,自动在一个设定的目录创建以 <title> 命名的子目录,然后把文章用到的截图全部放到这个文件夹。通过工具自动同步到图床。图床的存储路径必须满足统一前缀。例如,我的截图是 youpath/title/name.png ,上传到图床后,网络路径必须是 http://yoursite/title/name.png 类型。
  • 在gvim写作的时候,每次保存会自动转换:
    1. ![pic4](4.png) 替换为 ![pic4](http://yoursite/title/4.png)
    2. ![pic4][4] 自动在文章末尾增加 ![4](http://yoursite/title/4.png)

vim配置

vim配置很简单,在你的配置文件vimrc里面添加下面的内容即可(网址请改为自己的图床,这里我用的是七牛图床)。

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
autocmd! BufWritePost *.md,*.mkd,*.markdown :silent!call Insertimg()<CR>
function! Insertimg()
" 转换![name](num)
:%s#\(!\[[^\]]*\](\)\(\w\{,10}\))#\=submatch(1).'http://7xsj4f.com2.z0.glb.clouddn.com/'.expand("%:r").'/'.submatch(2).'.png)'#

" 转换 ![name][num]
let lnum = 1
let lst = []
while lnum <= line("$")
let line = getline(lnum)
call substitute(line, '\(!\[[^\]]*\]\[\)\(\d\{,2}\)\]', '\=add(lst, submatch(2))', 'g')
let lnum += 1
endwhile
let unduplst=sort(filter(copy(lst),'index(lst, v:val, v:key+1)==-1'))
let line = getline(line("$"))
let flag = matchstr(line,'\[\d\+\]: http:')
:ks
while flag != ''
exe "normal G"
exe "normal dd"
let line = getline(line("$"))
let flag = matchstr(line,'\[\d\+\]: http:')
endwhile
exe "normal 's"

for name in unduplst
if len(name)>0
call append(line("$"), "[".name."]: http://7xsj4f.com2.z0.glb.clouddn.com/".expand("%:r")."/".name.".png")
endif
endfor
:w
endfunction

hexo 配置

这个配置起来有点小麻烦,要改hexo的一个模块代码。文件路径在yourpath\hexo\node_modules\hexo\lib\hexo\post.js 更改内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@@ -63,7 +63,7 @@ Post.prototype.create = function(data, replace, callback) {
// Write content to file
fs.writeFile(path, content),
// Create asset folder
- createAssetFolder(path, config.post_asset_folder)
+ createAssetFolder(pathFn.resolve(config.post_asset_folder,pathFn.basename(path)), config.post_asset_folder)
]).then(function() {
ctx.emit('new', result);
}).thenReturn(result);
@@ -213,7 +213,7 @@ Post.prototype.publish = function(data, replace, callback) {
// Remove the original draft file
return fs.unlink(src);
}).then(function() {
- if (!config.post_asset_folder) return;
+ if (config.post_asset_folder !== true) return;

然后在 yourpath\hexo\_config.yml 中配置 post_asset_folder 路径,路径可随意:

1
post_asset_folder: .\static\images\

当每次用 hexo new [layout] <title> 命令的时候就会自动在配置的路径生成一个跟 title 同名的文件夹。并且此文件夹内的内容不会上传到github。

自动同步到图床

正在加载中……