Ace编辑器:锁定或只读代码段 [英] Ace Editor: Lock or Readonly Code Segment

查看:979
本文介绍了Ace编辑器:锁定或只读代码段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用Ace代码编辑器锁定或只读一段代码,但仍允许在会话期间编写或编辑其他代码行吗?

Using the Ace Code Editor can I lock or make readonly a segment of code but still allow other lines of code to be written or edited during a session?

推荐答案

这是解决方案的开始:

$(function() {
    var editor     = ace.edit("editor1")
        , session  = editor.getSession()
        , Range    = require("ace/range").Range
        , range    = new Range(1, 4, 1, 10)
        , markerId = session.addMarker(range, "readonly-highlight");

    session.setMode("ace/mode/javascript");
    editor.keyBinding.addKeyboardHandler({
        handleKeyboard : function(data, hash, keyString, keyCode, event) {
            if (hash === -1 || (keyCode <= 40 && keyCode >= 37)) return false;

            if (intersects(range)) {
                return {command:"null", passEvent:false};
            }
        }
    });

    before(editor, 'onPaste', preventReadonly);
    before(editor, 'onCut',   preventReadonly);

    range.start  = session.doc.createAnchor(range.start);
    range.end    = session.doc.createAnchor(range.end);
    range.end.$insertRight = true;

    function before(obj, method, wrapper) {
        var orig = obj[method];
        obj[method] = function() {
            var args = Array.prototype.slice.call(arguments);
            return wrapper.call(this, function(){
                return orig.apply(obj, args);
            }, args);
        }

        return obj[method];
    }

    function intersects(range) {
        return editor.getSelectionRange().intersects(range);
    }

    function preventReadonly(next, args) {
        if (intersects(range)) return;
        next();
    }
});

查看此小提琴的工作方式: http://jsfiddle.net/bzwheeler/btsxgena/

see it working in this fiddle: http://jsfiddle.net/bzwheeler/btsxgena/

主要作品是:


  1. 创建起始和结束ace锚点,这些锚点跟踪只读部分的位置,因为其周围的文档发生了变化。

  2. 创建一个范围以封装锚点

  3. 添加自定义按键处理程序,以检查当前即将到来的按键是否会影响只读范围,并取消该范围。

  4. 添加自定义粘贴/剪切处理程序以防止右键单击菜单和浏览器菜单的剪切/粘贴操作

  1. create start and end ace anchors which track the location of a 'readonly' portion as the document around it changes.
  2. create a range to encapsulate the anchors
  3. add a custom keyhandler to check if the current impending keypress will affect the readonly range and cancel it if so.
  4. add custom paste/cut handlers to protect against right-click menu and browser menu cut/paste actions

这篇关于Ace编辑器:锁定或只读代码段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆