2015-08-23 3 views
3

Я использую codemirror, чтобы пользователь мог ввести anycode, например, css/html/js.Как включить подсказку кода с помощью codemirror?

мне нужно включить, если тип пользователя что-то, как и в режиме CSS

div { 
padding- 
} 

Он должен намекнуть пользователю выбрать доступные опции из списка, как

div { 
padding-top 
padding-left 
padding-right 
padding-bottom 
} 

Что-то вроде возвышенной редактор, используя CodeMirror. Пожалуйста, смотрите прикрепленное изображение для демонстрации возвышенного авто намекая

enter image description here

Вот мой код:

<script src="codemirror-5.4/mode/javascript/javascript.js"></script> 
    <script src="codemirror-5.4/mode/css/css.js"></script> 
    <script src="codemirror-5.4/mode/htmlmixed/htmlmixed.js"></script> 
    <script src="codemirror-5.4/addon/display/fullscreen.js"></script> 
    <script src="codemirror-5.4/keymap/sublime.js"></script> 
    <script src="codemirror-5.4/addon/hint/show-hint.js"></script> 
    <script src="codemirror-5.4/addon/hint/css-hint.js"></script> 
    <script src="codemirror-5.4/addon/hint/javascript.js"></script> 

<h3>Editor</h3> 
    <div class="control-group"> 
    <label class="control-label" for="textarea2">HTML</label> 
    <div class="controls"> 
     <textarea class="code" name="code" id="codert" cols="40" rows="5" placeholder="Enter code here ..." style="width: 810px; height: 200px"> 
     </textarea> 
     </div> 
    </div> 

    <div class="control-group"> 
     <label class="control-label" for="textarea3">CSS</label> 
     <div class="controls"> 
      <textarea id="code" class="code" name="codeCSS" cols="40" rows="5" placeholder="Enter code here ..." style="width: 810px; height: 200px"> 
     </textarea> 
     </div> 
    </div> 
    <div class="control-group"> 
     <label class="control-label" for="textarea3">javascript</label> 
     <div class="controls"> 
      <textarea id="codeJS" class="code" name="codeJS" cols="40" rows="5" placeholder="Enter code here ..." style="width: 0px; height: 0px"> 
      </textarea> 
     </div> 
    </div> 

JavaScript код CodeMirror

<script> 

    function loadCSS() { 
    var $head = $("#preview").contents().find("head");     
    $head.html("<style>" + editor.getValue() + "</style>"); 
}; 

function loadJS() { 
    var scriptTag = "<script>"+editorJS.getValue()+"<"; 
    scriptTag += "/script>"; 

    var previewFrame2 = document.getElementById('preview'); 
    var preview2 = previewFrame2.contentDocument || previewFrame2.contentWindow.document; 
    preview2.open(); 
    preview2.write(editor2.getValue()+scriptTag); 
    preview2.close(); 

    loadCSS(); 
}; 

var delay; 
// Initialize CodeMirror editor with a nice html5 canvas demo. 

// css editor 
var editor = CodeMirror.fromTextArea(document.getElementById('code'), { 
    lineNumbers: true, 
    styleActiveLine: true, 
    matchBrackets: true, 
    mode: "text/x-scss", 
    keyMap: "sublime", 
    theme: 'monokai', 
    autoCloseTags: true, 
    lineWrapping: true, 
    extraKeys: {"Ctrl-Space": "autocomplete"} 
}); 
editor.on("change", function() { 
    clearTimeout(delay); 

    delay = setTimeout(updatePreview, 0); 
}); 

function updatePreview() { 
    loadCSS(); 
} 
setTimeout(updatePreview, 0); 


var delay2; 
// Initialize CodeMirror editor with a nice html5 canvas demo. 
var editor2 = CodeMirror.fromTextArea(document.getElementById('codert'), { 
    lineNumbers: true, 
    styleActiveLine: true, 
    matchBrackets: true, 
    mode: "text/html", 
    keyMap: "sublime", 
    theme: 'monokai', 
    autoCloseTags: true, 
    lineWrapping: true, 
    extraKeys: {"Ctrl-Space": "autocomplete"} 
}); 
editor2.on("change", function() { 
    clearTimeout(delay2); 

    delay2 = setTimeout(updatePreview2, 0); 
}); 

function updatePreview2() { 
    var scriptTag = "<script>"+editorJS.getValue()+"<"; 
    scriptTag += "/script>"; 

    var previewFrame2 = document.getElementById('preview'); 
    var preview2 = previewFrame2.contentDocument || previewFrame2.contentWindow.document; 
    preview2.open(); 
    preview2.write(editor2.getValue()+scriptTag); 
    preview2.close(); 

    loadCSS(); 
} 
setTimeout(updatePreview2, 0); 


var delayJS; 
// Initialize CodeMirror editor with a nice html5 canvas demo. 
var editorJS = CodeMirror.fromTextArea(document.getElementById('codeJS'), { 
    lineNumbers: true, 
    styleActiveLine: true, 
    matchBrackets: true, 
    mode: 'javascript', 
    keyMap: "sublime", 
    theme: 'monokai', 
    autoCloseTags: true, 
    lineWrapping: true, 
    extraKeys: {"Ctrl-Space": "autocomplete"} 
}); 
editorJS.on("change", function() { 
    clearTimeout(delayJS); 

    delayJS = setTimeout(updatePreviewJS, 0); 
}); 

function updatePreviewJS() { 
    loadJS(); 
} 
setTimeout(updatePreviewJS, 0); 
</script> 

ответ

3

из code mirror website

function getCompletions(token, context) { 
    var found = [], start = token.string; 
    function maybeAdd(str) { 
    if (str.indexOf(start) == 0) found.push(str); 
    } 
    function gatherCompletions(obj) { 
    if (typeof obj == "string") forEach(stringProps, maybeAdd); 
    else if (obj instanceof Array) forEach(arrayProps, maybeAdd); 
    else if (obj instanceof Function) forEach(funcProps, maybeAdd); 
    for (var name in obj) maybeAdd(name); 
    } 

    if (context) { 
    // If this is a property, see if it belongs to some object we can 
    // find in the current environment. 
    var obj = context.pop(), base; 
    if (obj.className == "js-variable") 
     base = window[obj.string]; 
    else if (obj.className == "js-string") 
     base = ""; 
    else if (obj.className == "js-atom") 
     base = 1; 
    while (base != null && context.length) 
     base = base[context.pop().string]; 
    if (base != null) gatherCompletions(base); 
    } 
    else { 
    // If not, just look in the window object and any local scope 
    // (reading into JS mode internals to get at the local variables) 
    for (var v = token.state.localVars; v; v = v.next) maybeAdd(v.name); 
    gatherCompletions(window); 
    forEach(keywords, maybeAdd); 
    } 
    return found; 
} 

вы нажимаете ctrl + space, чтобы включить подсказку кода.

+0

это для javascript. html можно найти здесь https://codemirror.net/demo/html5complete.html –

+0

Код, который вы написали, представляет собой пример кода, предоставленного codemirror для демонстрации. Но функциональность не будет работать только с этим кодом. Кстати, как насчет css auto hinting? Есть идеи? Спасибо! – Packer

+0

@Packer я сказал в своем ответе, что это было с сайта. не знаю, на css. есть большое обсуждение групп google об этом! –

1

Вы не опубликовали весь код, чтобы я мог ошибаться, но не забудьте добавить таблицу стилей show-hint.css в заголовок страницы.

<link rel="stylesheet" href="../addon/hint/show-hint.css"> 

В противном случае подсказки просто не отображаются, и я предположил, что функция автозаполнения не работает.

1

Weave: http://kodeweave.sourceforge.net/editor/#bc08cb08dee7609bbe7df11e8a55f27a

Есть много различных способов вы можете реализовать код намекая/автозаполнения.

var arrows = [37, 38, 39, 40] 

editor.on("keyup", function(cm, e) { 
    if (arrows.indexOf(e.keyCode) < 0) { 
    editor.execCommand("autocomplete") 
    } 
}) 

конечно же CodeMirror имеет official documentation для подсказки кода/автозаполнения.
XML completion
HTML completion
JavaScript completion

Вы можете view the source для яваскрипта примера, чтобы узнать, как сделать свои собственные намеки тоже.

Смежные вопросы