Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

context.matchBefore for creating autocompletions ignores other matches if there is a match at the start of the line #1510

Open
nsrCodes opened this issue Jan 22, 2025 · 2 comments · May be fixed by codemirror/autocomplete#27

Comments

@nsrCodes
Copy link

Here's a demo.ts file to help reproduce the bug:

import {EditorView, basicSetup} from "codemirror"
import {javascript} from "@codemirror/lang-javascript"
import { autocompletion, Completion, CompletionResult, CompletionSource } from "@codemirror/autocomplete";


const dummyCompletions: Completion[] = [{label: "foo"}, {label: "bar"}] 

function generateCompletionSource(
  matchPattern: RegExp,
  completions: Completion[],
  lengthOfStartingChars: number
): CompletionSource {
  return (context) => {
    const match = context.matchBefore(matchPattern);
    if (match) {
      return {
        from: match.from + lengthOfStartingChars,
        to: match.to,
        options: completions,
        filter: true,
      } as CompletionResult;
    } else return null;
  };
}

function generateAutocompletePlugin() {
  return autocompletion({
    override: [generateCompletionSource(/\{\{.*?/g, dummyCompletions, 2)]
  })
}

;(window as any).view = new EditorView({
  doc: 'console.log("Hello world")',
  extensions: [
    basicSetup,
    javascript(),
    generateAutocompletePlugin()
  ],
  parent: document.body
})

if the editor has a line like {{anything}} {{fo and the cursor is at the end, the auto completions are not shown even though it should be captured by the regex in the code (/\{\{.*?/g at least since there is an explicit global flag)

The auto completions are not shown for any matching occurrences after the first one

Screen.Recording.2025-01-22.at.10.19.53.PM.mov
@nsrCodes
Copy link
Author

If there is a way to achieve this by fixing my code for generating the autoCompletions feel free to point that out, but I thought this is a bug and so have raised a PR for the same

@marijnh
Copy link
Member

marijnh commented Jan 23, 2025

I don't think complicating the semantics of this method is a good idea. Regexps are messy, and they won't work in all situations. But there's no real reason the updated behavior is more obvious than the current behavior, and that kind of hidden cleverness will trip people up.

I think if you use /\{\{([^{]|\{[^{])*$/ instead, you should get the match you're looking for.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
2 participants