【ace.js】网页版代码智能提示,带高亮编辑器

时间:2022-07-22
本文章向大家介绍【ace.js】网页版代码智能提示,带高亮编辑器,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

背景

纯粹为了在自己博客实现一个代码编辑器,方便在线测试各种代码。

ace介绍

ACE 是一个开源的、独立的、基于浏览器的代码编辑器,可以嵌入到任何web页面或JavaScript应用程序中。到目前版本,它支持了超过120多种的语法高亮,超过20多种主题等,在编辑器方面也支持多种操作,包括提示等,算是一个基于web端的代码编辑器了。,并能够处理代码多达400万行的大型文档。ACE开发团队称,ACE在性能和功能上可以媲美本地代码编辑器(如Sublime Text、TextMate和Vim等)。详细API和demo可查阅官网。

步骤

1.编写代码编辑器样式

2.引入ace.js

<script type="text/javascript" src="./src-noconflict/ace.js"></script>
<script type="text/javascript" src="./src-noconflict/ext-language_tools.js"></script>

3.具体示例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>test</title>
    <style type="text/css" media="screen">
        .ace_editor {
            /*position: relative !important;*/
            border: 1px solid lightgray;
            border-radius:5px;
            margin: auto;
            height: 800px;
            width: 80%;
        }
    </style>
</head>
<body>
<div id="editor"></div>
<script src="ace-builds-master/src/ace.js"></script>
<script src="ace-builds-master/src-noconflict/ext-language_tools.js"></script>
<script>
    //引入语言工具
    ace.require("ace/ext/language_tools");
    const editor = ace.edit("editor");
    //选择主题
    editor.setTheme("ace/theme/twilight");
    //选择语言
    editor.session.setMode("ace/mode/javascript");
    //各项设置
    editor.setOptions({
        enableBasicAutoCompletion : true,
        enableSnippets : true,
        enableLiveAutocompletion : true
    });

    //预设值
    if (typeof ace == "undefined" && typeof require == "undefined") {
        document.body.innerHTML = "<p style='padding: 20px 50px;'>couldn't find ace.js file, <br>"
            + "to build it run <code>node Makefile.dryice.js full<code>"
    } else if (typeof ace == "undefined" && typeof require != "undefined") {
        require(["ace/ace"], setValue)
    } else {
        require = ace.require;
        setValue()
    }

    function setValue() {
        require("ace/lib/net").get(document.baseURI, function(t){
            var el = document.getElementById("editor");
            el.env.editor.setValue(t, 1);
        })
    }
</script>
</body>
</html>

4. 效果展示