File: TextDomain.py

package info (click to toggle)
onboard 1.4.1-5
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye
  • size: 31,548 kB
  • sloc: python: 29,215; cpp: 5,965; ansic: 5,735; xml: 1,026; sh: 163; makefile: 39
file content (1026 lines) | stat: -rw-r--r-- 36,772 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
# -*- coding: utf-8 -*-

# Copyright © 2012-2017 marmuta <marmvta@gmail.com>
#
# This file is part of Onboard.
#
# Onboard is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# Onboard is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

from __future__ import division, print_function, unicode_literals

import os
import re
import glob

import logging

from Onboard.Version import require_gi_versions
require_gi_versions()
try:
    from gi.repository import Atspi
except ImportError as e:
    pass

from Onboard.TextChanges  import TextSpan
from Onboard.utils        import KeyCode, Modifiers, unicode_str

_logger = logging.getLogger("TextDomain")

class TextDomains:
    """ Collection of all recognized text domains. """

    def __init__(self):
        # default domain has to be last
        self._domains = [
                         DomainTerminal(),
                         DomainURL(),
                         DomainPassword(),
                         DomainGenericText(),
                         DomainNOP()
                        ]

    def find_match(self, **kwargs):
        for domain in self._domains:
            if domain.matches(**kwargs):
                return domain
        return None  # should never happen, default domain always matches

    def get_nop_domain(self):
        return self._domains[-1]


class TextDomain:
    """
    Abstract base class as a catch-all for domain specific functionalty.
    """

    def __init__(self):
        self._url_parser = PartialURLParser()

    def matches(self, **kwargs):
        # Weed out unity text entries that report being editable but don't
        # actually provide methods of the Atspi.Text interface.
        return "Text" in kwargs.get("interfaces", [])

    def init_domain(self):
        """ Called on being selected as the currently active domain. """
        pass

    def read_context(self, keyboard, accessible):
        return NotImplementedError()

    def get_text_begin_marker(self):
        return ""

    def get_auto_separator(self, context):
        """
        Get word separator to add after inserting a prediction choice.

        Doctests:

        >>> from os.path import join

        # URL
        >>> d = DomainGenericText()
        >>> d.get_auto_separator("word http")
        ' '
        >>> d.get_auto_separator("word http://www")
        '.'
        >>> d.get_auto_separator("word http://www.domain.org/path")
        '/'
        >>> d.get_auto_separator("word http://www.domain.org/path/document.ext")
        ''

        # filename
        >>> import tempfile
        >>> from os.path import abspath, dirname, join
        >>> def touch(fn):
        ...     with open(fn, mode="w") as f: n = f.write("")
        >>> td = tempfile.TemporaryDirectory(prefix="test_onboard _")
        >>> dir = td.name

        >>> touch(join(dir, "onboard-defaults.conf.example"))
        >>> touch(join(dir, "onboard-defaults.conf.example.another"))
        >>>
        >>> d.get_auto_separator("/etc")
        '/'
        >>> d.get_auto_separator(join(dir, "onboard-defaults"))
        '.'
        >>> d.get_auto_separator(join(dir, "onboard-defaults.conf"))
        '.'
        >>> d.get_auto_separator(join(dir, "onboard-defaults.conf.example"))
        ''
        >>> d.get_auto_separator(join(dir, "onboard-defaults.conf.example.another"))
        ' '

        # filename in directory with spaces
        >>> import tempfile
        >>> td = tempfile.TemporaryDirectory(prefix="test onboard _")
        >>> dir = td.name
        >>> fn = os.path.join(dir, "onboard-defaults.conf.example")
        >>> touch(fn)
        >>> d.get_auto_separator(join(dir, "onboard-defaults"))
        '.'

        # no false positives for valid filenames before the current token
        >>> d.get_auto_separator(dir + "/onboard-defaults no-file")
        ' '
        """
        separator = " "

        # Split at whitespace to catch whole URLs/file names and
        # keep separators.
        strings = re.split('(\s+)', context)
        if strings:
            string = strings[-1]
            if self._url_parser.is_maybe_url(string):
                separator = self._url_parser.get_auto_separator(string)
            else:
                fn = self._search_valid_file_name(strings)
                if fn:
                    string = fn
                if self._url_parser._is_maybe_filename(string):
                    url = "file://" + string
                    separator = self._url_parser.get_auto_separator(url)

        return separator


    def _search_valid_file_name(self, strings):
        """
        Search for a valid filename backwards across separators.

        Doctests:
        >>> import tempfile, re, os.path
        >>>
        >>> d = DomainGenericText()
        >>>
        >>> td = tempfile.TemporaryDirectory(prefix="test onboard _")
        >>> dir = td.name
        >>> fn1 = os.path.join(dir, "file")
        >>> fn2 = os.path.join(dir, "file with many spaces")
        >>> with open(fn1, mode="w") as f: n = f.write("")
        >>> with open(fn2, mode="w") as f: n = f.write("")

        # simple file in dir with spaces must return as filename
        >>> strings = re.split('(\s+)', fn1)
        >>> "/test onboard" in d._search_valid_file_name(strings)
        True

        # file with spaces in dir with spaces must return as filename
        >>> strings = re.split('(\s+)', fn2)
        >>> "/test onboard" in d._search_valid_file_name(strings)
        True

        # random string after a valid file must not be confused with a filename
        >>> strings = re.split('(\s+)', fn2 + " no-file")
        >>> d._search_valid_file_name(strings) is None
        True
        """
        # Search backwards across spaces for an absolute filename.
        max_sections = 16  # allow this many path sections (separators+tokens)
        for i in range(min(max_sections, len(strings))):
            fn = "".join(strings[-1-i:])
            # Is it (part of) a valid absolute filename?
            # Do least impact checks first.
            if self._url_parser._is_maybe_filename(fn) and \
               os.path.isabs(fn):

                # Does a file or directory of this name exist?
                if os.path.exists(fn):
                    return fn

                # Check if it is at least an incomplete filename of
                # an existing file
                files  = glob.glob(fn + "*")
                if files:
                    return fn

        return None

    def grow_learning_span(self, text_span):
        """
        Grow span before learning to include e.g. whole URLs.

        Doctests:
        >>> d = DomainGenericText()

        # Span doesn't grow for simple words
        >>> d.grow_learning_span(TextSpan(8, 1, "word1 word2 word3"))
        (8, 1, 'r')

        # Span grows to include a complete URL
        >>> d.grow_learning_span(TextSpan(13, 1, "http://www.domain.org"))
        (0, 21, 'http://www.domain.org')

        # Span grows to include multiple complete URLs
        >>> d.grow_learning_span(TextSpan(19, 13, "http://www.domain.org word http://slashdot.org"))
        (0, 46, 'http://www.domain.org word http://slashdot.org')

        # Span grows to include a complete filename
        >>> d.grow_learning_span(TextSpan(10, 1, "word1 /usr/bin/bash word2"))
        (6, 13, '/usr/bin/bash')

        # Edge cases
        >>> d.grow_learning_span(TextSpan(6, 0, "word1 /usr/bin/bash word2"))
        (6, 0, '')
        >>> d.grow_learning_span(TextSpan(19, 0, "word1 /usr/bin/bash word2"))
        (19, 0, '')
        >>> d.grow_learning_span(TextSpan(6, 1, "word1 /usr/bin/bash word2"))
        (6, 13, '/usr/bin/bash')
        >>> d.grow_learning_span(TextSpan(18, 1, "word1 /usr/bin/bash word2"))
        (6, 13, '/usr/bin/bash')

        # Large text with text offset>0: returned position must be offset too
        >>> d.grow_learning_span(TextSpan(116, 1,
        ...     "word1 /usr/bin/bash word2", 100))
        (106, 13, '/usr/bin/bash')
        """
        text   = text_span.get_text()
        offset = text_span.text_begin()
        begin  = text_span.begin() - offset
        end    = text_span.end() - offset

        sections, spans = self._split_growth_sections(text)

        for i, s in enumerate(spans):
            if begin < s[1] and end > s[0]:  # intersects?

                section = sections[i]
                span = spans[i]
                if self._url_parser.is_maybe_url(section) or \
                   self._url_parser._is_maybe_filename(section):
                    begin = min(begin, span[0])
                    end = max(end, span[1])

        return begin + offset, end - begin, text[begin:end]

    def can_record_insertion(self, accessible, pos, length):
        return True

    def can_give_keypress_feedback(self):
        return True

    def can_spell_check(self, section_span):
        return False

    def can_auto_correct(self, section_span):
        return False

    def can_auto_punctuate(self, has_begin_of_text):
        return False

    def can_suggest_before_typing(self):
        """ Can give word suggestions before typing has started? """
        return True

    def handle_key_press(self, keycode, mod_mask):
        return True, None  # entering_text, end_of_editing

    _growth_sections_pattern = re.compile("[^\s?#@]+", re.DOTALL)

    def _split_growth_sections(self, text):
        """
        Split text at whitespace and other delimiters where
        growing learning spans should stop.

        Doctests:
        >>> d = DomainGenericText()
        >>> d._split_growth_sections("word1 www.domain.org word2. http://test")
        (['word1', 'www.domain.org', 'word2.', 'http://test'], [(0, 5), (6, 20), (21, 27), (28, 39)])

        >>> d._split_growth_sections("http://www.domain.org/?p=1#anchor")
        (['http://www.domain.org/', 'p=1', 'anchor'], [(0, 22), (23, 26), (27, 33)])

        >>> d._split_growth_sections("http://user:pass@www.domain.org")
        (['http://user:pass', 'www.domain.org'], [(0, 16), (17, 31)])
        """
        matches = self._growth_sections_pattern.finditer(text)
        tokens = []
        spans = []
        for m in matches:
            tokens.append(m.group())
            spans.append(m.span())
        return tokens, spans


class DomainNOP(TextDomain):
    """ Do-nothing domain, no focused accessible. """

    def matches(self, **kwargs):
        return True

    def read_context(self, keyboard, accessible):
        return "", "", 0, TextSpan(), False, 0

    def get_auto_separator(self, context):
        """ Get word separator to add after inserting a prediction choice. """
        return ""


class DomainPassword(DomainNOP):
    """ Do-nothing domain for password entries """

    def matches(self, **kwargs):
        return kwargs.get("role") == Atspi.Role.PASSWORD_TEXT

    def can_give_keypress_feedback(self):
        return False


class DomainGenericText(TextDomain):
    """ Default domain for generic text entry """

    def matches(self, **kwargs):
        return TextDomain.matches(self, **kwargs)

    def read_context(self, keyboard, accessible):
        """ Extract prediction context from the accessible """

        # get caret position from selection
        selection = accessible.get_selection()

        # get text around the caret position
        try:
            count = accessible.get_character_count()

            if selection is None:
                offset = accessible.get_caret_offset()

                # In Zesty, firefox 50.1 often returns caret position -1
                # when typing into the urlbar. Assume we are at the end
                # of the text when that happens.
                if offset < 0:
                    _logger.warning("DomainGenericText.read_context(): "
                                    "Atspi.Text.get_caret_offset() "
                                    "returned invalid {}. "
                                    "Pretending the cursor is at the end "
                                    "of the text at offset {}."
                                    .format(offset, count))
                    offset = count

                selection = (offset, offset)

            r = accessible.get_text_at_offset(
                selection[0], Atspi.TextBoundaryType.LINE_START)
        except Exception as ex:     # Private exception gi._glib.GError when
                                    # gedit became unresponsive.
            _logger.info("DomainGenericText.read_context(), text: " +
                         unicode_str(ex))
            return None

        line = unicode_str(r.content).replace("\n", "")
        line_caret = max(selection[0] - r.start_offset, 0)

        begin = max(selection[0] - 256, 0)
        end   = min(selection[0] + 100, count)
        try:
            text = accessible.get_text(begin, end)
        except Exception as ex:     # Private exception gi._glib.GError when
                                    # gedit became unresponsive.
            _logger.info("DomainGenericText.read_context(), text2: " +
                         unicode_str(ex))
            return None

        text = unicode_str(text)

        # Not all text may be available for large selections. We only need the
        # part before the begin of the selection/caret.
        selection_span = TextSpan(selection[0], selection[1] - selection[0],
                                  text, begin)
        context = text[:selection[0] - begin]
        begin_of_text = begin == 0
        begin_of_text_offset = 0

        return (context, line, line_caret, selection_span,
                begin_of_text, begin_of_text_offset)

    def can_spell_check(self, section_span):
        """
        Can we auto-correct this span?.

        Doctests:
        >>> d = DomainGenericText()
        >>> d.can_spell_check(TextSpan(0, 3, "abc"))
        True
        >>> d.can_spell_check(TextSpan(4, 3, "abc def"))
        True
        >>> d.can_spell_check(TextSpan(0, 20, "http://www.domain.org"))
        False
        """
        section = section_span.get_span_text()
        return not self._url_parser.is_maybe_url(section) and \
               not self._url_parser._is_maybe_filename(section)
        return True

    def can_auto_correct(self, section_span):
        """
        Can we auto-correct this span?.
        """
        return self.can_spell_check(section_span)

    def can_auto_punctuate(self, has_begin_of_text):
        return True

    def get_text_begin_marker(self):
        return "<bot:txt>"


class DomainTerminal(TextDomain):
    """ Terminal entry, in particular gnome-terminal """

    _prompt_patterns = tuple(re.compile(p, re.UNICODE) for p in
                                (
                                    "^gdb$ ",
                                    "^>>> ",              # python
                                    "^In \[[0-9]*\]: ",   # ipython
                                    "^:",                 # vi command mode
                                    "^/",                 # vi search
                                    "^\?",                # vi reverse search
                                    "\$ ",                # generic prompt
                                    "# ",                 # root prompt
                                    "^.*?@.*?/.*?> "      # fish
                                )
                            )

    _prompt_blacklist_patterns = tuple(re.compile(p, re.UNICODE) for p in
                                (
                                    "^\(.*\)`.*': ",  # bash incremental search
                                )
                            )

    def matches(self, **kwargs):
        return TextDomain.matches(self, **kwargs) and \
               kwargs.get("role") == Atspi.Role.TERMINAL

    def init_domain(self):
        pass

    def read_context(self, keyboard, accessible):
        """
        Extract prediction context from the accessible
        """
        try:
            offset = accessible.get_caret_offset()
        except Exception as ex:     # Private exception gi._glib.GError
                                    # when gedit became unresponsive.
            _logger.info("DomainTerminal.read_context(): " +
                         unicode_str(ex))
            return None

        context_lines, prompt_length, line, line_start, line_caret = \
            self._get_text_after_prompt(
                accessible, offset,
                keyboard.get_last_typed_was_separator())

        if prompt_length:
            begin_of_text = True
            begin_of_text_offset = line_start
        else:
            begin_of_text = False
            begin_of_text_offset = None

        context = "".join(context_lines)
        before_line = "".join(context_lines[:-1])
        selection_span = TextSpan(offset, 0,
                                  before_line + line,
                                  line_start - len(before_line))

        result = (context, line, line_caret, selection_span,
                  begin_of_text, begin_of_text_offset)
        return result

    def _get_text_after_prompt(self, accessible, caret_offset,
                               last_typed_was_separator=None):
        """
        Return text from the input area of the terminal after the prompt.

        Doctests:
        >>> class AtspiTextRangeMockup:
        ...     pass
        >>> class AccessibleMockup:
        ...     def __init__(self, text, width):
        ...         self._text = text
        ...         self._width = width
        ...     def get_text_at_offset(self, offset, boundary):
        ...         line = offset // self._width
        ...         lbegin = line * self._width
        ...         r = AtspiTextRangeMockup()
        ...         r.content = self._text[lbegin:lbegin+self._width]
        ...         r.start_offset = lbegin
        ...         return r
        ...     def get_text_before_offset(self, offset, boundary):
        ...         return self.get_text_at_offset(offset - self._width, boundary)
        ...     def is_byobu(self):
        ...         return False

        >>> d = DomainTerminal()

        # Single line
        >>> a = AccessibleMockup("abc$ ls /etc\\n", 15)
        >>> d._get_text_after_prompt(a, 12)
        (['ls /etc'], 5, 'ls /etc\\n', 5, 7)

        # Two lines
        >>> a = AccessibleMockup("abc$ ls /e"
        ...                      "tc\\n", 10)
        >>> d._get_text_after_prompt(a, 12)
        (['ls /e', 'tc'], 5, 'tc\\n', 10, 2)

        # Three lines: prompt not detected
        # More that two lines are not supported. The probability of detecting
        # "prompts" in random scrolling data rises with each additional line.
        >>> a = AccessibleMockup("abc$ ls /e"
        ...                      "tc/X11/xor"
        ...                      "g.conf.d\\n", 10)
        >>> d._get_text_after_prompt(a, 28)
        (['tc/X11/xor', 'g.conf.d'], 0, 'g.conf.d\\n', 20, 8)

        # Two lines with slash at the beginning of the second: detect vi
        # search prompt. Not ideal, but vi is important too.
        >>> a = AccessibleMockup("abc$ ls /etc"
        ...                      "/X11\\n", 12)
        >>> d._get_text_after_prompt(a, 16)
        (['X11'], 1, 'X11\\n', 13, 3)

        """

        r = accessible.get_text_at_offset(
            caret_offset, Atspi.TextBoundaryType.LINE_START)
        line = unicode_str(r.content)
        line_start = r.start_offset
        line_caret = caret_offset - line_start
        # remove prompt from the current or previous lines
        context_lines = []
        prompt_length = None
        l = line[:line_caret]

        # Zesty: byobu running in gnome-terminal doesn't report trailing
        # spaces in text and caret-position.
        # Awful hack: assume there is always a trailing space when the caret
        # is at the end of the line and we just typed a separator.
        if line[line_caret:] == "\n" and \
           last_typed_was_separator and \
           accessible.is_byobu():
            l += " "

        for i in range(2):

            # matching blacklisted prompt? -> cancel whole context
            if self._find_blacklisted_prompt(l):
                context_lines = []
                prompt_length = None
                break

            prompt_length = self._find_prompt(l)
            context_lines.insert(0, l[prompt_length:])
            if i == 0:
                line = line[prompt_length:]  # cut prompt from input line
                line_start += prompt_length
                line_caret -= prompt_length
            if prompt_length:
                break

            # no prompt yet -> let context reach
            # across one more line break
            r = accessible.get_text_before_offset(
                caret_offset, Atspi.TextBoundaryType.LINE_START)
            l = unicode_str(r.content)

        result = (context_lines, prompt_length,
                  line, line_start, line_caret)
        return result

    def _find_prompt(self, context):
        """
        Search for a prompt and return the offset where the user input starts.
        Until we find a better way just look for some common prompt patterns.
        """
        for pattern in self._prompt_patterns:
            match = pattern.search(context)
            if match:
                return match.end()
        return 0

    def _find_blacklisted_prompt(self, context):
        for pattern in self._prompt_blacklist_patterns:
            match = pattern.search(context)
            if match:
                return match.end()
        return None

    def get_text_begin_marker(self):
        return "<bot:term>"

    def can_record_insertion(self, accessible, offset, length):
        # Only record (for learning) when there is a known prompt in sight.
        # Problem: learning won't happen for uncommon prompts, but less random
        # junk scrolling by should enter the user model in return.
        context_lines, prompt_length, line, line_start, line_caret = \
            self._get_text_after_prompt(accessible, offset)
        return bool(prompt_length)

    def can_suggest_before_typing(self):
        """ Can give word suggestions before typing has started? """
        # Mostly prevent updates to word suggestions while text is scrolling by
        return False

    def handle_key_press(self, keycode, mod_mask):
        """
        End recording and learn when pressing [Return]
        because text that is scrolled out of view is
        lost in a terminal.
        """
        if keycode == KeyCode.Return or \
           keycode == KeyCode.KP_Enter:
            return False, True
        elif keycode == KeyCode.C and mod_mask & Modifiers.CTRL:
            return False, False

        return True, None  # entering_text, end_of_editing

    def can_auto_punctuate(self, has_begin_of_text):
        """
        Only auto-punctuate in Terminal when no prompt was detected.
        Intention is to allow punctuation assistance in editors, but disable
        it when entering commands at the prompt, e.g. for "cd ..".
        """
        return not has_begin_of_text


class DomainURL(DomainGenericText):
    """ (Firefox) address bar """

    def matches(self, **kwargs):
        return kwargs.get("is_urlbar", False)

    def get_auto_separator(self, context):
        """
        Get word separator to add after inserting a prediction choice.
        """
        return self._url_parser.get_auto_separator(context)

    def get_text_begin_marker(self):
        return "<bot:url>"

    def can_spell_check(self, section_span):
        return False


class PartialURLParser:
    """
    Parse partial URLs and predict separators.
    Parsing is neither complete nor RFC prove but probably doesn't
    have to be either. The goal is to save key strokes for the
    most common cases.

    Doctests:
    >>> p = PartialURLParser()

    >>> p.tokenize_url('http://user:pass@www.do-mai_n.nl/path/name.ext')
    ['http', '://', 'user', ':', 'pass', '@', 'www', '.', 'do-mai_n', '.', 'nl', '/', 'path', '/', 'name', '.', 'ext']

    >>> p.tokenize_url('user:pass@www.do-mai_n.nl/path/name.ext')
    ['user', ':', 'pass', '@', 'www', '.', 'do-mai_n', '.', 'nl', '/', 'path', '/', 'name', '.', 'ext']

    >>> p.tokenize_url('www.do-mai_n.nl/path/name.ext')
    ['www', '.', 'do-mai_n', '.', 'nl', '/', 'path', '/', 'name', '.', 'ext']

    >>> p.tokenize_url('www.do-mai_n.nl')
    ['www', '.', 'do-mai_n', '.', 'nl']
    """
    _gTLDs   = ["aero", "asia", "biz", "cat", "com", "coop", "info", "int",
               "jobs", "mobi", "museum", "name", "net", "org", "pro", "tel",
               "travel", "xxx"]
    _usTLDs = ["edu", "gov", "mil"]
    _ccTLDs = ["ac", "ad", "ae", "af", "ag", "ai", "al", "am", "an", "ao",
               "aq", "ar", "as", "at", "au", "aw", "ax", "az", "ba", "bb",
               "bd", "be", "bf", "bg", "bh", "bi", "bj", "bm", "bn", "bo",
               "br", "bs", "bt", "bv", "bw", "by", "bz", "ca", "cc", "cd",
               "cf", "cg", "ch", "ci", "ck", "cl", "cm", "cn", "co", "cr",
               "cs", "cu", "cv", "cx", "cy", "cz", "dd", "de", "dj", "dk",
               "dm", "do", "dz", "ec", "ee", "eg", "eh", "er", "es", "et",
               "eu", "fi", "fj", "fk", "fm", "fo", "fr", "ga", "gb", "gd",
               "ge", "gf", "gg", "gh", "gi", "gl", "gm", "gn", "gp", "gq",
               "gr", "gs", "gt", "gu", "gw", "gy", "hk", "hm", "hn", "hr",
               "ht", "hu", "id", "ie", "il", "im", "in", "io", "iq", "ir",
               "is", "it", "je", "jm", "jo", "jp", "ke", "kg", "kh", "ki",
               "km", "kn", "kp", "kr", "kw", "ky", "kz", "la", "lb", "lc",
               "li", "lk", "lr", "ls", "lt", "lu", "lv", "ly", "ma", "mc",
               "md", "me", "mg", "mh", "mk", "ml", "mm", "mn", "mo", "mp",
               "mq", "mr", "ms", "mt", "mu", "mv", "mw", "mx", "my", "mz",
               "na", "nc", "ne", "nf", "ng", "ni", "nl", "no", "np", "nr",
               "nu", "nz", "om", "pa", "pe", "pf", "pg", "ph", "pk", "pl",
               "pm", "pn", "pr", "ps", "pt", "pw", "py", "qa", "re", "ro",
               "rs", "ru", "rw", "sa", "sb", "sc", "sd", "se", "sg", "sh",
               "si", "sj", "sk", "sl", "sm", "sn", "so", "sr", "ss", "st",
               "su", "sv", "sy", "sz", "tc", "td", "tf", "tg", "th", "tj",
               "tk", "tl", "tm", "tn", "to", "tp", "tr", "tt", "tv", "tw",
               "tz", "ua", "ug", "uk", "us", "uy", "uz", "va", "vc", "ve",
               "vg", "vi", "vn", "vu", "wf", "ws", "ye", "yt", "yu", "za",
               "zm", "zw"]
    _TLDs = frozenset(_gTLDs + _usTLDs + _ccTLDs)

    _schemes = ["http", "https", "ftp", "file"]
    _protocols = ["mailto", "apt"]
    _all_schemes = _schemes + _protocols

    _url_pattern = re.compile("([\w-]+)|(\W+)", re.UNICODE)

    def iter_url(self, url):
        return self._url_pattern.finditer(url)

    def tokenize_url(self, url):
        return[group for match in self.iter_url(url)
                     for group in match.groups() if not group is None]

    def is_maybe_url(self, context):
        """
        Is this maybe something looking like an URL?

        Doctests:
        >>> p = PartialURLParser()
        >>> p.is_maybe_url("http")
        False
        >>> p.is_maybe_url("http:")
        True
        >>> p.is_maybe_url("http://www.domain.org")
        True
        >>> p.is_maybe_url("www.domain.org")
        True
        >>> p.is_maybe_url("www.domain")
        False
        >>> p.is_maybe_url("www")
        False
        """
        tokens = self.tokenize_url(context)

        # with scheme
        if len(tokens) >= 2:
            token  = tokens[0]
            septok = tokens[1]
            if token in self._all_schemes and septok.startswith(":"):
                return True

        # without scheme
        if len(tokens) >= 5:
            if tokens[1] == "." and tokens[3] == ".":
                try:
                    index = tokens.index("/")
                except ValueError:
                    index = 0

                if index >= 4:
                    hostname = tokens[:index]
                else:
                    hostname = tokens

                if hostname[-1] in self._TLDs:
                    return True

        return False


    def _is_maybe_filename(self, string):
            return  "/" in string

    def get_auto_separator(self, context):
        """
        Get word separator to add after inserting a prediction choice.

        Doctests:
        >>> p = PartialURLParser()
        >>> p.get_auto_separator("http")
        '://'
        >>> p.get_auto_separator("www")
        '.'
        >>> p.get_auto_separator("domain.org")
        '/'
        >>> p.get_auto_separator("www.domain.org")
        '/'
        >>> p.get_auto_separator("http://www.domain")
        '.'
        >>> p.get_auto_separator("http://www.domain.org")
        '/'
        >>> p.get_auto_separator("http://www.domain.co") # ambiguous co/ or co.uk/
        '/'
        >>> p.get_auto_separator("http://www.domain.co.uk")
        '/'
        >>> p.get_auto_separator("http://www.domain.co.uk/home")
        '/'
        >>> p.get_auto_separator("http://www.domain.co/home")
        '/'
        >>> p.get_auto_separator("http://www.domain.org/home")
        '/'
        >>> p.get_auto_separator("http://www.domain.org/home/index.html")
        ''
        >>> p.get_auto_separator("mailto")
        ':'

        # local files
        >>> import tempfile
        >>> from os.path import abspath, dirname, join
        >>> def touch(fn):
        ...     with open(fn, mode="w") as f: n = f.write("")
        >>> td = tempfile.TemporaryDirectory(prefix="test onboard _")
        >>> dir = td.name

        >>> touch(join(dir, "onboard-defaults.conf.example"))
        >>> touch(join(dir, "onboard-defaults.conf.example.another"))
        >>>
        >>> import glob
        >>> #glob.glob(dir+"/**")
        >>> p.get_auto_separator("file")
        ':///'
        >>> p.get_auto_separator("file:///home")
        '/'
        >>> p.get_auto_separator("file://"+join(dir, "onboard-defaults"))
        '.'
        >>> p.get_auto_separator("file://"+join(dir, "onboard-defaults.conf"))
        '.'
        >>> p.get_auto_separator("file://"+join(dir, "onboard-defaults.conf.example"))
        ''
        >>> p.get_auto_separator("file://"+join(dir, "onboard-defaults.conf.example.another"))
        ' '

        # Non-existing filename: we don't know, don't guess a separator
        >>> p.get_auto_separator("file:///tmp/onboard1234")
        ''

        # Non-existing filename: if basename has an extension assume we're done
        >>> p.get_auto_separator("file:///tmp/onboard1234.txt")
        ' '

        # Relative filename: we don't know current dir, return empty separator
        >>> p.get_auto_separator("file://tmp")
        ''

        """
        separator = None

        SCHEME, PROTOCOL, DOMAIN, PATH = range(4)
        component = SCHEME
        last_septok = ""
        matches = tuple(self.iter_url(context))
        for index, match in enumerate(matches):
            groups = match.groups()
            token  = groups[0]
            septok = groups[1]

            if septok:
                last_septok = septok
            if index < len(matches)-1:
                next_septok = matches[index+1].groups()[1]
            else:
                next_septok = ""

            if component == SCHEME:
                if token:
                    if token == "file":
                        separator = ":///"
                        component = PATH
                        continue
                    if token in self._schemes:
                        separator = "://"
                        component = DOMAIN
                        continue
                    elif token in self._protocols:
                        separator = ":"
                        component = PROTOCOL
                        continue
                    else:
                        component = DOMAIN

            if component == DOMAIN:
                if token:
                    separator = "."
                    if last_septok == "." and \
                       next_septok != "." and \
                       token in self._TLDs:
                        separator = "/"
                        component = PATH
                        continue

            if component == PATH:
                separator = ""

            if component == PROTOCOL:
                separator = ""

        if component == PATH and not separator:
            file_scheme = "file://"
            if context.startswith(file_scheme):
                filename = context[len(file_scheme):]
                separator = self._get_filename_separator(filename)
            else:
                if not last_septok == ".":
                    separator = "/"

        if separator is None:
             separator = " " # may be entering search terms, keep space as default

        return separator

    def _get_filename_separator(self, filename):
        """
        Get auto separator for a partial filename.
        """
        separator = None

        if os.path.isabs(filename):
            files  = glob.glob(filename + "*")
            files += glob.glob(filename + "/*")  # look inside directories too
            separator = self._get_separator_from_file_list(filename, files)

        if separator is None:
            basename = os.path.basename(filename)
            if "." in basename:
                separator = " "
            else:
                separator = ""

        return separator

    @staticmethod
    def _get_separator_from_file_list(filename, files):
        """
        Extract separator from a list of matching filenames.

        Doctests:
        >>> p = PartialURLParser

        # no matching files: return None, assume new file we can't check
        >>> p._get_separator_from_file_list("/dir/file", [])

        # complete file: we're done, continue with space separator
        >>> p._get_separator_from_file_list("/dir/file.ext", ["/dir/file.ext"])
        ' '

        # multiple files with identical separator: return that separator
        >>> p._get_separator_from_file_list("/dir/file",
        ...                                ["/dir/file.ext1", "/dir/file.ext2"])
        '.'

        # multiple files with different separators: return empty separator
        >>> p._get_separator_from_file_list("/dir/file",
        ...                                ["/dir/file.ext", "/dir/file-ext"])
        ''

        # directory
        >>> p._get_separator_from_file_list("/dir",
        ...                                ["/dir/file.ext1", "/dir/file.ext2"])
        '/'
        >>> p._get_separator_from_file_list("/dir",
        ...                                ["/dir", "/dir/file.ext2"])
        '/'

        # multiple extensions
        >>> files = ["/dir/dir/file.ext1.ext2", "/dir/dir/file.ext1.ext3"]
        >>> p._get_separator_from_file_list("/dir/dir/file", files)
        '.'
        >>> p._get_separator_from_file_list("/dir/dir/file.ext1", files)
        '.'
        >>> p._get_separator_from_file_list("/dir/dir/file.ext1.ext2", files)
        ' '

        # partial path match
        >>> files = ["/dir/dir/file", "/dir/dir/file.ext1",
        ...          "/dir/dir/file.ext2"]
        >>> p._get_separator_from_file_list("/dir/dir/file", files)
        ''
        >>> p._get_separator_from_file_list("/dir/dir/file.ext1", files)
        ' '
        """
        separator = None

        l = len(filename)
        separators = set([f[l:l+1] for f in files \
                         if f.startswith(filename)])

        # directory?
        if len(separators) == 2 and "/" in separators and "" in separators:
            separator = "/"
        # end of filename?
        elif len(separators) == 1 and "" in separators:
            separator = " "
        # unambigous separator?
        elif len(separators) == 1:
            separator = separators.pop()
        # multiple separators
        elif separators:
            separator = ""

        return separator