javascript codemirror在任何keyup后自动完成?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13744176/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
codemirror autocomplete after any keyup?
提问by Kyle
I'm working on trying to add a custom autocomplete, that I want to trigger whenever the user is typing (configurable of course). I've found a couple examples of autocomplete for codemirror:
我正在尝试添加自定义自动完成功能,我想在用户输入时触发它(当然可以配置)。我发现了一些 codemirror 自动完成的例子:
http://codemirror.net/demo/complete.htmland http://codemirror.net/demo/xmlcomplete.html
http://codemirror.net/demo/complete.html和 http://codemirror.net/demo/xmlcomplete.html
But both of these trigger on specific keys (Control-Space for one and '<' for the other) and both use the extraKeys
functionality to process the events, but I want to trigger from any key. I have tried the following:
但是这两个都在特定键上触发(一个是 Control-Space,另一个是 '<')并且都使用该extraKeys
功能来处理事件,但我想从任何键触发。我尝试了以下方法:
var editor = CodeMirror.fromTextArea(document.getElementById("code"),
{
lineNumbers: true,
mode: "text/x-mysql",
fixedGutter: true,
gutter: true,
// extraKeys: {"'.'": "autocomplete"}
keyup: function(e)
{
console.log('testing');
},
onkeyup: function(e)
{
console.log('testing2');
}
});
But have had no luck. Any suggestions on how I could trigger from any keyup events?
但没有运气。关于如何从任何键盘事件触发的任何建议?
采纳答案by aljordan82
onKeyEvent: function(e , s){
if (s.type == "keyup")
{
console.log("test");
}
}
回答by Sasha
For version 5.7 neither of the previously proposed solutions work fine for me (and I think they have bugs even for earlier versions). My solution:
对于 5.7 版,之前提出的解决方案都不适用于我(我认为即使对于早期版本,它们也有错误)。我的解决方案:
myCodeMirror.on("keyup", function (cm, event) {
if (!cm.state.completionActive && /*Enables keyboard navigation in autocomplete list*/
event.keyCode != 13) { /*Enter - do not open autocomplete list just after item has been selected in it*/
CodeMirror.commands.autocomplete(cm, null, {completeSingle: false});
}
});
How it works:
怎么运行的:
This opens autocomplete popup only if it is not opened yet (otherwise keyboard-navigation would have caused reopening the popup with 1st item selected again).
这仅在尚未打开时打开自动完成弹出窗口(否则键盘导航会导致重新打开弹出窗口并再次选择第一个项目)。
When you click Enteryou want popup to close so this is special case of a character which shouldn't trigger autocompletion (you may consider a case when you want to show antocompletion for empty line though).
当您单击Enter 时,您希望弹出窗口关闭,因此这是不应触发自动完成的字符的特殊情况(尽管您可能会考虑要为空行显示 antocompletion 的情况)。
Then last fix is setting completeSingle: false
which prevents case when you are typing some word and in the middle it is automatically completed and you continue typing by reflex. So user will always need to select the intended string from popup (even if it's single option).
然后最后一个修复是设置completeSingle: false
,当您输入某个单词时防止大小写,并且在中间它会自动完成并且您继续通过反射输入。所以用户总是需要从弹出窗口中选择想要的字符串(即使它是单一选项)。
回答by Buh Buh
To also display the autocomplete widget:
还要显示自动完成小部件:
onKeyEvent: function (e, s) {
if (s.type == "keyup") {
CodeMirror.showHint(e);
}
}
回答by Tobias Punke
The most IntelliSense-like behavior can be achieved by this:
可以通过以下方式实现最类似于 IntelliSense 的行为:
var ExcludedIntelliSenseTriggerKeys =
{
"8": "backspace",
"9": "tab",
"13": "enter",
"16": "shift",
"17": "ctrl",
"18": "alt",
"19": "pause",
"20": "capslock",
"27": "escape",
"33": "pageup",
"34": "pagedown",
"35": "end",
"36": "home",
"37": "left",
"38": "up",
"39": "right",
"40": "down",
"45": "insert",
"46": "delete",
"91": "left window key",
"92": "right window key",
"93": "select",
"107": "add",
"109": "subtract",
"110": "decimal point",
"111": "divide",
"112": "f1",
"113": "f2",
"114": "f3",
"115": "f4",
"116": "f5",
"117": "f6",
"118": "f7",
"119": "f8",
"120": "f9",
"121": "f10",
"122": "f11",
"123": "f12",
"144": "numlock",
"145": "scrolllock",
"186": "semicolon",
"187": "equalsign",
"188": "comma",
"189": "dash",
"190": "period",
"191": "slash",
"192": "graveaccent",
"220": "backslash",
"222": "quote"
}
EditorInstance.on("keyup", function(editor, event)
{
var __Cursor = editor.getDoc().getCursor();
var __Token = editor.getTokenAt(__Cursor);
if (!editor.state.completionActive &&
!ExcludedIntelliSenseTriggerKeys[(event.keyCode || event.which).toString()] &&
(__Token.type == "tag" || __Token.string == " " || __Token.string == "<" || __Token.string == "/"))
{
CodeMirror.commands.autocomplete(editor, null, { completeSingle: false });
}
});
回答by Damodharan J
editor.on("inputRead",function(cm,changeObj){
// hinting logic
})
As far I've seen, "inputRead" is the best event to show "auto completions" in "codemirror". The only drawback is that you can't show hints on backspace or delete.
就我所见,“inputRead”是在“codemirror”中显示“自动完成”的最佳事件。唯一的缺点是您无法显示退格或删除提示。
回答by Gary Gauh
Let me share a full example that contains autocomplete(for hive sql) after any keyup:
让我分享一个完整的例子,它在任何 keyup 之后包含自动完成(对于 hive sql):
Include scripts and styles:
包括脚本和样式:
<link rel="stylesheet" href="/static/codemirror/lib/codemirror.css">
<link rel="stylesheet" href="/static/codemirror/theme/material.css">
<link rel="stylesheet" href="/static/codemirror/addon/hint/show-hint.css" />
<script type="text/javascript" src="/static/codemirror/lib/CodeMirror.js"></script>
<script type="text/javascript" src="/static/codemirror/mode/sql/sql.js"></script>
<script type="text/javascript" src="/static/codemirror/addon/hint/show-hint.js"></script>
<script type="text/javascript" src="/static/codemirror/addon/hint/sql-hint.js"></script>
Html :
网址:
<textarea id="code" name="code" rows="4" placeholder="" value=""></textarea>
Script :
脚本 :
<script>
$(function () {
initSqlEditor();
initAutoComplete();
});
// init sql editor
function initSqlEditor() {
var editor = CodeMirror.fromTextArea(document.getElementById('code'), {
autofocus: true,
extraKeys: {
"Tab": "autocomplete"
},
hint: CodeMirror.hint.sql,
lineNumbers: true,
mode: 'text/x-hive',
lineWrapping: true,
theme: 'material',
});
editor.on('keyup', function(editor, event){
// type code and show autocomplete hint in the meanwhile
CodeMirror.commands.autocomplete(editor);
});
}
/**
* Init autocomplete for table name and column names in table.
*/
function initAutoComplete() {
CodeMirror.commands.autocomplete = function (cmeditor) {
CodeMirror.showHint(cmeditor, CodeMirror.hint.sql, {
// "completeSingle: false" prevents case when you are typing some word
// and in the middle it is automatically completed and you continue typing by reflex.
// So user will always need to select the intended string
// from popup (even if it's single option). (copy from @Oleksandr Pshenychnyy)
completeSingle: false,
// there are 2 ways to autocomplete field name:
// (1) table_name.field_name (2) field_name
// Put field name in table names to autocomplete directly
// no need to type table name first.
tables: {
"table1": ["col_A", "col_B", "col_C"],
"table2": ["other_columns1", "other_columns2"],
"col_A": [],
"col_B": [],
"col_C": [],
"other_columns1": [],
"other_columns2": [],
}
});
}
}
</script>
回答by Aditya Shankar
changed Oleksandr Pshenychnyy's answer a little bit(see here), Answering as I can't add comments yet
稍微改变了 Oleksandr Pshenychnyy 的回答(见这里),回答我还不能添加评论
The code below only allows autocomplete to come up when a letter key is pressed (probably what you want instead on any key)
下面的代码只允许在按下字母键时自动完成(可能是你想要的任何键)
editor.on("keyup", function (cm, event) {
if (!cm.state.completionActive && /*Enables keyboard navigation in autocomplete list*/
event.keyCode > 64 && event.keyCode < 91){// only when a letter key is pressed
CodeMirror.commands.autocomplete(cm, null, {completeSingle: false});
}
});
(this should work logically, but could some please comment if this works or not !)
(这应该合乎逻辑,但如果这行得通,请评论一下!)
回答by Ronn Wilder
I think everyone has their own use cases. I also had to club parts from different answers to make something which is best for my case.
我想每个人都有自己的用例。我还必须从不同的答案中挑选部分,以制作最适合我的情况的东西。
According to me, I want to show suggestions only on alphabets, numbers, and (.) with an exception of ctrl key pressed. because sometimes I copy or paste something, so that should not open suggestions. 46 ascii is for (.) which I've included with numbers.
据我说,除了按 ctrl 键外,我只想显示有关字母、数字和 (.) 的建议。因为有时我会复制或粘贴某些内容,因此不应打开建议。46 ascii 用于 (.),我已将其包含在数字中。
activeEditor.on("keydown", function (cm, event) {
if (
!(event.ctrlKey) &&
(event.keyCode >= 65 && event.keyCode <= 90) ||
(event.keyCode >= 97 && event.keyCode <= 122) ||
(event.keyCode >= 46 && event.keyCode <= 57)
) {
CodeMirror.commands.autocomplete(cm, null, {completeSingle: false});
}
});
Do remeber to include 3 things -
请记住包括 3 件事 -
js and css of show hint -
<link rel="stylesheet" href="codemirror/addon/hint/show-hint.css"> <script src="codemirror/addon/hint/show-hint.js"></script>
script for language you want the hint for - for ex - javascript
<script src="codemirror/addon/hint/javascript-hint.js"></script>
include this line while initializing your code editor. I've used javascript hint.
hint: CodeMirror.hint.javascript
显示提示的 js 和 css -
<link rel="stylesheet" href="codemirror/addon/hint/show-hint.css"> <script src="codemirror/addon/hint/show-hint.js"></script>
您想要提示的语言脚本 - 例如 - javascript
<script src="codemirror/addon/hint/javascript-hint.js"></script>
在初始化代码编辑器时包括这一行。我使用过 javascript 提示。
hint: CodeMirror.hint.javascript
回答by SWAPNIL KUWAR
Use this function to autocomplete codeMirror without CTRL + Space.
使用此功能可以在没有 CTRL + 空格的情况下自动完成 codeMirror。
set completeSingle to false in the show-hint.js
在 show-hint.js 中将 completeSingle 设置为 false
editor.on("inputRead", function(instance) {
if (instance.state.completionActive) {
return;
}
var cur = instance.getCursor();
var token = instance.getTokenAt(cur);
if (token.type && token.type != "comment") {
CodeMirror.commands.autocomplete(instance);
}
});
回答by Yuting Woo
editor.on('keyup', function(){
CodeMirror.commands.autocomplete(editor);
});
it may works
它可能有效