@@ -17,14 +17,12 @@ def initialize(node)
1717
1818 # Insert text before bookmarkStart node
1919 def insert_text_before ( text )
20- text_run = get_run_before
21- text_run . text = "#{ text_run . text } #{ text } "
20+ append_to_run ( get_run_before , text )
2221 end
2322
2423 # Insert text after bookmarkStart node
2524 def insert_text_after ( text )
26- text_run = get_run_after
27- text_run . text = "#{ text } #{ text_run . text } "
25+ prepend_to_run ( get_run_after , text )
2826 end
2927
3028 # insert multiple lines starting with paragraph containing bookmark node.
@@ -103,6 +101,38 @@ def parent_paragraph
103101
104102 private
105103
104+ # A run's text, line breaks and tabs, in document order.
105+ RUN_CONTENT_XPATH = 'w:t|w:br|w:tab|w:cr'
106+ private_constant :RUN_CONTENT_XPATH
107+
108+ # Add text at the very end of the run, which sits just before the
109+ # bookmark: to its last w:t, or to a new w:t when the run ends with a
110+ # break or tab. The rest of the run is left as it is (#197).
111+ def append_to_run ( run , text )
112+ last = run . node . xpath ( RUN_CONTENT_XPATH ) . last
113+ if last && run . node . xpath ( 'w:t' ) . include? ( last )
114+ Text . new ( last ) . content = last . content + text
115+ else
116+ Text . create_within ( run ) . content = text
117+ end
118+ end
119+
120+ # Add text at the very start of the run, which sits just after the
121+ # bookmark: to its first w:t, or to a new w:t when the run starts with
122+ # a break or tab. The rest of the run is left as it is (#197).
123+ def prepend_to_run ( run , text )
124+ first = run . node . xpath ( RUN_CONTENT_XPATH ) . first
125+ if first && run . node . xpath ( 'w:t' ) . include? ( first )
126+ Text . new ( first ) . content = text + first . content
127+ elsif first
128+ new_t = Text . create_with ( run )
129+ new_t . node = first . add_previous_sibling ( new_t . node )
130+ new_t . content = text
131+ else
132+ Text . create_within ( run ) . content = text
133+ end
134+ end
135+
106136 # The w:p the bookmark sits inside, or nil when it is block-level.
107137 def enclosing_paragraph
108138 @node . at_xpath ( "./parent::w:p" )
0 commit comments