react-codemirror icon indicating copy to clipboard operation
react-codemirror copied to clipboard

Hints?

Open desduvauchelle opened this issue 9 years ago • 10 comments

Hello. Thanks for this!

Is it possible to use code hints? If yes, could you provide an example?

Thanks!

desduvauchelle avatar May 28 '16 20:05 desduvauchelle

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:)

yakewdx avatar Jul 21 '16 04:07 yakewdx

@desduvauchelle Did the above response solved the issue? I'm wondering can we close it.

revelt avatar Dec 22 '16 14:12 revelt

@yakewdx is there a way to show the autocomplete dropdown automatically on every key stroke?

ankitgoyal100 avatar Jan 04 '17 19:01 ankitgoyal100

@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.

yakewdx avatar Jan 07 '17 08:01 yakewdx

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}
      />
    );
  }
}

rickbergfalk avatar May 25 '17 15:05 rickbergfalk

@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.

JakubKahovec avatar Jun 02 '17 21:06 JakubKahovec

@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.

rickbergfalk avatar Jun 02 '17 23:06 rickbergfalk

@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.

JakubKahovec avatar Jun 03 '17 08:06 JakubKahovec

@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.

JakubKahovec avatar Jun 05 '17 06:06 JakubKahovec

`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

archiesbhoir avatar Jun 28 '19 14:06 archiesbhoir