日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

Asp.Net?Core?使用Monaco?Editor?實(shí)現(xiàn)代碼編輯器功能_實(shí)用技巧

作者:尋找無名的特質(zhì) ? 更新時(shí)間: 2022-03-23 編程語言

在項(xiàng)目中經(jīng)常有代碼在線編輯的需求,比如修改基于Xml的配置文件,編輯Json格式的測(cè)試數(shù)據(jù)等。我們可以使用微軟開源的在線代碼編輯器Monaco Editor實(shí)現(xiàn)這些功能。Monaco Editor是著名的VSCode的前身,項(xiàng)目地址:https://microsoft.github.io/monaco-editor/。本文介紹在Asp.Net Core項(xiàng)目中使用Monaco Editor實(shí)現(xiàn)代碼編輯器功能。

安裝

可以使用npm下載moaco-editor:

npm install monaco-editor@0.31.1

我們需要的文件在node_modules/monaco-editor/min/vs目錄中,將整個(gè)vs目錄拷貝到Asp.Net Core Web項(xiàng)目的wwwroot/lib目錄下:

在Program.cs中需要啟動(dòng)靜態(tài)文件:

app.UseStaticFiles();

在布局頁面中引入如下css和js:

<link data-name="vs/editor/editor.main"  href="~/lib/vs/editor/editor.main.css"   />
    <script  src="~/lib/vs/loader.js"></script>
    <script  src="~/lib/vs/editor/editor.main.nls.js"></script>
    <script src="~/lib/vs/editor/editor.main.js"></script>

基本的環(huán)境設(shè)置就完成了。

基本功能

現(xiàn)在可以在頁面中實(shí)現(xiàn)編輯器的基本功能,在頁面中增加一個(gè)div,作為編輯器容器:

<div id="container" style="width:800px;height:600px;border:1px solid grey"></div>

然后增加編輯器的js代碼:

<script>
    $(document).ready(function () {
        require.config({ paths: { 'vs': '/lib/vs' } });
        monaco.editor.create(document.getElementById('container'), {
            value: "function sayHello(){\n console.write('Hello World');\n}",
            language: 'javascript'
        });
    })
</script>

設(shè)置

編輯器有多種設(shè)置,比如是否顯示代碼行、顯示樣式等等,設(shè)置完成后,可以使用updateOptions修改設(shè)置,示例代碼如下:

        var editor = monaco.editor.create(document.getElementById('container'), {
            value: "function sayHello(){\n console.write('Hello World');\n}",
            language: 'javascript',
            lineNumbers: 'on',
            roundedSelection: false,
            scrollBeyondLastLine: false,
            readOnly: false,
            theme: 'vs-dark'
        });

代碼比較

monaco editor的一個(gè)強(qiáng)大的功能是文字比較功能,可以將兩段文字進(jìn)行比較:

<script>
    require.config({ paths: { 'vs': '/lib/vs' } });
    var originalModel = monaco.editor.createModel(
        '刪除行\(zhòng)n行一\n行二\n行三內(nèi)容\n更多內(nèi)容',
        'text/plain'
    );
    var modifiedModel = monaco.editor.createModel(
        '\n行一\n行二\n行三\n更多內(nèi)容\n增加行',
        'text/plain'
    );
    var diffEditor = monaco.editor.createDiffEditor(document.getElementById('container'), {
        // You can optionally disable the resizing
        enableSplitViewResizing: false
    });
    diffEditor.setModel({
        original: originalModel,
        modified: modifiedModel
    });
</script>

效果如下:

自定義語言

monaco editor 支持常見的幾乎所有編程語言,在編輯這些語言的代碼時(shí)可以高亮顯示關(guān)鍵字,同時(shí)也支持對(duì)自定義語言的擴(kuò)展。其功能非常強(qiáng)大,同時(shí)配置起來也比較復(fù)雜,這里只舉個(gè)簡(jiǎn)單的例子,說明如何使用。

這里使用的“語言”很簡(jiǎn)單,目的是記錄中國象棋的棋譜,關(guān)鍵字只有代表“車馬炮”等棋子的大寫漢語拼音,運(yùn)算符只有代表向前、向后和平行移動(dòng)的“++”、“--”和“==”,還有就是注釋。
使用自定義語言,首先要注冊(cè)這個(gè)語言的id:

        monaco.languages.register({ id: 'mylang' });

然后設(shè)置語言的Token Provider:

 monaco.languages.setMonarchTokensProvider('mylang', getlang());

這樣就可以在編輯器中使用這種自定義語言了,下面是完整的代碼:

@page
@model CustomLanguageModel
@{
    ViewData["Title"] = "自定義語言";
}
<h1>@ViewData["Title"]</h1>
<div id="container" style="height: 800px"></div>
<script>
    var require = { paths: { vs: '/lib/vs' } };
</script>
@section Scripts
{
<script>
    $(document).ready(function () {
        monaco.languages.register({ id: 'mylang' });
        monaco.languages.setMonarchTokensProvider('mylang', getlang());

        var sampleEditor=monaco.editor.create(document.getElementById('container'), {
            model:null
        }
        );
        setTimeout(function(){
             var model=monaco.editor.createModel('// 炮二平五 \nPAO 2 == 5 \n//馬八進(jìn)七 \nMA 8 ++ 7', 'mylang');
             sampleEditor.setModel(model);
        },1);
    });
    function getlang(){
        return {
            //車馬炮相士將帥兵卒
          keywords: [ 'JU', 'MA', 'PAO', 'XIANG', 'SHI', 'JIANG', 'SHUAI', 'BING', 'ZU' ],
          //++ 進(jìn) --退 ==平 
          operators: [ '++', '--', '=='  ],
          symbols:  /[=><!~?:&|+\-*\/\^%]+/,
          // The main tokenizer for our languages
          tokenizer: {
            root: [
              [/[A-Z][\w\$]*/, {cases: { '@@keywords': 'keyword' }}],
              { include: '@@whitespace' },
              [/@@symbols/, { cases: { '@@operators': 'operator'} } ],
              [/\d./, 'number'],
            ],
            comment: [
              [/[^\/*]+/, 'comment' ],
              [/\/\*/,    'comment', '@@push' ],
              ["\\*/",    'comment', '@@pop'  ],
              [/[\/*]/,   'comment' ]
            ],
            whitespace: [
              [/[ \t\r\n]+/, 'white'],
              [/\/\*/,       'comment', '@@comment' ],
              [/\/\/.*$/,    'comment'],
            ],
          },
        };
    }
</script>
}}

效果如下:

本文的示例項(xiàng)目已經(jīng)上傳到github: https://github.com/zhenl/monacoEditorDotNet

原文鏈接:https://www.cnblogs.com/zhenl/p/15758472.html

欄目分類
最近更新