@@ -183,30 +183,57 @@ std::string Text::content(const abstract::Document *) const {
183183
184184void Text::set_content (const abstract::Document *, const std::string &text) {
185185 auto parent = m_node.parent ();
186- auto old_start = m_node;
186+ auto old_first = m_node;
187+ auto old_last = m_last;
188+ auto new_first = old_first;
189+ auto new_last = m_last;
190+
191+ const auto insert_pcdata = [&]() {
192+ auto new_node =
193+ parent.insert_child_before (pugi::xml_node_type::node_pcdata, old_first);
194+ if (new_first == old_first) {
195+ new_first = new_node;
196+ }
197+ new_last = new_node;
198+ return new_node;
199+ };
200+ const auto insert_node = [&](const char *node) {
201+ auto new_node = parent.insert_child_before (node, old_first);
202+ if (new_first == old_first) {
203+ new_first = new_node;
204+ }
205+ new_last = new_node;
206+ return new_node;
207+ };
187208
188- for (auto & &token : util::xml::tokenize_text (text)) {
209+ for (const util::xml::StringToken &token : util::xml::tokenize_text (text)) {
189210 switch (token.type ) {
190211 case util::xml::StringToken::Type::none:
191212 break ;
192213 case util::xml::StringToken::Type::string: {
193- auto text_node = parent.insert_child_before (
194- pugi::xml_node_type::node_pcdata, old_start);
214+ auto text_node = insert_pcdata ();
195215 text_node.text ().set (token.string .c_str ());
196216 } break ;
197217 case util::xml::StringToken::Type::spaces: {
198- auto space_node = parent. insert_child_before (" text:s" , old_start );
218+ auto space_node = insert_node (" text:s" );
199219 space_node.prepend_attribute (" text:c" ).set_value (token.string .size ());
200220 } break ;
201221 case util::xml::StringToken::Type::tabs: {
202222 for (std::size_t i = 0 ; i < token.string .size (); ++i) {
203- parent. insert_child_before (" text:tab" , old_start );
223+ insert_node (" text:tab" );
204224 }
205225 } break ;
206226 }
207227 }
208228
209- // TODO set first and last
229+ m_node = new_first;
230+ m_last = new_last;
231+
232+ for (auto node = old_first; node != old_last.next_sibling ();) {
233+ auto next = node.next_sibling ();
234+ parent.remove_child (node);
235+ node = next;
236+ }
210237}
211238
212239TextStyle Text::style (const abstract::Document *document) const {
0 commit comments