uiwjs / react-codemirror

CodeMirror 6 component for React. @codemirror https://uiwjs.github.io/react-codemirror/
https://uiwjs.github.io/react-codemirror/
MIT License
1.65k stars 132 forks source link

How to setup autocomplete #527

Closed avin-kavish closed 1 year ago

avin-kavish commented 1 year ago

I saw this snippet on SO for setting up SQL auto-complete with table names and columns.

CodeMirror.commands.autocomplete = function(cm) {
    CodeMirror.showHint(cm, CodeMirror.hint.sql, { 
        tables: {
            "table1": [ "col_A", "col_B", "col_C" ],
            "table2": [ "other_columns1", "other_columns2" ]
        }
    } );
}

Can I do the same with the react version?

jaywcjlove commented 1 year ago

@avin-kavish https://codemirror.net/examples/autocompletion/

avin-kavish commented 1 year ago

I mean in the react version.

jaywcjlove commented 1 year ago

@avin-kavish The method of use is the same.

<CodeMirror
  value="console.log('hello world!');"
  height="200px"
+  extensions={[
+    //.... Set it here
+  ]}
  onChange={onChange}
 />
jaywcjlove commented 1 year ago

@codercoin98 Example: https://codesandbox.io/embed/vibrant-marco-p8znlj?fontsize=14&hidenavigation=1&theme=dark

import React from "react";
import CodeMirror from "@uiw/react-codemirror";
import { autocompletion } from "@codemirror/autocomplete";

// Our list of completions (can be static, since the editor
/// will do filtering based on context).
const completions = [
  { label: "panic", type: "keyword" },
  { label: "park", type: "constant", info: "Test completion" },
  { label: "password", type: "variable" }
];

function myCompletions(context) {
  let before = context.matchBefore(/\w+/);
  // If completion wasn't explicitly started and there
  // is no word before the cursor, don't open completions.
  if (!context.explicit && !before) return null;
  return {
    from: before ? before.from : context.pos,
    options: completions,
    validFor: /^\w*$/
  };
}

function App() {
  const [value, setValue] = React.useState("// Type a 'p'\n");
  const onChange = React.useCallback((val, viewUpdate) => {
    console.log("val:", val);
    setValue(val);
  }, []);
  return (
    <CodeMirror
      value={value}
      height="200px"
      extensions={[autocompletion({ override: [myCompletions] })]}
      onChange={onChange}
    />
  );
}

export default App;
Swat009 commented 1 year ago

I think this was the intend of the question

import { sql } from "@codemirror/lang-sql";

<CodeMirror
  value={command}
  extensions={[
    sql({
      schema: {
        "customers": ['abc', 'efg'],
        "table1": ['hij', 'klm'],
        "table2": [],
        "str.table4": ['sadad'],
      },
    })
  ]}
/>