Comments (10)
I was able to get a built-in codemirror hints working and configured without modifying any of the react-codemirror or codemirror files, and figured I'd share.
Assuming you have a webpack/create-react-app setup you can do:
'use es6';
import React, { PureComponent } from 'react';
import CodeMirror from 'react-codemirror';
// assuming a setup with webpack/create-react-app import the additional js/css files
import 'codemirror/mode/sql/sql';
import 'codemirror/addon/hint/show-hint';
import 'codemirror/addon/hint/sql-hint';
import 'codemirror/addon/hint/show-hint.css'; // without this css hints won't show
class CodeEditorField extends PureComponent {
autoComplete = cm => {
const codeMirror = this.refs['CodeMirror'].getCodeMirrorInstance();
// hint options for specific plugin & general show-hint
// 'tables' is sql-hint specific
// 'disableKeywords' is also sql-hint specific, and undocumented but referenced in sql-hint plugin
// Other general hint config, like 'completeSingle' and 'completeOnSingleClick'
// should be specified here and will be honored
const hintOptions = {
tables: {
table_name: ['column1', 'column2', 'column3', 'etc'],
another_table: ['columnA', 'columnB']
},
disableKeywords: true,
completeSingle: false,
completeOnSingleClick: false
};
// codeMirror.hint.sql is defined when importing codemirror/addon/hint/sql-hint
// (this is mentioned in codemirror addon documentation)
// Reference the hint function imported here when including other hint addons
// or supply your own
codeMirror.showHint(cm, codeMirror.hint.sql, hintOptions);
};
handleChange = value => {};
render() {
const options = {
lineNumbers: true,
mode: 'text/x-pgsql',
tabSize: 2,
readOnly: false,
extraKeys: {
'Ctrl-Space': this.autoComplete
}
};
return (
<CodeMirror
ref="CodeMirror"
value={value}
onChange={this.handleChange}
options={options}
/>
);
}
}
from react-codemirror.
I have found a way to use hint.
I registered the show-hint add-on in componentDidMount
function.
// editor.js
var React = require('react');
var Codemirror = require('react-codemirror');
var CodeMirror = React.createClass({
getInitialState: function () {
return {
code: "// Code"
};
},
updateCode: function (newCode) {
this.setState({
code: newCode
});
},
componentDidMount: function () {
"use strict";
let CodeMirror = this.refs['CodeMirror'].getCodeMirrorInstance();
let showHint = require('./show-hint');
showHint(CodeMirror);
/* the part below is copied from anyword-hint.js */
var WORD = /([\u4e00-\u9fa5]|[a-zA-Z])+/, RANGE = 500;
CodeMirror.registerHelper("hint", "tag", function (editor, options) {
var word = options && options.word || WORD;
var range = options && options.range || RANGE;
var cur = editor.getCursor(), curLine = editor.getLine(cur.line);
var end = cur.ch, start = end;
while (start && word.test(curLine.charAt(start - 1)))--start;
var curWord = start != end && curLine.slice(start, end);
var list = options && options.list || [], seen = {};
var re = new RegExp(word.source, "g");
for (var dir = -1; dir <= 1; dir += 2) {
var line = cur.line, endLine = Math.min(Math.max(line + dir * range, editor.firstLine()), editor.lastLine()) + dir;
for (; line != endLine; line += dir) {
var text = editor.getLine(line), m;
while (m = re.exec(text)) {
if (line == cur.line && m[0] === curWord) continue;
if ((!curWord || m[0].lastIndexOf(curWord, 0) == 0) && !Object.prototype.hasOwnProperty.call(seen, m[0])) {
seen[m[0]] = true;
list.push(m[0]);
}
}
}
}
return { list: list, from: CodeMirror.Pos(cur.line, start), to: CodeMirror.Pos(cur.line, end) };
});
},
autocomplete: function (cm) {
let codeMirror = this.refs['CodeMirror'].getCodeMirrorInstance();
codeMirror.showHint(cm, codeMirror.hint.tag);
},
render: function () {
var options = {
lineNumbers: true,
lineWrapping: true,
extraKeys: {
'Tab': this.autocomplete
}
};
return <Codemirror ref="CodeMirror" value={this.state.code} onChange={this.updateCode} options={options} />
}
});
module.exports.CodeMirror = CodeMirror;
and the file
show-hint.js
also need a bit rearrange.
// show-hint.js
// remove this part
/*
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})
*/
var showHint = function (CodeMirror) {
/*
contents remain unchanged.
*/
}
module.exports = showHint;
and then you can use 'Tab' key to fire a hint.
I hope this may help you:)
from react-codemirror.
@ankitgoyal100
You have to activate the event handler.
According to the documents of CodeMirror,
the event 'keyup' is the right choice.
"mousedown", "dblclick", "touchstart", "contextmenu", "keydown", "keypress", "keyup", "cut", "copy", "paste", "dragstart", "dragenter", "dragover", "dragleave", "drop" (instance: CodeMirror, event: Event)
Fired when CodeMirror is handling a DOM event of this type. You can preventDefault the event, or give it a truthy codemirrorIgnore property, to signal that CodeMirror should do no further handling.
So you can change a bit of the source code of react-codemirror.
In the file node-modules/react-codemirror/lib/Codemirror.js
,
add the event handler:
// Codemirror.js
componentDidMount: function componentDidMount() {
var textareaNode = this.refs.textarea;
var codeMirrorInstance = this.getCodeMirrorInstance();
this.codeMirror = codeMirrorInstance.fromTextArea(textareaNode, this.props.options);
this.codeMirror.on('change', this.codemirrorValueChanged);
this.codeMirror.on('focus', this.focusChanged.bind(this, true));
this.codeMirror.on('blur', this.focusChanged.bind(this, false));
// add keyup events
this.codeMirror.on('keyup', this.keyUp.bind(this, true));
this.codeMirror.setValue(this.props.defaultValue || this.props.value || '');
},
keyUp: function (key) {
this.props.onKeyUp();
},
and also in editor.js
,
add the event handler,
// editor.js
handleKeyUpEvent: function (e) {
let cm = this.refs['CodeMirror'].getCodeMirror();
this.autocomplete(cm);
},
autocomplete: function (cm) {
let codeMirror = this.refs['CodeMirror'].getCodeMirrorInstance();
codeMirror.showHint(cm, codeMirror.hint.tag);
},
render: function () {
var options = {
lineNumbers: true,
lineWrapping: true,
completeSingle: false,
completeOnSingleClick: false,
extraKeys: {
'Tab': this.autocomplete
}
};
return <Codemirror ref="CodeMirror" value={this.state.code} onKeyUp={this.handleKeyUpEvent} onChange={this.updateCode} options={options} />
}
If you want to handle other original events of codemirror,
you can use similar way like this.
by the way, if you want to autocomplete by every keystroke,
you should turn off completeSingle
, I tried to set this option in editor.js
, but it did not work.
You can change the default setting in show-hint.js.
var defaultOptions = {
hint: CodeMirror.hint.auto,
completeSingle: false,
alignWithWord: true,
closeCharacters: /[\s()\[\]{};:>,]/,
closeOnUnfocus: true,
completeOnSingleClick: false,
container: null,
customKeys: null,
extraKeys: null
};
Hope this helps.
from react-codemirror.
`autoComplete = cm => {
const codeMirror = this.refs['CodeMirror'].getCodeMirrorInstance();
const customTags = {
'!top': ['add','hello'],
'!attrs': {},
'add': {
attrs: {
'id': null
},
children: ['Student', 'hello']
},
'hello': {
attrs: {
'id': null
},
children: ['A-Child']
},
'Student': {
attrs: {
name: null
},
children: ['A-Child']
},
'A-Child': {
attrs: {
roll_no: null
},
children: ['marks']
},
'marks': {
children: [],
},
};
const hintOptions = {
schemaInfo: customTags,
completeSingle: false,
completeOnSingleClick: true,
matchInMiddle: true
};
codeMirror.showHint(cm, codeMirror.hint.auto, hintOptions);
};`
Worked for me
from react-codemirror.
@desduvauchelle Did the above response solved the issue? I'm wondering can we close it.
from react-codemirror.
@yakewdx is there a way to show the autocomplete dropdown automatically on every key stroke?
from react-codemirror.
@rickbergfalk does the dropdown with options get shown ? I made it somehow working, it auto-completes a word, but the dropdown with options never appears.
from react-codemirror.
@JakubKahovec It should... I ran into similar issues. A couple things to check:
- make sure you're including the dropdown css
import 'codemirror/addon/hint/show-hint.css';
- if only 1 match would display in the dropdown, I believe the default codemirror behavior is to automatically complete and skip showing the dropdown. To avoid this set
completeSingle
to false in the hint options passed to showHint.
from react-codemirror.
@rickbergfalk I've double checked show-hint css is there (it appears as an inline css) and completeSingle is false. The only thing is I don't use create-react-app, but have my own stack. The code is almost identical to yours, the only difference is I use javascript hint. When I press Ctrl-Space nothing appears but when then I press Tab it completes the word with some random word (i.e 'f' completes with 'find'). When I debug it it jumps into the autoComplete, calls codeMirror.showHint but the popup does not appear.
from react-codemirror.
@rickbergfalk finally got it. I had the codemirror editor in a modal window (semantic ui) so the hints popup was hidden behind it. Setting z-index to max on hints popup fixed it.
from react-codemirror.
Related Issues (20)
- Theme syntax highlighting not working HOT 3
- how can I beautify(formatting) code after load HOT 2
- Foldcode not working for me. And not even getting foldgutter. Any help? HOT 3
- Update peerDependencies for react > 16 HOT 1
- Is this library deprecated? HOT 2
- How to integrate codemirror-formatting plugin with react
- Focus lost after typing character HOT 2
- How do I use methods like setSize of an instance?
- How to Set Default Background Color and Default Content Width in Editor?????
- Line numbers sometimes don't load properly using fromTextArea
- Can't use defineMode ?
- beforeChange is not fired?
- autofocus is broken on UnControlled
- how can I use MergeView
- lineNumbers show in preview codemirror
- .
- New project with react-codemirror on typescript HOT 1
- Codemirror syntax highlighting works in preview but not when published
- Support React 17 HOT 1
- When pasting in multi-line values, it pastes twice HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from react-codemirror.