From af629add58e0148eae11c77da712a8240b22fe49 Mon Sep 17 00:00:00 2001
From: Eirik Byrkjeflot Anonsen <eirik@eirikba.org>
Date: Sat, 24 Mar 2012 16:28:06 +0100
Subject: [PATCH] Make sure Screen.add_line.get_line_chunks() does not discard beginning of line.

The old version would discard everything before the first '{!'.

Also, this version is less magic and all over easier to understand.
---
 deluge/ui/console/screen.py |   42 +++++++++++++++++++++++-------------------
 1 files changed, 23 insertions(+), 19 deletions(-)

diff --git a/deluge/ui/console/screen.py b/deluge/ui/console/screen.py
index 1a05c45..26327f6 100644
--- a/deluge/ui/console/screen.py
+++ b/deluge/ui/console/screen.py
@@ -163,28 +163,32 @@ def add_line(self, text, refresh=True):
         def get_line_chunks(line):
             """
             Returns a list of 2-tuples (color string, text)
+            First tuple may have empty color string.
 
             """
+            if not line:
+                return []
             chunks = []
-            num_chunks = line.count("{!")
-            for i in range(num_chunks):
-                # Find the beginning and end of the color tag
-                beg = line.find("{!")
-                end = line.find("!}") + 2
-                color = line[beg:end]
-                line = line[end:]
-
-                # Check to see if this is the last chunk
-                if i + 1 == num_chunks:
-                    text = line
-                else:
-                    # Not the last chunk so get the text up to the next tag
-                    # and remove the text from line
-                    text = line[:line.find("{!")]
-                    line = line[line.find("{!"):]
-
-                chunks.append((color, text))
-
+            if not line.startswith('{!'):
+                begin = line.find('{!')
+                if begin < 0:
+                    begin = len(line)
+                chunks.append( ('', line[:begin]) )
+                line = line[begin:]
+            while line:
+                # We know the line starts with '{!' here
+                end_color = line.find('!}')
+                if end_color < 0:
+                    # Could raise an exception here, but it may be better to
+                    # pass along what we've got to the real parser and see
+                    # what happens.
+                    chunks.append( (line, '') )
+                    return chunks
+                next_color = line.find('{!', end_color)
+                if next_color < 0:
+                    next_color = len(line)
+                chunks.append( (line[:end_color+2], line[end_color+2:next_color]) )
+                line = line[next_color:]
             return chunks
 
         for line in text.splitlines():
-- 
1.7.2.5

