windows.py 47.2 KB
Newer Older
1
# Copyright 2010 Le Coz Florent <louiz@louiz.org>
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#
# This file is part of Poezio.
#
# Poezio 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, version 3 of the License.
#
# Poezio 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 Poezio.  If not, see <http://www.gnu.org/licenses/>.

17
"""
18 19 20 21
Define all the windows.
A window is a little part of the screen, for example the input window,
the text window, the roster window, etc.
A Tab (see tab.py) is composed of multiple Windows
22 23
"""

24 25
from gettext import (bindtextdomain, textdomain, bind_textdomain_codeset,
                     gettext as _)
26
from os.path import isfile
27

28 29 30
import logging
log = logging.getLogger(__name__)

31 32 33
import locale
locale.setlocale(locale.LC_ALL, '')

34
import shlex
35
import curses
36
from config import config
37

38 39
from threading import Lock

40
from contact import Contact, Resource
41
from roster import RosterGroup, roster
42

43
from message import Line
44
from tabs import MIN_WIDTH, MIN_HEIGHT
45

46 47
from sleekxmpp.xmlstream.stanzabase import JID

48
import theme
49

50 51
g_lock = Lock()

52
class Win(object):
53 54
    def __init__(self):
        pass
55

56
    def _resize(self, height, width, y, x, parent_win):
57
        self.height, self.width, self.x, self.y = height, width, x, y
58 59 60 61
        self._win = curses.newwin(height, width, y, x)

    def _refresh(self):
        self._win.noutrefresh()
62

63 64
    def addnstr(self, *args):
        """
65
        Safe call to addnstr
66 67
        """
        try:
68
            self._win.addnstr(*args)
69 70 71 72 73
        except:
            pass

    def addstr(self, *args):
        """
74
        Safe call to addstr
75
        """
76
        try:
77
            self._win.addstr(*args)
78 79
        except:
            pass
80

81 82 83 84
    def finish_line(self, color):
        """
        Write colored spaces until the end of line
        """
85
        (y, x) = self._win.getyx()
86 87 88
        size = self.width-x
        self.addnstr(' '*size, size, curses.color_pair(color))

89
class UserList(Win):
90 91
    def __init__(self):
        Win.__init__(self)
92 93 94
        self.color_role = {'moderator': theme.COLOR_USER_MODERATOR,
                           'participant':theme.COLOR_USER_PARTICIPANT,
                           'visitor':theme.COLOR_USER_VISITOR,
95 96
                           'none':theme.COLOR_USER_NONE,
                           '':theme.COLOR_USER_NONE
97
                           }
98
        self.color_show = {'xa':theme.COLOR_STATUS_XA,
99 100
                           'none':theme.COLOR_STATUS_NONE,
                           '':theme.COLOR_STATUS_NONE,
101 102 103
                           'dnd':theme.COLOR_STATUS_DND,
                           'away':theme.COLOR_STATUS_AWAY,
                           'chat':theme.COLOR_STATUS_CHAT
104
                           }
105 106

    def refresh(self, users):
107
        with g_lock:
108
            self._win.erase()
109 110 111 112 113 114 115 116 117 118 119
            y = 0
            for user in sorted(users):
                if not user.role in self.color_role:
                    role_col = theme.COLOR_USER_NONE
                else:
                    role_col = self.color_role[user.role]
                if not user.show in self.color_show:
                    show_col = theme.COLOR_STATUS_NONE
                else:
                    show_col = self.color_show[user.show]
                self.addstr(y, 0, theme.CHAR_STATUS, curses.color_pair(show_col))
120
                self.addnstr(y, 1, user.nick, self.width-1, curses.color_pair(role_col))
121 122 123
                y += 1
                if y == self.height:
                    break
124
            self._refresh()
125

126 127
    def resize(self, height, width, y, x, stdscr):
        self._resize(height, width, y, x, stdscr)
128 129 130
        self._win.attron(curses.color_pair(theme.COLOR_VERTICAL_SEPARATOR))
        self._win.vline(0, 0, curses.ACS_VLINE, self.height)
        self._win.attroff(curses.color_pair(theme.COLOR_VERTICAL_SEPARATOR))
131

132
class Topic(Win):
133 134
    def __init__(self):
        Win.__init__(self)
135

136 137
    def resize(self, height, width, y, x, stdscr):
        self._resize(height, width, y, x, stdscr)
138

139
    def refresh(self, topic):
140
        with g_lock:
141
            self._win.erase()
142
            self.addstr(0, 0, topic[:self.width-1], curses.color_pair(theme.COLOR_TOPIC_BAR))
143
            (y, x) = self._win.getyx()
144 145 146 147
            remaining_size = self.width - x
            if remaining_size:
                self.addnstr(' '*remaining_size, remaining_size,
                             curses.color_pair(theme.COLOR_INFORMATION_BAR))
148
            self._refresh()
149

150
class GlobalInfoBar(Win):
151 152
    def __init__(self):
        Win.__init__(self)
153

154 155
    def resize(self, height, width, y, x, stdscr):
        self._resize(height, width, y, x, stdscr)
156

157
    def refresh(self, tabs, current):
158 159 160 161
        def compare_room(a):
            # return a.nb - b.nb
            return a.nb
        comp = lambda x: x.nb
162
        with g_lock:
163
            self._win.erase()
164
            self.addstr(0, 0, "[", curses.color_pair(theme.COLOR_INFORMATION_BAR))
165 166 167 168 169 170 171 172
            sorted_tabs = sorted(tabs, key=comp)
            for tab in sorted_tabs:
                color = tab.get_color_state()
                try:
                    self.addstr("%s" % str(tab.nb), curses.color_pair(color))
                    self.addstr("|", curses.color_pair(theme.COLOR_INFORMATION_BAR))
                except:             # end of line
                    break
173
            (y, x) = self._win.getyx()
174
            self.addstr(y, x-1, '] ', curses.color_pair(theme.COLOR_INFORMATION_BAR))
175
            (y, x) = self._win.getyx()
176 177 178
            remaining_size = self.width - x
            self.addnstr(' '*remaining_size, remaining_size,
                         curses.color_pair(theme.COLOR_INFORMATION_BAR))
179
            self._refresh()
180

181 182 183 184 185
class InfoWin(Win):
    """
    Base class for all the *InfoWin, used in various tabs. For example
    MucInfoWin, etc. Provides some useful methods.
    """
186 187
    def __init__(self):
        Win.__init__(self)
188 189 190 191 192 193 194 195 196

    def print_scroll_position(self, text_buffer):
        """
        Print, link in Weechat, a -PLUS(n)- where n
        is the number of available lines to scroll
        down
        """
        if text_buffer.pos > 0:
            plus = ' -PLUS(%s)-' % text_buffer.pos
197
            self.addstr(plus, curses.color_pair(theme.COLOR_SCROLLABLE_NUMBER) | curses.A_BOLD)
198 199 200 201 202 203

class PrivateInfoWin(InfoWin):
    """
    The live above the information window, displaying informations
    about the MUC user we are talking to
    """
204 205
    def __init__(self):
        InfoWin.__init__(self)
206

207 208
    def resize(self, height, width, y, x, stdscr):
        self._resize(height, width, y, x, stdscr)
209 210

    def refresh(self, room):
211

212
        with g_lock:
213
            self._win.erase()
214 215 216
            self.write_room_name(room)
            self.print_scroll_position(room)
            self.finish_line(theme.COLOR_INFORMATION_BAR)
217
            self._refresh()
218 219

    def write_room_name(self, room):
220 221
        jid = JID(room.name)
        room_name, nick = jid.bare, jid.resource
222
        self.addstr(nick, curses.color_pair(13))
223
        txt = ' from room %s' % room_name
224
        self.addstr(txt, curses.color_pair(theme.COLOR_INFORMATION_BAR))
225

226 227 228
class ConversationInfoWin(InfoWin):
    """
    The line above the information window, displaying informations
229
    about the user we are talking to
230
    """
231 232 233 234 235 236 237 238 239 240
    color_show = {'xa':theme.COLOR_STATUS_XA,
                  'none':theme.COLOR_STATUS_ONLINE,
                  '':theme.COLOR_STATUS_ONLINE,
                  'available':theme.COLOR_STATUS_ONLINE,
                  'dnd':theme.COLOR_STATUS_DND,
                  'away':theme.COLOR_STATUS_AWAY,
                  'chat':theme.COLOR_STATUS_CHAT,
                  'unavailable':theme.COLOR_STATUS_UNAVAILABLE
                  }

241 242
    def __init__(self):
        InfoWin.__init__(self)
243

244 245
    def resize(self, height, width, y, x, stdscr):
        self._resize(height, width, y, x, stdscr)
246

247
    def refresh(self, jid, contact, text_buffer):
248 249 250
        # contact can be None, if we receive a message
        # from someone not in our roster. In this case, we display
        # only the maximum information from the message we can get.
251 252 253 254 255 256 257 258 259 260 261 262 263
        jid = JID(jid)
        if contact:
            if jid.resource:
                resource = contact.get_resource_by_fulljid(jid.full)
            else:
                resource = contact.get_highest_priority_resource()
        else:
            resource = None
        # if contact is None, then resource is None too: user is not in the roster
        # so we don't know almost anything about it
        # If contact is a Contact, then
        # resource can now be a Resource: user is in the roster and online
        # or resource is None: user is in the roster but offline
264
        with g_lock:
265
            self._win.erase()
266 267 268 269 270
            self.write_contact_jid(jid)
            self.write_contact_informations(contact)
            self.write_resource_information(resource)
            self.print_scroll_position(text_buffer)
            self.finish_line(theme.COLOR_INFORMATION_BAR)
271
            self._refresh()
272

273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
    def write_resource_information(self, resource):
        """
        Write the informations about the resource
        """
        if not resource:
            presence = "unavailable"
        else:
            presence = resource.get_presence()
        color = RosterWin.color_show[presence]
        self.addstr('[', curses.color_pair(theme.COLOR_INFORMATION_BAR))
        self.addstr(" ", curses.color_pair(color))
        self.addstr(']', curses.color_pair(theme.COLOR_INFORMATION_BAR))

    def write_contact_informations(self, contact):
        """
        Write the informations about the contact
        """
290
        if not contact:
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
            self.addstr("(contact not in roster)", curses.color_pair(theme.COLOR_INFORMATION_BAR))
            return
        display_name = contact.get_name() or contact.get_bare_jid()
        self.addstr('%s '%(display_name), curses.color_pair(theme.COLOR_INFORMATION_BAR))

    def write_contact_jid(self, jid):
        """
        Just write the jid that we are talking to
        """
        self.addstr('[', curses.color_pair(theme.COLOR_INFORMATION_BAR))
        self.addstr(jid.full, curses.color_pair(10))
        self.addstr('] ', curses.color_pair(theme.COLOR_INFORMATION_BAR))

class ConversationStatusMessageWin(InfoWin):
    """
    The upper bar displaying the status message of the contact
    """
308 309
    def __init__(self):
        InfoWin.__init__(self)
310

311 312
    def resize(self, height, width, y, x, stdscr):
        self._resize(height, width, y, x, stdscr)
313 314 315 316 317 318 319 320

    def refresh(self, jid, contact):
        jid = JID(jid)
        if contact:
            if jid.resource:
                resource = contact.get_resource_by_fulljid(jid.full)
            else:
                resource = contact.get_highest_priority_resource()
321
        else:
322 323 324 325 326 327 328 329 330 331
            resource = None
        with g_lock:
            self._win.erase()
            if resource:
                self.write_status_message(resource)
            self.finish_line(theme.COLOR_INFORMATION_BAR)
            self._refresh()

    def write_status_message(self, resource):
        self.addstr(resource.get_status(), curses.color_pair(theme.COLOR_INFORMATION_BAR))
332

333 334 335 336 337
class MucInfoWin(InfoWin):
    """
    The line just above the information window, displaying informations
    about the MUC we are viewing
    """
338 339
    def __init__(self):
        InfoWin.__init__(self)
340

341 342
    def resize(self, height, width, y, x, stdscr):
        self._resize(height, width, y, x, stdscr)
343 344

    def refresh(self, room):
345
        with g_lock:
346
            self._win.erase()
347 348 349 350 351 352
            self.write_room_name(room)
            self.write_own_nick(room)
            self.write_disconnected(room)
            self.write_role(room)
            self.print_scroll_position(room)
            self.finish_line(theme.COLOR_INFORMATION_BAR)
353
            self._refresh()
354 355 356 357

    def write_room_name(self, room):
        """
        """
358
        self.addstr('[', curses.color_pair(theme.COLOR_INFORMATION_BAR))
359
        self.addnstr(room.name, len(room.name), curses.color_pair(13))
360
        self.addstr('] ', curses.color_pair(theme.COLOR_INFORMATION_BAR))
361 362 363 364 365 366

    def write_disconnected(self, room):
        """
        Shows a message if the room is not joined
        """
        if not room.joined:
367 368
            self.addstr(' -!- Not connected ', curses.color_pair(theme.COLOR_INFORMATION_BAR))

369 370 371 372 373 374 375 376 377
    def write_own_nick(self, room):
        """
        Write our own nick in the info bar
        """
        nick = room.own_nick
        if not nick:
            return
        if len(nick) > 13:
            nick = nick[:13]+'…'
378
        self.addstr(nick, curses.color_pair(theme.COLOR_INFORMATION_BAR))
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394

    def write_role(self, room):
        """
        Write our own role and affiliation
        """
        own_user = None
        for user in room.users:
            if user.nick == room.own_nick:
                own_user = user
                break
        if not own_user:
            return
        txt = ' ('
        if own_user.affiliation != 'none':
            txt += own_user.affiliation+', '
        txt += own_user.role+')'
395
        self.addstr(txt, curses.color_pair(theme.COLOR_INFORMATION_BAR))
396

397
class TextWin(Win):
398 399
    def __init__(self):
        Win.__init__(self)
400

401
    def build_lines_from_messages(self, messages):
402
        """
403 404
        From all the existing messages in the window, create the that will
        be displayed on the screen
405
        """
406 407
        lines = []
        for message in messages:
408 409 410
            if message == None:  # line separator
                lines.append(None)
                continue
411
            txt = message.txt
412 413
            if not txt:
                continue
414 415
            # length of the time
            offset = 9+len(theme.CHAR_TIME_LEFT[:1])+len(theme.CHAR_TIME_RIGHT[:1])
416
            if message.nickname and len(message.nickname) >= 30:
417
                nick = message.nickname[:30]+'…'
418 419 420 421
            else:
                nick = message.nickname
            if nick:
                offset += len(nick) + 2 # + nick + spaces length
422
            first = True
423
            this_line_was_broken_by_space = False
424 425 426 427
            while txt != '':
                if txt[:self.width-offset].find('\n') != -1:
                    limit = txt[:self.width-offset].find('\n')
                else:
428
                    # break between words if possible
429 430
                    if len(txt) >= self.width-offset:
                        limit = txt[:self.width-offset].rfind(' ')
431 432
                        this_line_was_broken_by_space = True
                        if limit <= 0:
433
                            limit = self.width-offset
434 435 436 437
                            this_line_was_broken_by_space = False
                    else:
                        limit = self.width-offset-1
                        this_line_was_broken_by_space = False
438
                color = message.user.color if message.user else None
439 440
                if not first:
                    nick = None
441 442 443
                    time = None
                else:
                    time = message.time
444
                l = Line(nick, color,
445
                         time,
446
                         txt[:limit], message.color,
447 448
                         offset,
                         message.colorized)
449
                lines.append(l)
450 451 452 453
                if this_line_was_broken_by_space:
                    txt = txt[limit+1:] # jump the space at the start of the line
                else:
                    txt = txt[limit:]
454 455
                if txt.startswith('\n'):
                    txt = txt[1:]
456
                first = False
457
        return lines
458

459
    def refresh(self, room):
460
        """
461 462
        Build the Line objects from the messages, and then write
        them in the text area
463
        """
464 465
        if self.height <= 0:
            return
466
        with g_lock:
467
            self._win.erase()
468 469 470 471 472 473 474 475 476 477 478
            lines = self.build_lines_from_messages(room.messages)
            if room.pos + self.height > len(lines):
                room.pos = len(lines) - self.height
                if room.pos < 0:
                    room.pos = 0
            if room.pos != 0:
                lines = lines[-self.height-room.pos:-room.pos]
            else:
                lines = lines[-self.height:]
            y = 0
            for line in lines:
479
                self._win.move(y, 0)
480 481 482 483 484 485 486 487 488
                if line == None:
                    self.write_line_separator()
                    y += 1
                    continue
                if line.time is not None:
                    self.write_time(line.time)
                if line.nickname is not None:
                    self.write_nickname(line.nickname, line.nickname_color)
                self.write_text(y, line.text_offset, line.text, line.text_color, line.colorized)
489
                y += 1
490
            self._refresh()
491

492 493 494
    def write_line_separator(self):
        """
        """
495
        self._win.attron(curses.color_pair(theme.COLOR_NEW_TEXT_SEPARATOR))
496
        self.addnstr('- '*(self.width//2), self.width)
497
        self._win.attroff(curses.color_pair(theme.COLOR_NEW_TEXT_SEPARATOR))
498

499
    def write_text(self, y, x, txt, color, colorized):
500
        """
501
        write the text of a line.
502
        """
503
        txt = txt
504 505
        if not colorized:
            if color:
506
                self._win.attron(curses.color_pair(color))
507
            self.addstr(y, x, txt)
508
            if color:
509
                self._win.attroff(curses.color_pair(color))
510 511 512 513 514 515 516

        else:                   # Special messages like join or quit
            special_words = {
                theme.CHAR_JOIN: theme.COLOR_JOIN_CHAR,
                theme.CHAR_QUIT: theme.COLOR_QUIT_CHAR,
                theme.CHAR_KICK: theme.COLOR_KICK_CHAR,
                }
517 518 519
            try:
                splitted = shlex.split(txt)
            except ValueError:
520 521 522 523 524
                # FIXME colors are disabled on too long words
                txt = txt.replace('"[', '').replace(']"', '')\
                    .replace('"{', '').replace('}"', '')\
                    .replace('"(', '').replace(')"', '')
                splitted = txt.split()
525
            for word in splitted:
526
                if word in list(special_words.keys()):
527
                    self.addstr(word, curses.color_pair(special_words[word]))
528
                elif word.startswith('(') and word.endswith(')'):
529 530 531
                    self.addstr('(', curses.color_pair(color))
                    self.addstr(word[1:-1], curses.color_pair(theme.COLOR_CURLYBRACKETED_WORD))
                    self.addstr(')', curses.color_pair(color))
532
                elif word.startswith('{') and word.endswith('}'):
533
                    self.addstr(word[1:-1], curses.color_pair(theme.COLOR_ACCOLADE_WORD))
534
                elif word.startswith('[') and word.endswith(']'):
535
                    self.addstr(word[1:-1], curses.color_pair(theme.COLOR_BRACKETED_WORD))
536
                else:
537
                    self.addstr(word, curses.color_pair(color))
538
                self._win.addch(' ')
539

540
    def write_nickname(self, nickname, color):
541 542 543 544
        """
        Write the nickname, using the user's color
        and return the number of written characters
        """
545
        if color:
546
            self._win.attron(curses.color_pair(color))
547
        self.addstr(nickname)
548
        if color:
549
            self._win.attroff(curses.color_pair(color))
550
        self.addstr("> ")
551

552
    def write_time(self, time):
553 554 555
        """
        Write the date on the yth line of the window
        """
556 557 558 559 560 561 562
        self.addstr(theme.CHAR_TIME_LEFT, curses.color_pair(theme.COLOR_TIME_LIMITER))
        self.addstr(time.strftime("%H"), curses.color_pair(theme.COLOR_TIME_NUMBERS))
        self.addstr(':', curses.color_pair(theme.COLOR_TIME_SEPARATOR))
        self.addstr(time.strftime("%M"), curses.color_pair(theme.COLOR_TIME_NUMBERS))
        self.addstr(':', curses.color_pair(theme.COLOR_TIME_SEPARATOR))
        self.addstr(time.strftime('%S'), curses.color_pair(theme.COLOR_TIME_NUMBERS))
        self.addnstr(theme.CHAR_TIME_RIGHT, curses.color_pair(theme.COLOR_TIME_LIMITER))
563
        self.addstr(' ')
564

565 566
    def resize(self, height, width, y, x, stdscr):
        self._resize(height, width, y, x, stdscr)
567

568 569
class HelpText(Win):
    """
570
    A Window just displaying a read-only message.
571 572 573
    Usually used to replace an Input when the tab is in
    command mode.
    """
574 575
    def __init__(self, text=''):
        Win.__init__(self)
576 577
        self.txt = text

578 579
    def resize(self, height, width, y, x, stdscr):
        self._resize(height, width, y, x, stdscr)
580 581 582 583 584 585 586 587 588 589 590

    def refresh(self):
        with g_lock:
            self._win.erase()
            self.addstr(0, 0, self.txt[:self.width-1], curses.color_pair(theme.COLOR_INFORMATION_BAR))
            self.finish_line(theme.COLOR_INFORMATION_BAR)
            self._refresh()

    def do_command(self, key):
        return False

591 592
class Input(Win):
    """
593 594 595 596 597 598 599 600 601
    The simplest Input possible, provides just a way to edit a single line
    of text. It also has a clipboard, common to all Inputs.
    Doesn't have any history.
    It doesn't do anything when enter is pressed either.
    This should be herited for all kinds of Inputs, for example MessageInput
    or the little inputs in dataforms, etc, adding specific features (completion etc)
    It features two kinds of completion, but they have to be called from outside (the Tab),
    passing the list of items that can be used to complete. The completion can be used
    in a very flexible way.
602
    """
603 604
    clipboard = '' # A common clipboard for all the inputs, this makes
    # it easy cut and paste text between various input
605
    def __init__(self):
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
        self.key_func = {
            "KEY_LEFT": self.key_left,
            "M-D": self.key_left,
            "KEY_RIGHT": self.key_right,
            "M-C": self.key_right,
            "KEY_END": self.key_end,
            "KEY_HOME": self.key_home,
            "KEY_DC": self.key_dc,
            '^D': self.key_dc,
            'M-b': self.jump_word_left,
            '^W': self.delete_word,
            '^K': self.delete_end_of_line,
            '^U': self.delete_begining_of_line,
            '^Y': self.paste_clipboard,
            '^A': self.key_home,
            '^E': self.key_end,
            'M-f': self.jump_word_right,
            "KEY_BACKSPACE": self.key_backspace,
            '^?': self.key_backspace,
            }

627
        Win.__init__(self)
628
        self.text = ''
629 630
        self.pos = 0            # cursor position
        self.line_pos = 0 # position (in self.text) of
631

632 633 634
    def is_empty(self):
        return len(self.text) == 0

635 636 637
    def resize(self, height, width, y, x, stdscr):

        self._resize(height, width, y, x, stdscr)
638
        self._win.erase()
639
        self.addnstr(0, 0, self.text, self.width-1)
640

641 642 643 644 645 646 647 648 649 650
    def jump_word_left(self):
        """
        Move the cursor one word to the left
        """
        if not len(self.text) or self.pos == 0:
            return
        previous_space = self.text[:self.pos+self.line_pos].rfind(' ')
        if previous_space == -1:
            previous_space = 0
        diff = self.pos+self.line_pos-previous_space
651
        for i in range(diff):
652
            self.key_left()
653
        return True
654 655 656 657 658 659 660 661 662 663 664

    def jump_word_right(self):
        """
        Move the cursor one word to the right
        """
        if len(self.text) == self.pos+self.line_pos or not len(self.text):
            return
        next_space = self.text.find(' ', self.pos+self.line_pos+1)
        if next_space == -1:
            next_space = len(self.text)
        diff = next_space - (self.pos+self.line_pos)
665
        for i in range(diff):
666
            self.key_right()
667
        return True
668 669 670 671 672 673 674 675 676 677 678

    def delete_word(self):
        """
        Delete the word just before the cursor
        """
        if not len(self.text) or self.pos == 0:
            return
        previous_space = self.text[:self.pos+self.line_pos].rfind(' ')
        if previous_space == -1:
            previous_space = 0
        diff = self.pos+self.line_pos-previous_space
679
        for i in range(diff):
680 681
            self.key_backspace(False)
        self.rewrite_text()
682
        return True
683 684 685 686 687 688 689

    def delete_end_of_line(self):
        """
        Cut the text from cursor to the end of line
        """
        if len(self.text) == self.pos+self.line_pos:
            return              # nothing to cut
690
        Input.clipboard = self.text[self.pos+self.line_pos:]
691 692
        self.text = self.text[:self.pos+self.line_pos]
        self.key_end()
693
        return True
694 695 696 697 698 699 700

    def delete_begining_of_line(self):
        """
        Cut the text from cursor to the begining of line
        """
        if self.pos+self.line_pos == 0:
            return
701
        Input.clipboard = self.text[:self.pos+self.line_pos]
702 703
        self.text = self.text[self.pos+self.line_pos:]
        self.key_home()
704
        return True
705 706 707 708 709

    def paste_clipboard(self):
        """
        Insert what is in the clipboard at the cursor position
        """
710
        if not Input.clipboard or len(Input.clipboard) == 0:
711
            return
712
        for letter in Input.clipboard:
713
            self.do_command(letter)
714
        return True
715

716
    def key_dc(self):
717 718 719
        """
        delete char just after the cursor
        """
720
        self.reset_completion()
721 722 723 724
        if self.pos + self.line_pos == len(self.text):
            return              # end of line, nothing to delete
        self.text = self.text[:self.pos+self.line_pos]+self.text[self.pos+self.line_pos+1:]
        self.rewrite_text()
725
        return True
726 727

    def key_home(self):
728 729 730
        """
        Go to the begining of line
        """
731
        self.reset_completion()
732
        self.pos = 0
733 734
        self.line_pos = 0
        self.rewrite_text()
735
        return True
736

737 738 739 740 741 742
    def key_end(self, reset=False):
        """
        Go to the end of line
        """
        if reset:
            self.reset_completion()
743
        if len(self.text) >= self.width-1:
744 745
            self.pos = self.width-1
            self.line_pos = len(self.text)-self.pos
746
        else:
747 748 749
            self.pos = len(self.text)
            self.line_pos = 0
        self.rewrite_text()
750
        return True
751 752

    def key_left(self):
753 754 755
        """
        Move the cursor one char to the left
        """
756
        self.reset_completion()
757
        (y, x) = self._win.getyx()
758 759 760
        if self.pos == self.width-1 and self.line_pos > 0:
            self.line_pos -= 1
        elif self.pos >= 1:
761
            self.pos -= 1
762
        self.rewrite_text()
763
        return True
764 765

    def key_right(self):
766 767 768
        """
        Move the cursor one char to the right
        """
769
        self.reset_completion()
770
        (y, x) = self._win.getyx()
771 772 773 774
        if self.pos == self.width-1:
            if self.line_pos + self.width-1 < len(self.text):
                self.line_pos += 1
        elif self.pos < len(self.text):
775
            self.pos += 1
776
        self.rewrite_text()
777
        return True
778

779
    def key_backspace(self, reset=True):
780 781 782
        """
        Delete the char just before the cursor
        """
783
        self.reset_completion()
784
        (y, x) = self._win.getyx()
785 786 787 788
        if self.pos == 0:
            return
        self.text = self.text[:self.pos+self.line_pos-1]+self.text[self.pos+self.line_pos:]
        self.key_left()
789 790
        if reset:
            self.rewrite_text()
791
        return True
792

793
    def auto_completion(self, word_list, add_after):
794
        """
795 796 797 798
        Complete the input, from a list of words
        if add_after is None, we use the value defined in completion
        plus a space, after the completion. If it's a string, we use it after the
        completion (with no additional space)
799
        """
800
        if self.pos+self.line_pos != len(self.text): # or len(self.text) == 0
801
            return # we don't complete if cursor is not at the end of line
802
        completion_type = config.get('completion', 'normal')
803
        if completion_type == 'shell' and self.text != '':
804
            self.shell_completion(word_list, add_after)
805
        else:
806
            self.normal_completion(word_list, add_after)
807
        return True
808 809

    def reset_completion(self):
810 811 812
        """
        Reset the completion list (called on ALL keys except tab)
        """
813
        self.hit_list = []
814
        self.last_completion = None
815

816
    def normal_completion(self, word_list, after):
817 818 819
        """
        Normal completion
        """
820
        (y, x) = self._win.getyx()
821
        if not self.last_completion:
822 823
            # begin is the begining of the word we want to complete
            if self.text.strip() and not self.text.endswith(' '):
824
                begin = self.text.split()[-1].lower()
825 826
            else:
                begin = ''
827
            log.debug('BEGIN: [%s]\n' % begin)
828
            hit_list = []       # list of matching nicks
829 830 831
            for word in word_list:
                if word.lower().startswith(begin):
                    hit_list.append(word)
832 833 834
            if len(hit_list) == 0:
                return
            self.hit_list = hit_list
835
            end = len(begin)
836
        else:
837 838 839 840
            if after:
                begin = self.text[-len(after)-len(self.last_completion):-len(after)]
            else:
                begin = self.last_completion
841
            self.hit_list.append(self.hit_list.pop(0)) # rotate list