/* eslint-disable no-useless-escape */
// To keep the regular expressions in sync with Beancount, they might contain
// some superfluous escape characters.

import CodeMirror from "codemirror";

// Import the autogenerated (by a script in the 'contrib' directory) lists
import bqlGrammar from "./bql-grammar";

const { columns, functions, keywords } = bqlGrammar;

// This should match the grammar defined in Beancount (`query/query_parser.py`).
CodeMirror.defineSimpleMode("beancount-query", {
  start: [
    {
      regex: new RegExp(`(?=^|\\s)(${keywords.join("|")})(?=\\s|$)`, "i"),
      token: "keyword",
    },
    {
      regex: /(\"[^\"]*\"|\'[^\']*\')/,
      token: "string",
    },
    {
      regex: /(?:\#(?:\"[^\"]*\"|\'[^\']*\')|\d\d\d\d-\d\d-\d\d)/,
      token: "date",
    },
    {
      regex: /[-+]?([0-9]+\.[0-9]*|[0-9]*\.[0-9]+)/,
      token: "number",
    },
    {
      regex: /[-+]?[0-9]+/,
      token: "number",
    },
    {
      regex: new RegExp(`(${columns.join("|")})(?=\\)|\\s|,|$)`, "i"),
      token: "variable-2",
    },
    {
      regex: new RegExp(`(${functions.join("|")})(?=\\()`, "i"),
      token: "variable-3",
    },
  ],
});
