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

How can I express add value [value ...] in a grammar compile? #953

Open
laixintao opened this issue Aug 10, 2019 · 0 comments
Open

How can I express add value [value ...] in a grammar compile? #953

laixintao opened this issue Aug 10, 2019 · 0 comments

Comments

@laixintao
Copy link

Hi, I want to write a grammar like add value [value ...], for example:

add 1 2 3
add 1 2
add 10 11 12 13

All should be valid grammar.

Is it possible to do this in prompt_toolkit.contrib.regular_languages.compiler.compile? I tried everything but I can't figure it out. I tried with the grammar (\s* (?P<operator1>add) (\s+(?P<var1>[0-9.]+))+ \s*)

Here is the example I tried:

from prompt_toolkit import prompt
from prompt_toolkit.completion import WordCompleter
from prompt_toolkit.contrib.regular_languages.compiler import compile
from prompt_toolkit.contrib.regular_languages.completion import (
    GrammarCompleter,
)
from prompt_toolkit.contrib.regular_languages.lexer import GrammarLexer
from prompt_toolkit.lexers import SimpleLexer
from prompt_toolkit.styles import Style

operators1 = ['add']


def create_grammar():
    return compile(r"""
        (\s*  (?P<operator1>add)   (\s+(?P<var1>[0-9.]+))+    \s*)
    """)


example_style = Style.from_dict({
    'operator':       '#33aa33 bold',
    'number':         '#ff0000 bold',

    'trailing-input': 'bg:#662222 #ffffff',
})


if __name__ == '__main__':
    g = create_grammar()

    lexer = GrammarLexer(g, lexers={
        'operator1': SimpleLexer('class:operator'),
        'var1': SimpleLexer('class:number'),
    })

    completer = GrammarCompleter(g, {
        'operator1': WordCompleter(operators1),
    })

    # REPL loop.
    while True:
        # Read input and parse the result.
        text = prompt('Calculate: ', lexer=lexer, completer=completer,
                      style=example_style)
        m = g.match(text)
        if m:
            vars = m.variables()
        else:
            print('Invalid command\n')
            continue

        print(vars)

It seems that it can only recognize the last var1:

image

Many thanks.

@jonathanslenders

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

No branches or pull requests

1 participant