From af4d4151d3af49e6f6724dccbfd6c25a52082eec Mon Sep 17 00:00:00 2001
From: Edward Betts <edward@4angle.com>
Date: Wed, 22 Feb 2017 11:04:06 +0000
Subject: [PATCH] protect spaces at the start of a line

---
 sourcing/templates/view.html |  7 ++++---
 sourcing/view.py             | 10 ++++++++++
 2 files changed, 14 insertions(+), 3 deletions(-)

diff --git a/sourcing/templates/view.html b/sourcing/templates/view.html
index 3c65d7e..fb888e7 100644
--- a/sourcing/templates/view.html
+++ b/sourcing/templates/view.html
@@ -14,6 +14,7 @@ div#text { font-family: Courier; }
       {% if doc.type == 'xanadoc' %}
         <a href="{{ doc.url }}" class="btn btn-default">fulfil</a>
       {% endif %}
+      <a href="{{ request.url }}/raw" class="btn btn-default">raw</a>
     </h1>
     <p><a href="{{ url_for('.home') }}">back to index</a></p>
 
@@ -24,10 +25,10 @@ div#text { font-family: Courier; }
           {% for i in line %}
             {%- if i.highlight -%}
               {% if i.highlight != '\n' and i.highlight != '\r\n' %}
-                <span class="highlight">{{- i.highlight -}}</span>
+                <span class="highlight">{{- nbsp_at_start(i.highlight) -}}</span>
               {% endif %}
             {%- else -%}
-              {{- i.text -}}
+              {{- nbsp_at_start(i.text) -}}
             {%- endif -%}
           {% endfor %}
         </p>
@@ -36,7 +37,7 @@ div#text { font-family: Courier; }
       {%- for start, line in iter_lines(doc.text) if line -%}
         {# <p data-start="{{ start }}">{% if line != "\n" and line != "\r\n" %}{{ line }}{% else %}&nbsp;{% endif
 %}</p>#}
-        <p data-start="{{ start }}">{{ line }}</p>
+        <p data-start="{{ start }}">{{ nbsp_at_start(line) }}</p>
       {%- endfor -%}
     {% endif %}
     </div>
diff --git a/sourcing/view.py b/sourcing/view.py
index 902c316..5817a41 100644
--- a/sourcing/view.py
+++ b/sourcing/view.py
@@ -141,6 +141,15 @@ def view_edl(username, hashid):
 def view_item_raw(username, hashid):
     return view_item(username, hashid, raw=True)
 
+def nbsp_at_start(text):
+    ''' Protect spaces at the start of a string. '''
+    space_count = 0
+    for c in text:
+        if c != ' ':
+            break
+        space_count += 1
+    return Markup('&nbsp;') * space_count + text[space_count:]
+
 @bp.route('/<username>/<hashid>')
 def view_item(username, hashid, raw=False):
     if ',' in hashid:
@@ -162,6 +171,7 @@ def view_item(username, hashid, raw=False):
                            span_start=start,
                            span_length=length,
                            add_highlight=add_highlight,
+                           nbsp_at_start=nbsp_at_start,
                            iter_lines=iter_lines)
 
 @bp.route('/<username>/<hashid>/edit', methods=['GET', 'POST'])