因為我是用 Google Blogger 來寫部落格,但是身為一個寫程式碼的部落客,常常要貼程式碼
我改過很多版本,有時候使用 gist 分享程式碼,有時候使用 JSFiddle ,我是覺得都不錯,但是其實分享C# 的時候有點麻煩,就是要去 gist 貼 code ,或是 有時候我會使用 http://hilite.me/ 這網站來美化我的程式碼。
這時候我在想既然我最近都在用 Monaco Editor 這時候我在想有沒有可能用來使用當作分享程式碼的工具..
1. 首先引入 jQuery ,因為我有用到 :P
2. 接下來講解一下我是針對 <xmp> 這 Element 下手,因為在這 Element 內可以直接貼程式碼,所以就用它了,再來因為我都是針對 monaco-viwer 這 class
下手所以我在我的 html 中插入如下
<xmp class='monaco-viwer' lang='html' id='sample1' style='width:100%;height:299px'>
<html>
<div style='width:70%;height:100px;padding:5px;background-color:#262626;color:white'>
<span style='font-size:20px'>
測試一下<br>
測試一下<br>
測試一下<br>
</span>
</div>
<script>
alert('test');</script>
</html>
</xmp>
3. 接下來,你要引入 Monaco Editor 的 lib ,詳請可以參考這一篇
: Monaco Editor 一套很好用的編輯器套件快速入門上手,在來下一步就是 javascript 了。
JS Code :
function htmlencode(s) {
var div = document.createElement('div');
div.appendChild(document.createTextNode(s));
return div.innerHTML;
}
function RenderMonaco() {
$(".monaco-viwer").each(function (index) {
var source = $(this).html();
var styleSource = $(this).attr('style');
var lang = $(this).attr('lang');
var id = $(this).attr('id');
$(this).replaceWith("
");
var editor = monaco.editor.create(document.getElementById(id), {
language: lang,
theme: 'vs-dark',
tabCompletion: 'on',
cursorSmoothCaretAnimation: true,
formatOnPaste: true,
mouseWheelZoom: true,
autoClosingBrackets: "always",
autoClosingOvertype: "always",
autoClosingQuotes: "always",
automaticLayout: "always",
//readOnly: true
});
editor.setValue(source);
setTimeout(function () {
editor.getAction('editor.action.formatDocument').run()
setTimeout(function () {
editor.updateOptions({
readOnly: true
});
}, 200);
}, 1000);
});
}
RenderMonaco();
C# code display Demo:
using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
先寫到這有時間我再來慢慢優化
Source:
結論,概念很美好但是我覺得還可以更好,有時間我再來把他改得更好用一點。