base.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334
  1. from __future__ import unicode_literals
  2. from prompt_toolkit.validation import Validator, ValidationError
  3. from six import string_types
  4. class SentenceValidator(Validator):
  5. """
  6. Validate input only when it appears in this list of sentences.
  7. :param sentences: List of sentences.
  8. :param ignore_case: If True, case-insensitive comparisons.
  9. """
  10. def __init__(self, sentences, ignore_case=False, error_message='Invalid input', move_cursor_to_end=False):
  11. assert all(isinstance(s, string_types) for s in sentences)
  12. assert isinstance(ignore_case, bool)
  13. assert isinstance(error_message, string_types)
  14. self.sentences = list(sentences)
  15. self.ignore_case = ignore_case
  16. self.error_message = error_message
  17. self.move_cursor_to_end = move_cursor_to_end
  18. if ignore_case:
  19. self.sentences = set([s.lower() for s in self.sentences])
  20. def validate(self, document):
  21. if document.text not in self.sentences:
  22. if self.move_cursor_to_end:
  23. index = len(document.text)
  24. else:
  25. index = 0
  26. raise ValidationError(cursor_position=index,
  27. message=self.error_message)