]> git.lyx.org Git - lyx.git/blob - src/Text.cpp
Add comment
[lyx.git] / src / Text.cpp
1 /**
2  * \file src/Text.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Asger Alstrup
7  * \author Lars Gullik Bjønnes
8  * \author Dov Feldstern
9  * \author Jean-Marc Lasgouttes
10  * \author John Levon
11  * \author André Pönitz
12  * \author Stefan Schimanski
13  * \author Dekel Tsur
14  * \author Jürgen Vigna
15  *
16  * Full author contact details are available in file CREDITS.
17  */
18
19 #include <config.h>
20
21 #include "Text.h"
22
23 #include "Author.h"
24 #include "Buffer.h"
25 #include "buffer_funcs.h"
26 #include "BufferParams.h"
27 #include "BufferView.h"
28 #include "Changes.h"
29 #include "CompletionList.h"
30 #include "Cursor.h"
31 #include "CutAndPaste.h"
32 #include "DispatchResult.h"
33 #include "Encoding.h"
34 #include "ErrorList.h"
35 #include "FuncRequest.h"
36 #include "factory.h"
37 #include "InsetList.h"
38 #include "Language.h"
39 #include "Layout.h"
40 #include "Length.h"
41 #include "Lexer.h"
42 #include "lyxfind.h"
43 #include "LyXRC.h"
44 #include "Paragraph.h"
45 #include "ParagraphParameters.h"
46 #include "ParIterator.h"
47 #include "TextClass.h"
48 #include "TextMetrics.h"
49 #include "WordLangTuple.h"
50 #include "WordList.h"
51
52 #include "insets/InsetText.h"
53 #include "insets/InsetBibitem.h"
54 #include "insets/InsetCaption.h"
55 #include "insets/InsetNewline.h"
56 #include "insets/InsetNewpage.h"
57 #include "insets/InsetArgument.h"
58 #include "insets/InsetIPAMacro.h"
59 #include "insets/InsetSpace.h"
60 #include "insets/InsetSpecialChar.h"
61 #include "insets/InsetTabular.h"
62
63 #include "support/convert.h"
64 #include "support/debug.h"
65 #include "support/docstream.h"
66 #include "support/gettext.h"
67 #include "support/lassert.h"
68 #include "support/lstrings.h"
69 #include "support/lyxalgo.h"
70 #include "support/textutils.h"
71
72 #include <limits>
73 #include <sstream>
74
75
76 // TODO: replace if in Text::readParToken() with compile time switch
77 #if 0
78
79 #include "support/metahash.h"
80
81 typedef boost::mpl::string<'\\end','_lay','out'> end_layout;
82 typedef boost::mpl::string<'\\end','in','set'>   end_inset;
83
84 void foo()
85 {
86         std::string token = "\\end_layout";
87
88         switch (boost::hash_value(token)) {
89                 case lyx::support::hash_string<end_layout>::value:
90                         return;
91                 case lyx::support::hash_string<end_inset>::value:
92                         return;
93                 default: ;
94         };
95
96 }
97 #endif
98
99
100 using namespace std;
101 using namespace lyx::support;
102
103 namespace lyx {
104
105 using cap::cutSelection;
106 using cap::pasteParagraphList;
107
108 static bool moveItem(Paragraph & fromPar, pos_type fromPos,
109         Paragraph & toPar, pos_type toPos, BufferParams const & params)
110 {
111         // Note: moveItem() does not honour change tracking!
112         // Therefore, it should only be used for breaking and merging paragraphs
113
114         // We need a copy here because the character at fromPos is going to be erased.
115         Font const tmpFont = fromPar.getFontSettings(params, fromPos);
116         Change const tmpChange = fromPar.lookupChange(fromPos);
117
118         if (Inset * tmpInset = fromPar.getInset(fromPos)) {
119                 fromPar.releaseInset(fromPos);
120                 // The inset is not in fromPar any more.
121                 if (!toPar.insertInset(toPos, tmpInset, tmpFont, tmpChange)) {
122                         delete tmpInset;
123                         return false;
124                 }
125                 return true;
126         }
127
128         char_type const tmpChar = fromPar.getChar(fromPos);
129         fromPar.eraseChar(fromPos, false);
130         toPar.insertChar(toPos, tmpChar, tmpFont, tmpChange);
131         return true;
132 }
133
134
135 void breakParagraphConservative(BufferParams const & bparams,
136         ParagraphList & pars, pit_type par_offset, pos_type pos)
137 {
138         // create a new paragraph
139         Paragraph & tmp = *pars.insert(next(pars.begin(), par_offset + 1),
140                                        Paragraph());
141         Paragraph & par = pars[par_offset];
142
143         tmp.setInsetOwner(&par.inInset());
144         tmp.makeSameLayout(par);
145
146         LASSERT(pos <= par.size(), return);
147
148         if (pos < par.size()) {
149                 // move everything behind the break position to the new paragraph
150                 pos_type pos_end = par.size() - 1;
151
152                 for (pos_type i = pos, j = 0; i <= pos_end; ++i) {
153                         if (moveItem(par, pos, tmp, j, bparams)) {
154                                 ++j;
155                         }
156                 }
157                 // Move over the end-of-par change information
158                 tmp.setChange(tmp.size(), par.lookupChange(par.size()));
159                 par.setChange(par.size(), Change(bparams.track_changes ?
160                                            Change::INSERTED : Change::UNCHANGED));
161         }
162 }
163
164
165 void mergeParagraph(BufferParams const & bparams,
166         ParagraphList & pars, pit_type par_offset)
167 {
168         Paragraph & next = pars[par_offset + 1];
169         Paragraph & par = pars[par_offset];
170
171         pos_type pos_end = next.size() - 1;
172         pos_type pos_insert = par.size();
173
174         // the imaginary end-of-paragraph character (at par.size()) has to be
175         // marked as unmodified. Otherwise, its change is adopted by the first
176         // character of the next paragraph.
177         if (par.isChanged(par.size())) {
178                 LYXERR(Debug::CHANGES,
179                    "merging par with inserted/deleted end-of-par character");
180                 par.setChange(par.size(), Change(Change::UNCHANGED));
181         }
182
183         Change change = next.lookupChange(next.size());
184
185         // move the content of the second paragraph to the end of the first one
186         for (pos_type i = 0, j = pos_insert; i <= pos_end; ++i) {
187                 if (moveItem(next, 0, par, j, bparams)) {
188                         ++j;
189                 }
190         }
191
192         // move the change of the end-of-paragraph character
193         par.setChange(par.size(), change);
194
195         pars.erase(lyx::next(pars.begin(), par_offset + 1));
196 }
197
198
199 Text::Text(InsetText * owner, bool use_default_layout)
200         : owner_(owner)
201 {
202         pars_.push_back(Paragraph());
203         Paragraph & par = pars_.back();
204         par.setInsetOwner(owner);
205         DocumentClass const & dc = owner->buffer().params().documentClass();
206         if (use_default_layout)
207                 par.setDefaultLayout(dc);
208         else
209                 par.setPlainLayout(dc);
210 }
211
212
213 Text::Text(InsetText * owner, Text const & text)
214         : owner_(owner)
215 {
216         pars_ = text.pars_;
217         ParagraphList::iterator const end = pars_.end();
218         ParagraphList::iterator it = pars_.begin();
219         for (; it != end; ++it)
220                 it->setInsetOwner(owner);
221 }
222
223
224 pit_type Text::depthHook(pit_type pit, depth_type depth) const
225 {
226         pit_type newpit = pit;
227
228         if (newpit != 0)
229                 --newpit;
230
231         while (newpit != 0 && pars_[newpit].getDepth() > depth)
232                 --newpit;
233
234         if (pars_[newpit].getDepth() > depth)
235                 return pit;
236
237         return newpit;
238 }
239
240
241 pit_type Text::outerHook(pit_type par_offset) const
242 {
243         Paragraph const & par = pars_[par_offset];
244
245         if (par.getDepth() == 0)
246                 return pars_.size();
247         return depthHook(par_offset, depth_type(par.getDepth() - 1));
248 }
249
250
251 bool Text::isFirstInSequence(pit_type par_offset) const
252 {
253         Paragraph const & par = pars_[par_offset];
254
255         pit_type dhook_offset = depthHook(par_offset, par.getDepth());
256
257         if (dhook_offset == par_offset)
258                 return true;
259
260         Paragraph const & dhook = pars_[dhook_offset];
261
262         return dhook.layout() != par.layout()
263                 || dhook.getDepth() != par.getDepth();
264 }
265
266
267 int Text::getTocLevel(pit_type par_offset) const
268 {
269         Paragraph const & par = pars_[par_offset];
270
271         if (par.layout().isEnvironment() && !isFirstInSequence(par_offset))
272                 return Layout::NOT_IN_TOC;
273
274         return par.layout().toclevel;
275 }
276
277
278 Font const Text::outerFont(pit_type par_offset) const
279 {
280         depth_type par_depth = pars_[par_offset].getDepth();
281         FontInfo tmpfont = inherit_font;
282         depth_type prev_par_depth = 0;
283         // Resolve against environment font information
284         while (par_offset != pit_type(pars_.size())
285                && par_depth != prev_par_depth
286                && par_depth
287                && !tmpfont.resolved()) {
288                 prev_par_depth = par_depth;
289                 par_offset = outerHook(par_offset);
290                 if (par_offset != pit_type(pars_.size())) {
291                         tmpfont.realize(pars_[par_offset].layout().font);
292                         par_depth = pars_[par_offset].getDepth();
293                 }
294         }
295
296         return Font(tmpfont);
297 }
298
299
300 static void acceptOrRejectChanges(ParagraphList & pars,
301         BufferParams const & bparams, Text::ChangeOp op)
302 {
303         pit_type pars_size = static_cast<pit_type>(pars.size());
304
305         // first, accept or reject changes within each individual
306         // paragraph (do not consider end-of-par)
307         for (pit_type pit = 0; pit < pars_size; ++pit) {
308                 // prevent assertion failure
309                 if (!pars[pit].empty()) {
310                         if (op == Text::ACCEPT)
311                                 pars[pit].acceptChanges(0, pars[pit].size());
312                         else
313                                 pars[pit].rejectChanges(0, pars[pit].size());
314                 }
315         }
316
317         // next, accept or reject imaginary end-of-par characters
318         for (pit_type pit = 0; pit < pars_size; ++pit) {
319                 pos_type pos = pars[pit].size();
320                 if (pars[pit].isChanged(pos)) {
321                         // keep the end-of-par char if it is inserted and accepted
322                         // or when it is deleted and rejected.
323                         if (pars[pit].isInserted(pos) == (op == Text::ACCEPT)) {
324                                 pars[pit].setChange(pos, Change(Change::UNCHANGED));
325                         } else {
326                                 if (pit == pars_size - 1) {
327                                         // we cannot remove a par break at the end of the last
328                                         // paragraph; instead, we mark it unchanged
329                                         pars[pit].setChange(pos, Change(Change::UNCHANGED));
330                                 } else {
331                                         mergeParagraph(bparams, pars, pit);
332                                         --pit;
333                                         --pars_size;
334                                 }
335                         }
336                 }
337         }
338 }
339
340
341 void acceptChanges(ParagraphList & pars, BufferParams const & bparams)
342 {
343         acceptOrRejectChanges(pars, bparams, Text::ACCEPT);
344 }
345
346
347 void rejectChanges(ParagraphList & pars, BufferParams const & bparams)
348 {
349         acceptOrRejectChanges(pars, bparams, Text::REJECT);
350 }
351
352
353 InsetText const & Text::inset() const
354 {
355         return *owner_;
356 }
357
358
359
360 void Text::readParToken(Paragraph & par, Lexer & lex,
361         string const & token, Font & font, Change & change, ErrorList & errorList)
362 {
363         Buffer * buf = const_cast<Buffer *>(&owner_->buffer());
364         BufferParams const & bp = buf->params();
365
366         if (token[0] != '\\') {
367                 docstring dstr = lex.getDocString();
368                 par.appendString(dstr, font, change);
369
370         } else if (token == "\\begin_layout") {
371                 lex.eatLine();
372                 docstring layoutname = lex.getDocString();
373
374                 font = Font(inherit_font, bp.language);
375                 change = Change(Change::UNCHANGED);
376
377                 DocumentClass const & tclass = bp.documentClass();
378
379                 if (layoutname.empty())
380                         layoutname = tclass.defaultLayoutName();
381
382                 if (owner_->forcePlainLayout()) {
383                         // in this case only the empty layout is allowed
384                         layoutname = tclass.plainLayoutName();
385                 } else if (par.usePlainLayout()) {
386                         // in this case, default layout maps to empty layout
387                         if (layoutname == tclass.defaultLayoutName())
388                                 layoutname = tclass.plainLayoutName();
389                 } else {
390                         // otherwise, the empty layout maps to the default
391                         if (layoutname == tclass.plainLayoutName())
392                                 layoutname = tclass.defaultLayoutName();
393                 }
394
395                 // When we apply an unknown layout to a document, we add this layout to the textclass
396                 // of this document. For example, when you apply class article to a beamer document,
397                 // all unknown layouts such as frame will be added to document class article so that
398                 // these layouts can keep their original names.
399                 bool const added_one = tclass.addLayoutIfNeeded(layoutname);
400                 if (added_one) {
401                         // Warn the user.
402                         docstring const s = bformat(_("Layout `%1$s' was not found."), layoutname);
403                         errorList.push_back(
404                                 ErrorItem(_("Layout Not Found"), s, par.id(), 0, par.size()));
405                 }
406
407                 par.setLayout(bp.documentClass()[layoutname]);
408
409                 // Test whether the layout is obsolete.
410                 Layout const & layout = par.layout();
411                 if (!layout.obsoleted_by().empty())
412                         par.setLayout(bp.documentClass()[layout.obsoleted_by()]);
413
414                 par.params().read(lex);
415
416         } else if (token == "\\end_layout") {
417                 LYXERR0("Solitary \\end_layout in line " << lex.lineNumber() << "\n"
418                        << "Missing \\begin_layout ?");
419         } else if (token == "\\end_inset") {
420                 LYXERR0("Solitary \\end_inset in line " << lex.lineNumber() << "\n"
421                        << "Missing \\begin_inset ?");
422         } else if (token == "\\begin_inset") {
423                 Inset * inset = readInset(lex, buf);
424                 if (inset)
425                         par.insertInset(par.size(), inset, font, change);
426                 else {
427                         lex.eatLine();
428                         docstring line = lex.getDocString();
429                         errorList.push_back(ErrorItem(_("Unknown Inset"), line,
430                                             par.id(), 0, par.size()));
431                 }
432         } else if (token == "\\family") {
433                 lex.next();
434                 setLyXFamily(lex.getString(), font.fontInfo());
435         } else if (token == "\\series") {
436                 lex.next();
437                 setLyXSeries(lex.getString(), font.fontInfo());
438         } else if (token == "\\shape") {
439                 lex.next();
440                 setLyXShape(lex.getString(), font.fontInfo());
441         } else if (token == "\\size") {
442                 lex.next();
443                 setLyXSize(lex.getString(), font.fontInfo());
444         } else if (token == "\\lang") {
445                 lex.next();
446                 string const tok = lex.getString();
447                 Language const * lang = languages.getLanguage(tok);
448                 if (lang) {
449                         font.setLanguage(lang);
450                 } else {
451                         font.setLanguage(bp.language);
452                         lex.printError("Unknown language `$$Token'");
453                 }
454         } else if (token == "\\numeric") {
455                 lex.next();
456                 font.fontInfo().setNumber(setLyXMisc(lex.getString()));
457         } else if (token == "\\emph") {
458                 lex.next();
459                 font.fontInfo().setEmph(setLyXMisc(lex.getString()));
460         } else if (token == "\\bar") {
461                 lex.next();
462                 string const tok = lex.getString();
463
464                 if (tok == "under")
465                         font.fontInfo().setUnderbar(FONT_ON);
466                 else if (tok == "no")
467                         font.fontInfo().setUnderbar(FONT_OFF);
468                 else if (tok == "default")
469                         font.fontInfo().setUnderbar(FONT_INHERIT);
470                 else
471                         lex.printError("Unknown bar font flag "
472                                        "`$$Token'");
473         } else if (token == "\\strikeout") {
474                 lex.next();
475                 font.fontInfo().setStrikeout(setLyXMisc(lex.getString()));
476         } else if (token == "\\uuline") {
477                 lex.next();
478                 font.fontInfo().setUuline(setLyXMisc(lex.getString()));
479         } else if (token == "\\uwave") {
480                 lex.next();
481                 font.fontInfo().setUwave(setLyXMisc(lex.getString()));
482         } else if (token == "\\noun") {
483                 lex.next();
484                 font.fontInfo().setNoun(setLyXMisc(lex.getString()));
485         } else if (token == "\\color") {
486                 lex.next();
487                 setLyXColor(lex.getString(), font.fontInfo());
488         } else if (token == "\\SpecialChar" ||
489                    (token == "\\SpecialCharNoPassThru" &&
490                     !par.layout().pass_thru && !inset().isPassThru())) {
491                 auto_ptr<Inset> inset;
492                 inset.reset(new InsetSpecialChar);
493                 inset->read(lex);
494                 inset->setBuffer(*buf);
495                 par.insertInset(par.size(), inset.release(), font, change);
496         } else if (token == "\\SpecialCharNoPassThru") {
497                 lex.next();
498                 docstring const s = ltrim(lex.getDocString(), "\\");
499                 par.insert(par.size(), s, font, change);
500         } else if (token == "\\IPAChar") {
501                 auto_ptr<Inset> inset;
502                 inset.reset(new InsetIPAChar);
503                 inset->read(lex);
504                 inset->setBuffer(*buf);
505                 par.insertInset(par.size(), inset.release(), font, change);
506         } else if (token == "\\twohyphens" || token == "\\threehyphens") {
507                 // Ideally, this should be done by lyx2lyx, but lyx2lyx does not know the
508                 // running font and does not know anything about layouts (and CopyStyle).
509                 Layout const & layout(par.layout());
510                 FontInfo info = font.fontInfo();
511                 info.realize(layout.resfont);
512                 if (layout.pass_thru || inset().isPassThru() ||
513                     info.family() == TYPEWRITER_FAMILY) {
514                         if (token == "\\twohyphens")
515                                 par.insert(par.size(), from_ascii("--"), font, change);
516                         else
517                                 par.insert(par.size(), from_ascii("---"), font, change);
518                 } else {
519                         if (token == "\\twohyphens")
520                                 par.insertChar(par.size(), 0x2013, font, change);
521                         else
522                                 par.insertChar(par.size(), 0x2014, font, change);
523                 }
524         } else if (token == "\\backslash") {
525                 par.appendChar('\\', font, change);
526         } else if (token == "\\LyXTable") {
527                 auto_ptr<Inset> inset(new InsetTabular(buf));
528                 inset->read(lex);
529                 par.insertInset(par.size(), inset.release(), font, change);
530         } else if (token == "\\change_unchanged") {
531                 change = Change(Change::UNCHANGED);
532         } else if (token == "\\change_inserted" || token == "\\change_deleted") {
533                 lex.eatLine();
534                 istringstream is(lex.getString());
535                 int aid;
536                 time_t ct;
537                 is >> aid >> ct;
538                 BufferParams::AuthorMap const & am = bp.author_map;
539                 if (am.find(aid) == am.end()) {
540                         errorList.push_back(ErrorItem(_("Change tracking error"),
541                                             bformat(_("Unknown author index for change: %1$d\n"), aid),
542                                             par.id(), 0, par.size()));
543                         change = Change(Change::UNCHANGED);
544                 } else {
545                         if (token == "\\change_inserted")
546                                 change = Change(Change::INSERTED, am.find(aid)->second, ct);
547                         else
548                                 change = Change(Change::DELETED, am.find(aid)->second, ct);
549                 }
550         } else {
551                 lex.eatLine();
552                 errorList.push_back(ErrorItem(_("Unknown token"),
553                         bformat(_("Unknown token: %1$s %2$s\n"), from_utf8(token),
554                         lex.getDocString()),
555                         par.id(), 0, par.size()));
556         }
557 }
558
559
560 void Text::readParagraph(Paragraph & par, Lexer & lex,
561         ErrorList & errorList)
562 {
563         lex.nextToken();
564         string token = lex.getString();
565         Font font;
566         Change change(Change::UNCHANGED);
567
568         while (lex.isOK()) {
569                 readParToken(par, lex, token, font, change, errorList);
570
571                 lex.nextToken();
572                 token = lex.getString();
573
574                 if (token.empty())
575                         continue;
576
577                 if (token == "\\end_layout") {
578                         //Ok, paragraph finished
579                         break;
580                 }
581
582                 LYXERR(Debug::PARSER, "Handling paragraph token: `" << token << '\'');
583                 if (token == "\\begin_layout" || token == "\\end_document"
584                     || token == "\\end_inset" || token == "\\begin_deeper"
585                     || token == "\\end_deeper") {
586                         lex.pushToken(token);
587                         lyxerr << "Paragraph ended in line "
588                                << lex.lineNumber() << "\n"
589                                << "Missing \\end_layout.\n";
590                         break;
591                 }
592         }
593         // Final change goes to paragraph break:
594         par.setChange(par.size(), change);
595
596         // Initialize begin_of_body_ on load; redoParagraph maintains
597         par.setBeginOfBody();
598
599         // mark paragraph for spell checking on load
600         // par.requestSpellCheck();
601 }
602
603
604 class TextCompletionList : public CompletionList
605 {
606 public:
607         ///
608         TextCompletionList(Cursor const & cur, WordList const * list)
609                 : buffer_(cur.buffer()), list_(list)
610         {}
611         ///
612         virtual ~TextCompletionList() {}
613
614         ///
615         virtual bool sorted() const { return true; }
616         ///
617         virtual size_t size() const
618         {
619                 return list_->size();
620         }
621         ///
622         virtual docstring const & data(size_t idx) const
623         {
624                 return list_->word(idx);
625         }
626
627 private:
628         ///
629         Buffer const * buffer_;
630         ///
631         WordList const * list_;
632 };
633
634
635 bool Text::empty() const
636 {
637         return pars_.empty() || (pars_.size() == 1 && pars_[0].empty()
638                 // FIXME: Should we consider the labeled type as empty too?
639                 && pars_[0].layout().labeltype == LABEL_NO_LABEL);
640 }
641
642
643 double Text::spacing(Paragraph const & par) const
644 {
645         if (par.params().spacing().isDefault())
646                 return owner_->buffer().params().spacing().getValue();
647         return par.params().spacing().getValue();
648 }
649
650
651 /**
652  * This breaks a paragraph at the specified position.
653  * The new paragraph will:
654  * - Decrease depth by one (or change layout to default layout) when
655  *    keep_layout == false
656  * - keep current depth and layout when keep_layout == true
657  */
658 static void breakParagraph(Text & text, pit_type par_offset, pos_type pos,
659                     bool keep_layout)
660 {
661         BufferParams const & bparams = text.inset().buffer().params();
662         ParagraphList & pars = text.paragraphs();
663         // create a new paragraph, and insert into the list
664         ParagraphList::iterator tmp =
665                 pars.insert(next(pars.begin(), par_offset + 1),
666                             Paragraph());
667
668         Paragraph & par = pars[par_offset];
669
670         // remember to set the inset_owner
671         tmp->setInsetOwner(&par.inInset());
672         // without doing that we get a crash when typing <Return> at the
673         // end of a paragraph
674         tmp->setPlainOrDefaultLayout(bparams.documentClass());
675
676         if (keep_layout) {
677                 tmp->setLayout(par.layout());
678                 tmp->setLabelWidthString(par.params().labelWidthString());
679                 tmp->params().depth(par.params().depth());
680         } else if (par.params().depth() > 0) {
681                 Paragraph const & hook = pars[text.outerHook(par_offset)];
682                 tmp->setLayout(hook.layout());
683                 // not sure the line below is useful
684                 tmp->setLabelWidthString(par.params().labelWidthString());
685                 tmp->params().depth(hook.params().depth());
686         }
687
688         bool const isempty = (par.allowEmpty() && par.empty());
689
690         if (!isempty && (par.size() > pos || par.empty())) {
691                 tmp->setLayout(par.layout());
692                 tmp->params().align(par.params().align());
693                 tmp->setLabelWidthString(par.params().labelWidthString());
694
695                 tmp->params().depth(par.params().depth());
696                 tmp->params().noindent(par.params().noindent());
697
698                 // move everything behind the break position
699                 // to the new paragraph
700
701                 /* Note: if !keepempty, empty() == true, then we reach
702                  * here with size() == 0. So pos_end becomes - 1. This
703                  * doesn't cause problems because both loops below
704                  * enforce pos <= pos_end and 0 <= pos
705                  */
706                 pos_type pos_end = par.size() - 1;
707
708                 for (pos_type i = pos, j = 0; i <= pos_end; ++i) {
709                         if (moveItem(par, pos, *tmp, j, bparams)) {
710                                 ++j;
711                         }
712                 }
713         }
714
715         // Move over the end-of-par change information
716         tmp->setChange(tmp->size(), par.lookupChange(par.size()));
717         par.setChange(par.size(), Change(bparams.track_changes ?
718                                            Change::INSERTED : Change::UNCHANGED));
719
720         if (pos) {
721                 // Make sure that we keep the language when
722                 // breaking paragraph.
723                 if (tmp->empty()) {
724                         Font changed = tmp->getFirstFontSettings(bparams);
725                         Font const & old = par.getFontSettings(bparams, par.size());
726                         changed.setLanguage(old.language());
727                         tmp->setFont(0, changed);
728                 }
729
730                 return;
731         }
732
733         if (!isempty) {
734                 bool const soa = par.params().startOfAppendix();
735                 par.params().clear();
736                 // do not lose start of appendix marker (bug 4212)
737                 par.params().startOfAppendix(soa);
738                 par.setPlainOrDefaultLayout(bparams.documentClass());
739         }
740
741         if (keep_layout) {
742                 par.setLayout(tmp->layout());
743                 par.setLabelWidthString(tmp->params().labelWidthString());
744                 par.params().depth(tmp->params().depth());
745         }
746 }
747
748
749 void Text::breakParagraph(Cursor & cur, bool inverse_logic)
750 {
751         LBUFERR(this == cur.text());
752
753         Paragraph & cpar = cur.paragraph();
754         pit_type cpit = cur.pit();
755
756         DocumentClass const & tclass = cur.buffer()->params().documentClass();
757         Layout const & layout = cpar.layout();
758
759         if (cur.lastpos() == 0 && !cpar.allowEmpty()) {
760                 if (changeDepthAllowed(cur, DEC_DEPTH))
761                         changeDepth(cur, DEC_DEPTH);
762                 else {
763                         docstring const & lay = cur.paragraph().usePlainLayout()
764                             ? tclass.plainLayoutName() : tclass.defaultLayoutName();
765                         setLayout(cur, lay);
766                 }
767                 return;
768         }
769
770         cur.recordUndo();
771
772         // Always break behind a space
773         // It is better to erase the space (Dekel)
774         if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
775                 cpar.eraseChar(cur.pos(), cur.buffer()->params().track_changes);
776
777         // What should the layout for the new paragraph be?
778         bool keep_layout = layout.isEnvironment()
779                 || (layout.isParagraph() && layout.parbreak_is_newline);
780         if (inverse_logic)
781                 keep_layout = !keep_layout;
782
783         // We need to remember this before we break the paragraph, because
784         // that invalidates the layout variable
785         bool sensitive = layout.labeltype == LABEL_SENSITIVE;
786
787         // we need to set this before we insert the paragraph.
788         bool const isempty = cpar.allowEmpty() && cpar.empty();
789
790         lyx::breakParagraph(*this, cpit, cur.pos(), keep_layout);
791
792         // After this, neither paragraph contains any rows!
793
794         cpit = cur.pit();
795         pit_type next_par = cpit + 1;
796
797         // well this is the caption hack since one caption is really enough
798         if (sensitive) {
799                 if (cur.pos() == 0)
800                         // set to standard-layout
801                 //FIXME Check if this should be plainLayout() in some cases
802                         pars_[cpit].applyLayout(tclass.defaultLayout());
803                 else
804                         // set to standard-layout
805                         //FIXME Check if this should be plainLayout() in some cases
806                         pars_[next_par].applyLayout(tclass.defaultLayout());
807         }
808
809         while (!pars_[next_par].empty() && pars_[next_par].isNewline(0)) {
810                 if (!pars_[next_par].eraseChar(0, cur.buffer()->params().track_changes))
811                         break; // the character couldn't be deleted physically due to change tracking
812         }
813
814         // A singlePar update is not enough in this case.
815         cur.screenUpdateFlags(Update::Force);
816         cur.forceBufferUpdate();
817
818         // This check is necessary. Otherwise the new empty paragraph will
819         // be deleted automatically. And it is more friendly for the user!
820         if (cur.pos() != 0 || isempty)
821                 setCursor(cur, cur.pit() + 1, 0);
822         else
823                 setCursor(cur, cur.pit(), 0);
824 }
825
826
827 // needed to insert the selection
828 void Text::insertStringAsLines(Cursor & cur, docstring const & str,
829                 Font const & font)
830 {
831         BufferParams const & bparams = owner_->buffer().params();
832         pit_type pit = cur.pit();
833         pos_type pos = cur.pos();
834
835         // insert the string, don't insert doublespace
836         bool space_inserted = true;
837         for (docstring::const_iterator cit = str.begin();
838             cit != str.end(); ++cit) {
839                 Paragraph & par = pars_[pit];
840                 if (*cit == '\n') {
841                         if (inset().allowMultiPar() && (!par.empty() || par.allowEmpty())) {
842                                 lyx::breakParagraph(*this, pit, pos,
843                                         par.layout().isEnvironment());
844                                 ++pit;
845                                 pos = 0;
846                                 space_inserted = true;
847                         } else {
848                                 continue;
849                         }
850                 // do not insert consecutive spaces if !free_spacing
851                 } else if ((*cit == ' ' || *cit == '\t') &&
852                            space_inserted && !par.isFreeSpacing()) {
853                         continue;
854                 } else if (*cit == '\t') {
855                         if (!par.isFreeSpacing()) {
856                                 // tabs are like spaces here
857                                 par.insertChar(pos, ' ', font, bparams.track_changes);
858                                 ++pos;
859                                 space_inserted = true;
860                         } else {
861                                 par.insertChar(pos, *cit, font, bparams.track_changes);
862                                 ++pos;
863                                 space_inserted = true;
864                         }
865                 } else if (!isPrintable(*cit)) {
866                         // Ignore unprintables
867                         continue;
868                 } else {
869                         // just insert the character
870                         par.insertChar(pos, *cit, font, bparams.track_changes);
871                         ++pos;
872                         space_inserted = (*cit == ' ');
873                 }
874         }
875         setCursor(cur, pit, pos);
876 }
877
878
879 // turn double CR to single CR, others are converted into one
880 // blank. Then insertStringAsLines is called
881 void Text::insertStringAsParagraphs(Cursor & cur, docstring const & str,
882                 Font const & font)
883 {
884         docstring linestr = str;
885         bool newline_inserted = false;
886
887         for (string::size_type i = 0, siz = linestr.size(); i < siz; ++i) {
888                 if (linestr[i] == '\n') {
889                         if (newline_inserted) {
890                                 // we know that \r will be ignored by
891                                 // insertStringAsLines. Of course, it is a dirty
892                                 // trick, but it works...
893                                 linestr[i - 1] = '\r';
894                                 linestr[i] = '\n';
895                         } else {
896                                 linestr[i] = ' ';
897                                 newline_inserted = true;
898                         }
899                 } else if (isPrintable(linestr[i])) {
900                         newline_inserted = false;
901                 }
902         }
903         insertStringAsLines(cur, linestr, font);
904 }
905
906
907 // insert a character, moves all the following breaks in the
908 // same Paragraph one to the right and make a rebreak
909 void Text::insertChar(Cursor & cur, char_type c)
910 {
911         LBUFERR(this == cur.text());
912
913         cur.recordUndo(INSERT_UNDO);
914
915         TextMetrics const & tm = cur.bv().textMetrics(this);
916         Buffer const & buffer = *cur.buffer();
917         Paragraph & par = cur.paragraph();
918         // try to remove this
919         pit_type const pit = cur.pit();
920
921         bool const freeSpacing = par.layout().free_spacing ||
922                 par.isFreeSpacing();
923
924         if (lyxrc.auto_number) {
925                 static docstring const number_operators = from_ascii("+-/*");
926                 static docstring const number_unary_operators = from_ascii("+-");
927                 static docstring const number_seperators = from_ascii(".,:");
928
929                 if (cur.current_font.fontInfo().number() == FONT_ON) {
930                         if (!isDigitASCII(c) && !contains(number_operators, c) &&
931                             !(contains(number_seperators, c) &&
932                               cur.pos() != 0 &&
933                               cur.pos() != cur.lastpos() &&
934                               tm.displayFont(pit, cur.pos()).fontInfo().number() == FONT_ON &&
935                               tm.displayFont(pit, cur.pos() - 1).fontInfo().number() == FONT_ON)
936                            )
937                                 number(cur); // Set current_font.number to OFF
938                 } else if (isDigitASCII(c) &&
939                            cur.real_current_font.isVisibleRightToLeft()) {
940                         number(cur); // Set current_font.number to ON
941
942                         if (cur.pos() != 0) {
943                                 char_type const c = par.getChar(cur.pos() - 1);
944                                 if (contains(number_unary_operators, c) &&
945                                     (cur.pos() == 1
946                                      || par.isSeparator(cur.pos() - 2)
947                                      || par.isEnvSeparator(cur.pos() - 2)
948                                      || par.isNewline(cur.pos() - 2))
949                                   ) {
950                                         setCharFont(pit, cur.pos() - 1, cur.current_font,
951                                                 tm.font_);
952                                 } else if (contains(number_seperators, c)
953                                      && cur.pos() >= 2
954                                      && tm.displayFont(pit, cur.pos() - 2).fontInfo().number() == FONT_ON) {
955                                         setCharFont(pit, cur.pos() - 1, cur.current_font,
956                                                 tm.font_);
957                                 }
958                         }
959                 }
960         }
961
962         // In Bidi text, we want spaces to be treated in a special way: spaces
963         // which are between words in different languages should get the
964         // paragraph's language; otherwise, spaces should keep the language
965         // they were originally typed in. This is only in effect while typing;
966         // after the text is already typed in, the user can always go back and
967         // explicitly set the language of a space as desired. But 99.9% of the
968         // time, what we're doing here is what the user actually meant.
969         //
970         // The following cases are the ones in which the language of the space
971         // should be changed to match that of the containing paragraph. In the
972         // depictions, lowercase is LTR, uppercase is RTL, underscore (_)
973         // represents a space, pipe (|) represents the cursor position (so the
974         // character before it is the one just typed in). The different cases
975         // are depicted logically (not visually), from left to right:
976         //
977         // 1. A_a|
978         // 2. a_A|
979         //
980         // Theoretically, there are other situations that we should, perhaps, deal
981         // with (e.g.: a|_A, A|_a). In practice, though, there really isn't any
982         // point (to understand why, just try to create this situation...).
983
984         if ((cur.pos() >= 2) && (par.isLineSeparator(cur.pos() - 1))) {
985                 // get font in front and behind the space in question. But do NOT
986                 // use getFont(cur.pos()) because the character c is not inserted yet
987                 Font const pre_space_font  = tm.displayFont(cur.pit(), cur.pos() - 2);
988                 Font const & post_space_font = cur.real_current_font;
989                 bool pre_space_rtl  = pre_space_font.isVisibleRightToLeft();
990                 bool post_space_rtl = post_space_font.isVisibleRightToLeft();
991
992                 if (pre_space_rtl != post_space_rtl) {
993                         // Set the space's language to match the language of the
994                         // adjacent character whose direction is the paragraph's
995                         // direction; don't touch other properties of the font
996                         Language const * lang =
997                                 (pre_space_rtl == par.isRTL(buffer.params())) ?
998                                 pre_space_font.language() : post_space_font.language();
999
1000                         Font space_font = tm.displayFont(cur.pit(), cur.pos() - 1);
1001                         space_font.setLanguage(lang);
1002                         par.setFont(cur.pos() - 1, space_font);
1003                 }
1004         }
1005
1006         // Next check, if there will be two blanks together or a blank at
1007         // the beginning of a paragraph.
1008         // I decided to handle blanks like normal characters, the main
1009         // difference are the special checks when calculating the row.fill
1010         // (blank does not count at the end of a row) and the check here
1011
1012         // When the free-spacing option is set for the current layout,
1013         // disable the double-space checking
1014         if (!freeSpacing && isLineSeparatorChar(c)) {
1015                 if (cur.pos() == 0) {
1016                         cur.message(_(
1017                                         "You cannot insert a space at the "
1018                                         "beginning of a paragraph. Please read the Tutorial."));
1019                         return;
1020                 }
1021                 // LASSERT: Is it safe to continue here?
1022                 LASSERT(cur.pos() > 0, /**/);
1023                 if ((par.isLineSeparator(cur.pos() - 1) || par.isNewline(cur.pos() - 1))
1024                                 && !par.isDeleted(cur.pos() - 1)) {
1025                         cur.message(_(
1026                                         "You cannot type two spaces this way. "
1027                                         "Please read the Tutorial."));
1028                         return;
1029                 }
1030         }
1031
1032         // Prevent to insert uncodable characters in verbatim and ERT
1033         // (workaround for bug 9012)
1034         // Don't do it for listings inset, since InsetListings::latex() tries
1035         // to switch to a usable encoding which works in many cases (bug 9102).
1036         if (cur.paragraph().isPassThru() && owner_->lyxCode() != LISTINGS_CODE &&
1037             cur.current_font.language()) {
1038                 Encoding const * e = cur.current_font.language()->encoding();
1039                 if (!e->encodable(c)) {
1040                         cur.message(_("Character is uncodable in verbatim paragraphs."));
1041                         return;
1042                 }
1043         }
1044
1045         pos_type pos = cur.pos();
1046         if (!cur.paragraph().isPassThru() && owner_->lyxCode() != IPA_CODE &&
1047             cur.current_font.fontInfo().family() != TYPEWRITER_FAMILY &&
1048             c == '-' && pos > 0) {
1049                 if (par.getChar(pos - 1) == '-') {
1050                         // convert "--" to endash
1051                         par.eraseChar(pos - 1, cur.buffer()->params().track_changes);
1052                         c = 0x2013;
1053                         pos--;
1054                 } else if (par.getChar(pos - 1) == 0x2013) {
1055                         // convert "---" to emdash
1056                         par.eraseChar(pos - 1, cur.buffer()->params().track_changes);
1057                         c = 0x2014;
1058                         pos--;
1059                 } else if (par.getChar(pos - 1) == 0x2014) {
1060                         // convert "----" to "-"
1061                         par.eraseChar(pos - 1, cur.buffer()->params().track_changes);
1062                         c = '-';
1063                         pos--;
1064                 }
1065         }
1066
1067         par.insertChar(pos, c, cur.current_font,
1068                 cur.buffer()->params().track_changes);
1069         cur.checkBufferStructure();
1070
1071 //              cur.screenUpdateFlags(Update::Force);
1072         bool boundary = cur.boundary()
1073                 || tm.isRTLBoundary(cur.pit(), pos + 1);
1074         setCursor(cur, cur.pit(), pos + 1, false, boundary);
1075         charInserted(cur);
1076 }
1077
1078
1079 void Text::charInserted(Cursor & cur)
1080 {
1081         Paragraph & par = cur.paragraph();
1082
1083         // register word if a non-letter was entered
1084         if (cur.pos() > 1
1085             && !par.isWordSeparator(cur.pos() - 2)
1086             && par.isWordSeparator(cur.pos() - 1)) {
1087                 // get the word in front of cursor
1088                 LBUFERR(this == cur.text());
1089                 cur.paragraph().updateWords();
1090         }
1091 }
1092
1093
1094 // the cursor set functions have a special mechanism. When they
1095 // realize, that you left an empty paragraph, they will delete it.
1096
1097 bool Text::cursorForwardOneWord(Cursor & cur)
1098 {
1099         LBUFERR(this == cur.text());
1100
1101         pos_type const lastpos = cur.lastpos();
1102         pit_type pit = cur.pit();
1103         pos_type pos = cur.pos();
1104         Paragraph const & par = cur.paragraph();
1105
1106         // Paragraph boundary is a word boundary
1107         if (pos == lastpos) {
1108                 if (pit != cur.lastpit())
1109                         return setCursor(cur, pit + 1, 0);
1110                 else
1111                         return false;
1112         }
1113
1114         if (lyxrc.mac_like_cursor_movement) {
1115                 // Skip through trailing punctuation and spaces.
1116                 while (pos != lastpos && (par.isChar(pos) || par.isSpace(pos)))
1117                         ++pos;
1118
1119                 // Skip over either a non-char inset or a full word
1120                 if (pos != lastpos && par.isWordSeparator(pos))
1121                         ++pos;
1122                 else while (pos != lastpos && !par.isWordSeparator(pos))
1123                              ++pos;
1124         } else {
1125                 LASSERT(pos < lastpos, return false); // see above
1126                 if (!par.isWordSeparator(pos))
1127                         while (pos != lastpos && !par.isWordSeparator(pos))
1128                                 ++pos;
1129                 else if (par.isChar(pos))
1130                         while (pos != lastpos && par.isChar(pos))
1131                                 ++pos;
1132                 else if (!par.isSpace(pos)) // non-char inset
1133                         ++pos;
1134
1135                 // Skip over white space
1136                 while (pos != lastpos && par.isSpace(pos))
1137                              ++pos;
1138         }
1139
1140         return setCursor(cur, pit, pos);
1141 }
1142
1143
1144 bool Text::cursorBackwardOneWord(Cursor & cur)
1145 {
1146         LBUFERR(this == cur.text());
1147
1148         pit_type pit = cur.pit();
1149         pos_type pos = cur.pos();
1150         Paragraph & par = cur.paragraph();
1151
1152         // Paragraph boundary is a word boundary
1153         if (pos == 0 && pit != 0)
1154                 return setCursor(cur, pit - 1, getPar(pit - 1).size());
1155
1156         if (lyxrc.mac_like_cursor_movement) {
1157                 // Skip through punctuation and spaces.
1158                 while (pos != 0 && (par.isChar(pos - 1) || par.isSpace(pos - 1)))
1159                         --pos;
1160
1161                 // Skip over either a non-char inset or a full word
1162                 if (pos != 0 && par.isWordSeparator(pos - 1) && !par.isChar(pos - 1))
1163                         --pos;
1164                 else while (pos != 0 && !par.isWordSeparator(pos - 1))
1165                              --pos;
1166         } else {
1167                 // Skip over white space
1168                 while (pos != 0 && par.isSpace(pos - 1))
1169                              --pos;
1170
1171                 if (pos != 0 && !par.isWordSeparator(pos - 1))
1172                         while (pos != 0 && !par.isWordSeparator(pos - 1))
1173                                 --pos;
1174                 else if (pos != 0 && par.isChar(pos - 1))
1175                         while (pos != 0 && par.isChar(pos - 1))
1176                                 --pos;
1177                 else if (pos != 0 && !par.isSpace(pos - 1)) // non-char inset
1178                         --pos;
1179         }
1180
1181         return setCursor(cur, pit, pos);
1182 }
1183
1184
1185 bool Text::cursorVisLeftOneWord(Cursor & cur)
1186 {
1187         LBUFERR(this == cur.text());
1188
1189         pos_type left_pos, right_pos;
1190         bool left_is_letter, right_is_letter;
1191
1192         Cursor temp_cur = cur;
1193
1194         // always try to move at least once...
1195         while (temp_cur.posVisLeft(true /* skip_inset */)) {
1196
1197                 // collect some information about current cursor position
1198                 temp_cur.getSurroundingPos(left_pos, right_pos);
1199                 left_is_letter =
1200                         (left_pos > -1 ? !temp_cur.paragraph().isWordSeparator(left_pos) : false);
1201                 right_is_letter =
1202                         (right_pos > -1 ? !temp_cur.paragraph().isWordSeparator(right_pos) : false);
1203
1204                 // if we're not at a letter/non-letter boundary, continue moving
1205                 if (left_is_letter == right_is_letter)
1206                         continue;
1207
1208                 // we should stop when we have an LTR word on our right or an RTL word
1209                 // on our left
1210                 if ((left_is_letter && temp_cur.paragraph().getFontSettings(
1211                                 temp_cur.buffer()->params(), left_pos).isRightToLeft())
1212                         || (right_is_letter && !temp_cur.paragraph().getFontSettings(
1213                                 temp_cur.buffer()->params(), right_pos).isRightToLeft()))
1214                         break;
1215         }
1216
1217         return setCursor(cur, temp_cur.pit(), temp_cur.pos(),
1218                                          true, temp_cur.boundary());
1219 }
1220
1221
1222 bool Text::cursorVisRightOneWord(Cursor & cur)
1223 {
1224         LBUFERR(this == cur.text());
1225
1226         pos_type left_pos, right_pos;
1227         bool left_is_letter, right_is_letter;
1228
1229         Cursor temp_cur = cur;
1230
1231         // always try to move at least once...
1232         while (temp_cur.posVisRight(true /* skip_inset */)) {
1233
1234                 // collect some information about current cursor position
1235                 temp_cur.getSurroundingPos(left_pos, right_pos);
1236                 left_is_letter =
1237                         (left_pos > -1 ? !temp_cur.paragraph().isWordSeparator(left_pos) : false);
1238                 right_is_letter =
1239                         (right_pos > -1 ? !temp_cur.paragraph().isWordSeparator(right_pos) : false);
1240
1241                 // if we're not at a letter/non-letter boundary, continue moving
1242                 if (left_is_letter == right_is_letter)
1243                         continue;
1244
1245                 // we should stop when we have an LTR word on our right or an RTL word
1246                 // on our left
1247                 if ((left_is_letter && temp_cur.paragraph().getFontSettings(
1248                                 temp_cur.buffer()->params(),
1249                                 left_pos).isRightToLeft())
1250                         || (right_is_letter && !temp_cur.paragraph().getFontSettings(
1251                                 temp_cur.buffer()->params(),
1252                                 right_pos).isRightToLeft()))
1253                         break;
1254         }
1255
1256         return setCursor(cur, temp_cur.pit(), temp_cur.pos(),
1257                                          true, temp_cur.boundary());
1258 }
1259
1260
1261 void Text::selectWord(Cursor & cur, word_location loc)
1262 {
1263         LBUFERR(this == cur.text());
1264         CursorSlice from = cur.top();
1265         CursorSlice to = cur.top();
1266         getWord(from, to, loc);
1267         if (cur.top() != from)
1268                 setCursor(cur, from.pit(), from.pos());
1269         if (to == from)
1270                 return;
1271         if (!cur.selection())
1272                 cur.resetAnchor();
1273         setCursor(cur, to.pit(), to.pos());
1274         cur.setSelection();
1275         cur.setWordSelection(true);
1276 }
1277
1278
1279 void Text::selectAll(Cursor & cur)
1280 {
1281         LBUFERR(this == cur.text());
1282         if (cur.lastpos() == 0 && cur.lastpit() == 0)
1283                 return;
1284         // If the cursor is at the beginning, make sure the cursor ends there
1285         if (cur.pit() == 0 && cur.pos() == 0) {
1286                 setCursor(cur, cur.lastpit(), getPar(cur.lastpit()).size());
1287                 cur.resetAnchor();
1288                 setCursor(cur, 0, 0);
1289         } else {
1290                 setCursor(cur, 0, 0);
1291                 cur.resetAnchor();
1292                 setCursor(cur, cur.lastpit(), getPar(cur.lastpit()).size());
1293         }
1294         cur.setSelection();
1295 }
1296
1297
1298 // Select the word currently under the cursor when no
1299 // selection is currently set
1300 bool Text::selectWordWhenUnderCursor(Cursor & cur, word_location loc)
1301 {
1302         LBUFERR(this == cur.text());
1303         if (cur.selection())
1304                 return false;
1305         selectWord(cur, loc);
1306         return cur.selection();
1307 }
1308
1309
1310 void Text::acceptOrRejectChanges(Cursor & cur, ChangeOp op)
1311 {
1312         LBUFERR(this == cur.text());
1313
1314         if (!cur.selection()) {
1315                 if (!selectChange(cur))
1316                         return;
1317         }
1318
1319         cur.recordUndoSelection();
1320
1321         pit_type begPit = cur.selectionBegin().pit();
1322         pit_type endPit = cur.selectionEnd().pit();
1323
1324         pos_type begPos = cur.selectionBegin().pos();
1325         pos_type endPos = cur.selectionEnd().pos();
1326
1327         // keep selection info, because endPos becomes invalid after the first loop
1328         bool endsBeforeEndOfPar = (endPos < pars_[endPit].size());
1329
1330         // first, accept/reject changes within each individual paragraph (do not consider end-of-par)
1331         for (pit_type pit = begPit; pit <= endPit; ++pit) {
1332                 pos_type parSize = pars_[pit].size();
1333
1334                 // ignore empty paragraphs; otherwise, an assertion will fail for
1335                 // acceptChanges(bparams, 0, 0) or rejectChanges(bparams, 0, 0)
1336                 if (parSize == 0)
1337                         continue;
1338
1339                 // do not consider first paragraph if the cursor starts at pos size()
1340                 if (pit == begPit && begPos == parSize)
1341                         continue;
1342
1343                 // do not consider last paragraph if the cursor ends at pos 0
1344                 if (pit == endPit && endPos == 0)
1345                         break; // last iteration anyway
1346
1347                 pos_type left  = (pit == begPit ? begPos : 0);
1348                 pos_type right = (pit == endPit ? endPos : parSize);
1349
1350                 if (left == right)
1351                         // there is no change here
1352                         continue;
1353
1354                 if (op == ACCEPT) {
1355                         pars_[pit].acceptChanges(left, right);
1356                 } else {
1357                         pars_[pit].rejectChanges(left, right);
1358                 }
1359         }
1360
1361         // next, accept/reject imaginary end-of-par characters
1362
1363         for (pit_type pit = begPit; pit <= endPit; ++pit) {
1364                 pos_type pos = pars_[pit].size();
1365
1366                 // skip if the selection ends before the end-of-par
1367                 if (pit == endPit && endsBeforeEndOfPar)
1368                         break; // last iteration anyway
1369
1370                 // skip if this is not the last paragraph of the document
1371                 // note: the user should be able to accept/reject the par break of the last par!
1372                 if (pit == endPit && pit + 1 != int(pars_.size()))
1373                         break; // last iteration anway
1374
1375                 if (op == ACCEPT) {
1376                         if (pars_[pit].isInserted(pos)) {
1377                                 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1378                         } else if (pars_[pit].isDeleted(pos)) {
1379                                 if (pit + 1 == int(pars_.size())) {
1380                                         // we cannot remove a par break at the end of the last paragraph;
1381                                         // instead, we mark it unchanged
1382                                         pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1383                                 } else {
1384                                         mergeParagraph(cur.buffer()->params(), pars_, pit);
1385                                         --endPit;
1386                                         --pit;
1387                                 }
1388                         }
1389                 } else {
1390                         if (pars_[pit].isDeleted(pos)) {
1391                                 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1392                         } else if (pars_[pit].isInserted(pos)) {
1393                                 if (pit + 1 == int(pars_.size())) {
1394                                         // we mark the par break at the end of the last paragraph unchanged
1395                                         pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1396                                 } else {
1397                                         mergeParagraph(cur.buffer()->params(), pars_, pit);
1398                                         --endPit;
1399                                         --pit;
1400                                 }
1401                         }
1402                 }
1403         }
1404
1405         // finally, invoke the DEPM
1406         deleteEmptyParagraphMechanism(begPit, endPit, cur.buffer()->params().track_changes);
1407
1408         cur.finishUndo();
1409         cur.clearSelection();
1410         setCursorIntern(cur, begPit, begPos);
1411         cur.screenUpdateFlags(Update::Force);
1412         cur.forceBufferUpdate();
1413 }
1414
1415
1416 void Text::acceptChanges()
1417 {
1418         BufferParams const & bparams = owner_->buffer().params();
1419         lyx::acceptChanges(pars_, bparams);
1420         deleteEmptyParagraphMechanism(0, pars_.size() - 1, bparams.track_changes);
1421 }
1422
1423
1424 void Text::rejectChanges()
1425 {
1426         BufferParams const & bparams = owner_->buffer().params();
1427         pit_type pars_size = static_cast<pit_type>(pars_.size());
1428
1429         // first, reject changes within each individual paragraph
1430         // (do not consider end-of-par)
1431         for (pit_type pit = 0; pit < pars_size; ++pit) {
1432                 if (!pars_[pit].empty())   // prevent assertion failure
1433                         pars_[pit].rejectChanges(0, pars_[pit].size());
1434         }
1435
1436         // next, reject imaginary end-of-par characters
1437         for (pit_type pit = 0; pit < pars_size; ++pit) {
1438                 pos_type pos = pars_[pit].size();
1439
1440                 if (pars_[pit].isDeleted(pos)) {
1441                         pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1442                 } else if (pars_[pit].isInserted(pos)) {
1443                         if (pit == pars_size - 1) {
1444                                 // we mark the par break at the end of the last
1445                                 // paragraph unchanged
1446                                 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1447                         } else {
1448                                 mergeParagraph(bparams, pars_, pit);
1449                                 --pit;
1450                                 --pars_size;
1451                         }
1452                 }
1453         }
1454
1455         // finally, invoke the DEPM
1456         deleteEmptyParagraphMechanism(0, pars_size - 1, bparams.track_changes);
1457 }
1458
1459
1460 void Text::deleteWordForward(Cursor & cur)
1461 {
1462         LBUFERR(this == cur.text());
1463         if (cur.lastpos() == 0)
1464                 cursorForward(cur);
1465         else {
1466                 cur.resetAnchor();
1467                 cur.setSelection(true);
1468                 cursorForwardOneWord(cur);
1469                 cur.setSelection();
1470                 cutSelection(cur, true, false);
1471                 cur.checkBufferStructure();
1472         }
1473 }
1474
1475
1476 void Text::deleteWordBackward(Cursor & cur)
1477 {
1478         LBUFERR(this == cur.text());
1479         if (cur.lastpos() == 0)
1480                 cursorBackward(cur);
1481         else {
1482                 cur.resetAnchor();
1483                 cur.setSelection(true);
1484                 cursorBackwardOneWord(cur);
1485                 cur.setSelection();
1486                 cutSelection(cur, true, false);
1487                 cur.checkBufferStructure();
1488         }
1489 }
1490
1491
1492 // Kill to end of line.
1493 void Text::changeCase(Cursor & cur, TextCase action)
1494 {
1495         LBUFERR(this == cur.text());
1496         CursorSlice from;
1497         CursorSlice to;
1498
1499         bool gotsel = false;
1500         if (cur.selection()) {
1501                 from = cur.selBegin();
1502                 to = cur.selEnd();
1503                 gotsel = true;
1504         } else {
1505                 from = cur.top();
1506                 getWord(from, to, PARTIAL_WORD);
1507                 cursorForwardOneWord(cur);
1508         }
1509
1510         cur.recordUndoSelection();
1511
1512         pit_type begPit = from.pit();
1513         pit_type endPit = to.pit();
1514
1515         pos_type begPos = from.pos();
1516         pos_type endPos = to.pos();
1517
1518         pos_type right = 0; // needed after the for loop
1519
1520         for (pit_type pit = begPit; pit <= endPit; ++pit) {
1521                 Paragraph & par = pars_[pit];
1522                 pos_type const pos = (pit == begPit ? begPos : 0);
1523                 right = (pit == endPit ? endPos : par.size());
1524                 par.changeCase(cur.buffer()->params(), pos, right, action);
1525         }
1526
1527         // the selection may have changed due to logically-only deleted chars
1528         if (gotsel) {
1529                 setCursor(cur, begPit, begPos);
1530                 cur.resetAnchor();
1531                 setCursor(cur, endPit, right);
1532                 cur.setSelection();
1533         } else
1534                 setCursor(cur, endPit, right);
1535
1536         cur.checkBufferStructure();
1537 }
1538
1539
1540 bool Text::handleBibitems(Cursor & cur)
1541 {
1542         if (cur.paragraph().layout().labeltype != LABEL_BIBLIO)
1543                 return false;
1544
1545         if (cur.pos() != 0)
1546                 return false;
1547
1548         BufferParams const & bufparams = cur.buffer()->params();
1549         Paragraph const & par = cur.paragraph();
1550         Cursor prevcur = cur;
1551         if (cur.pit() > 0) {
1552                 --prevcur.pit();
1553                 prevcur.pos() = prevcur.lastpos();
1554         }
1555         Paragraph const & prevpar = prevcur.paragraph();
1556
1557         // if a bibitem is deleted, merge with previous paragraph
1558         // if this is a bibliography item as well
1559         if (cur.pit() > 0 && par.layout() == prevpar.layout()) {
1560                 cur.recordUndo(prevcur.pit());
1561                 mergeParagraph(bufparams, cur.text()->paragraphs(),
1562                                                         prevcur.pit());
1563                 cur.forceBufferUpdate();
1564                 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1565                 cur.screenUpdateFlags(Update::Force);
1566                 return true;
1567         }
1568
1569         // otherwise reset to default
1570         cur.paragraph().setPlainOrDefaultLayout(bufparams.documentClass());
1571         return true;
1572 }
1573
1574
1575 bool Text::erase(Cursor & cur)
1576 {
1577         LASSERT(this == cur.text(), return false);
1578         bool needsUpdate = false;
1579         Paragraph & par = cur.paragraph();
1580
1581         if (cur.pos() != cur.lastpos()) {
1582                 // this is the code for a normal delete, not pasting
1583                 // any paragraphs
1584                 cur.recordUndo(DELETE_UNDO);
1585                 bool const was_inset = cur.paragraph().isInset(cur.pos());
1586                 if(!par.eraseChar(cur.pos(), cur.buffer()->params().track_changes))
1587                         // the character has been logically deleted only => skip it
1588                         cur.top().forwardPos();
1589
1590                 if (was_inset)
1591                         cur.forceBufferUpdate();
1592                 else
1593                         cur.checkBufferStructure();
1594                 needsUpdate = true;
1595         } else {
1596                 if (cur.pit() == cur.lastpit())
1597                         return dissolveInset(cur);
1598
1599                 if (!par.isMergedOnEndOfParDeletion(cur.buffer()->params().track_changes)) {
1600                         par.setChange(cur.pos(), Change(Change::DELETED));
1601                         cur.forwardPos();
1602                         needsUpdate = true;
1603                 } else {
1604                         setCursorIntern(cur, cur.pit() + 1, 0);
1605                         needsUpdate = backspacePos0(cur);
1606                 }
1607         }
1608
1609         needsUpdate |= handleBibitems(cur);
1610
1611         if (needsUpdate) {
1612                 // Make sure the cursor is correct. Is this really needed?
1613                 // No, not really... at least not here!
1614                 cur.text()->setCursor(cur.top(), cur.pit(), cur.pos());
1615                 cur.checkBufferStructure();
1616         }
1617
1618         return needsUpdate;
1619 }
1620
1621
1622 bool Text::backspacePos0(Cursor & cur)
1623 {
1624         LBUFERR(this == cur.text());
1625         if (cur.pit() == 0)
1626                 return false;
1627
1628         bool needsUpdate = false;
1629
1630         BufferParams const & bufparams = cur.buffer()->params();
1631         DocumentClass const & tclass = bufparams.documentClass();
1632         ParagraphList & plist = cur.text()->paragraphs();
1633         Paragraph const & par = cur.paragraph();
1634         Cursor prevcur = cur;
1635         --prevcur.pit();
1636         prevcur.pos() = prevcur.lastpos();
1637         Paragraph const & prevpar = prevcur.paragraph();
1638
1639         // is it an empty paragraph?
1640         if (cur.lastpos() == 0
1641             || (cur.lastpos() == 1 && par.isSeparator(0))) {
1642                 cur.recordUndo(prevcur.pit());
1643                 plist.erase(next(plist.begin(), cur.pit()));
1644                 needsUpdate = true;
1645         }
1646         // is previous par empty?
1647         else if (prevcur.lastpos() == 0
1648                  || (prevcur.lastpos() == 1 && prevpar.isSeparator(0))) {
1649                 cur.recordUndo(prevcur.pit());
1650                 plist.erase(next(plist.begin(), prevcur.pit()));
1651                 needsUpdate = true;
1652         }
1653         // Pasting is not allowed, if the paragraphs have different
1654         // layouts. I think it is a real bug of all other
1655         // word processors to allow it. It confuses the user.
1656         // Correction: Pasting is always allowed with standard-layout
1657         // or the empty layout.
1658         else if (par.layout() == prevpar.layout()
1659                  || tclass.isDefaultLayout(par.layout())
1660                  || tclass.isPlainLayout(par.layout())) {
1661                 cur.recordUndo(prevcur.pit());
1662                 mergeParagraph(bufparams, plist, prevcur.pit());
1663                 needsUpdate = true;
1664         }
1665
1666         if (needsUpdate) {
1667                 cur.forceBufferUpdate();
1668                 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1669         }
1670
1671         return needsUpdate;
1672 }
1673
1674
1675 bool Text::backspace(Cursor & cur)
1676 {
1677         LBUFERR(this == cur.text());
1678         bool needsUpdate = false;
1679         if (cur.pos() == 0) {
1680                 if (cur.pit() == 0)
1681                         return dissolveInset(cur);
1682
1683                 Cursor prev_cur = cur;
1684                 --prev_cur.pit();
1685
1686                 if (!prev_cur.paragraph().isMergedOnEndOfParDeletion(cur.buffer()->params().track_changes)) {
1687                         cur.recordUndo(prev_cur.pit(), prev_cur.pit());
1688                         prev_cur.paragraph().setChange(prev_cur.lastpos(), Change(Change::DELETED));
1689                         setCursorIntern(cur, prev_cur.pit(), prev_cur.lastpos());
1690                         return true;
1691                 }
1692                 // The cursor is at the beginning of a paragraph, so
1693                 // the backspace will collapse two paragraphs into one.
1694                 needsUpdate = backspacePos0(cur);
1695
1696         } else {
1697                 // this is the code for a normal backspace, not pasting
1698                 // any paragraphs
1699                 cur.recordUndo(DELETE_UNDO);
1700                 // We used to do cursorBackwardIntern() here, but it is
1701                 // not a good idea since it triggers the auto-delete
1702                 // mechanism. So we do a cursorBackwardIntern()-lite,
1703                 // without the dreaded mechanism. (JMarc)
1704                 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1705                                 false, cur.boundary());
1706                 bool const was_inset = cur.paragraph().isInset(cur.pos());
1707                 cur.paragraph().eraseChar(cur.pos(), cur.buffer()->params().track_changes);
1708                 if (was_inset)
1709                         cur.forceBufferUpdate();
1710                 else
1711                         cur.checkBufferStructure();
1712         }
1713
1714         if (cur.pos() == cur.lastpos())
1715                 cur.setCurrentFont();
1716
1717         needsUpdate |= handleBibitems(cur);
1718
1719         // A singlePar update is not enough in this case.
1720 //              cur.screenUpdateFlags(Update::Force);
1721         setCursor(cur.top(), cur.pit(), cur.pos());
1722
1723         return needsUpdate;
1724 }
1725
1726
1727 bool Text::dissolveInset(Cursor & cur)
1728 {
1729         LASSERT(this == cur.text(), return false);
1730
1731         if (isMainText() || cur.inset().nargs() != 1)
1732                 return false;
1733
1734         cur.recordUndoInset();
1735         cur.setMark(false);
1736         cur.selHandle(false);
1737         // save position
1738         pos_type spos = cur.pos();
1739         pit_type spit = cur.pit();
1740         ParagraphList plist;
1741         if (cur.lastpit() != 0 || cur.lastpos() != 0)
1742                 plist = paragraphs();
1743         cur.popBackward();
1744         // store cursor offset
1745         if (spit == 0)
1746                 spos += cur.pos();
1747         spit += cur.pit();
1748         Buffer & b = *cur.buffer();
1749         cur.paragraph().eraseChar(cur.pos(), b.params().track_changes);
1750
1751         if (!plist.empty()) {
1752                 // see bug 7319
1753                 // we clear the cache so that we won't get conflicts with labels
1754                 // that get pasted into the buffer. we should update this before
1755                 // its being empty matters. if not (i.e., if we encounter bugs),
1756                 // then this should instead be:
1757                 //        cur.buffer().updateBuffer();
1758                 // but we'll try the cheaper solution here.
1759                 cur.buffer()->clearReferenceCache();
1760
1761                 // ERT paragraphs have the Language latex_language.
1762                 // This is invalid outside of ERT, so we need to
1763                 // change it to the buffer language.
1764                 ParagraphList::iterator it = plist.begin();
1765                 ParagraphList::iterator it_end = plist.end();
1766                 for (; it != it_end; ++it)
1767                         it->changeLanguage(b.params(), latex_language, b.language());
1768
1769                 pasteParagraphList(cur, plist, b.params().documentClassPtr(),
1770                                    b.errorList("Paste"));
1771                 // restore position
1772                 cur.pit() = min(cur.lastpit(), spit);
1773                 cur.pos() = min(cur.lastpos(), spos);
1774         }
1775
1776         cur.forceBufferUpdate();
1777
1778         // Ensure the current language is set correctly (bug 6292)
1779         cur.text()->setCursor(cur, cur.pit(), cur.pos());
1780         cur.clearSelection();
1781         cur.resetAnchor();
1782         return true;
1783 }
1784
1785
1786 void Text::getWord(CursorSlice & from, CursorSlice & to,
1787         word_location const loc) const
1788 {
1789         to = from;
1790         pars_[to.pit()].locateWord(from.pos(), to.pos(), loc);
1791 }
1792
1793
1794 void Text::write(ostream & os) const
1795 {
1796         Buffer const & buf = owner_->buffer();
1797         ParagraphList::const_iterator pit = paragraphs().begin();
1798         ParagraphList::const_iterator end = paragraphs().end();
1799         depth_type dth = 0;
1800         for (; pit != end; ++pit)
1801                 pit->write(os, buf.params(), dth);
1802
1803         // Close begin_deeper
1804         for(; dth > 0; --dth)
1805                 os << "\n\\end_deeper";
1806 }
1807
1808
1809 bool Text::read(Lexer & lex,
1810                 ErrorList & errorList, InsetText * insetPtr)
1811 {
1812         Buffer const & buf = owner_->buffer();
1813         depth_type depth = 0;
1814         bool res = true;
1815
1816         while (lex.isOK()) {
1817                 lex.nextToken();
1818                 string const token = lex.getString();
1819
1820                 if (token.empty())
1821                         continue;
1822
1823                 if (token == "\\end_inset")
1824                         break;
1825
1826                 if (token == "\\end_body")
1827                         continue;
1828
1829                 if (token == "\\begin_body")
1830                         continue;
1831
1832                 if (token == "\\end_document") {
1833                         res = false;
1834                         break;
1835                 }
1836
1837                 if (token == "\\begin_layout") {
1838                         lex.pushToken(token);
1839
1840                         Paragraph par;
1841                         par.setInsetOwner(insetPtr);
1842                         par.params().depth(depth);
1843                         par.setFont(0, Font(inherit_font, buf.params().language));
1844                         pars_.push_back(par);
1845                         readParagraph(pars_.back(), lex, errorList);
1846
1847                         // register the words in the global word list
1848                         pars_.back().updateWords();
1849                 } else if (token == "\\begin_deeper") {
1850                         ++depth;
1851                 } else if (token == "\\end_deeper") {
1852                         if (!depth)
1853                                 lex.printError("\\end_deeper: " "depth is already null");
1854                         else
1855                                 --depth;
1856                 } else {
1857                         LYXERR0("Handling unknown body token: `" << token << '\'');
1858                 }
1859         }
1860
1861         // avoid a crash on weird documents (bug 4859)
1862         if (pars_.empty()) {
1863                 Paragraph par;
1864                 par.setInsetOwner(insetPtr);
1865                 par.params().depth(depth);
1866                 par.setFont(0, Font(inherit_font,
1867                                     buf.params().language));
1868                 par.setPlainOrDefaultLayout(buf.params().documentClass());
1869                 pars_.push_back(par);
1870         }
1871
1872         return res;
1873 }
1874
1875
1876 // Returns the current font and depth as a message.
1877 docstring Text::currentState(Cursor const & cur) const
1878 {
1879         LBUFERR(this == cur.text());
1880         Buffer & buf = *cur.buffer();
1881         Paragraph const & par = cur.paragraph();
1882         odocstringstream os;
1883
1884         if (buf.params().track_changes)
1885                 os << _("[Change Tracking] ");
1886
1887         Change change = par.lookupChange(cur.pos());
1888
1889         if (change.changed()) {
1890                 Author const & a = buf.params().authors().get(change.author);
1891                 os << _("Change: ") << a.name();
1892                 if (!a.email().empty())
1893                         os << " (" << a.email() << ")";
1894                 // FIXME ctime is english, we should translate that
1895                 os << _(" at ") << ctime(&change.changetime);
1896                 os << " : ";
1897         }
1898
1899         // I think we should only show changes from the default
1900         // font. (Asger)
1901         // No, from the document font (MV)
1902         Font font = cur.real_current_font;
1903         font.fontInfo().reduce(buf.params().getFont().fontInfo());
1904
1905         os << bformat(_("Font: %1$s"), font.stateText(&buf.params()));
1906
1907         // The paragraph depth
1908         int depth = cur.paragraph().getDepth();
1909         if (depth > 0)
1910                 os << bformat(_(", Depth: %1$d"), depth);
1911
1912         // The paragraph spacing, but only if different from
1913         // buffer spacing.
1914         Spacing const & spacing = par.params().spacing();
1915         if (!spacing.isDefault()) {
1916                 os << _(", Spacing: ");
1917                 switch (spacing.getSpace()) {
1918                 case Spacing::Single:
1919                         os << _("Single");
1920                         break;
1921                 case Spacing::Onehalf:
1922                         os << _("OneHalf");
1923                         break;
1924                 case Spacing::Double:
1925                         os << _("Double");
1926                         break;
1927                 case Spacing::Other:
1928                         os << _("Other (") << from_ascii(spacing.getValueAsString()) << ')';
1929                         break;
1930                 case Spacing::Default:
1931                         // should never happen, do nothing
1932                         break;
1933                 }
1934         }
1935
1936 #ifdef DEVEL_VERSION
1937         os << _(", Inset: ") << &cur.inset();
1938         os << _(", Paragraph: ") << cur.pit();
1939         os << _(", Id: ") << par.id();
1940         os << _(", Position: ") << cur.pos();
1941         // FIXME: Why is the check for par.size() needed?
1942         // We are called with cur.pos() == par.size() quite often.
1943         if (!par.empty() && cur.pos() < par.size()) {
1944                 // Force output of code point, not character
1945                 size_t const c = par.getChar(cur.pos());
1946                 os << _(", Char: 0x") << hex << c;
1947         }
1948         os << _(", Boundary: ") << cur.boundary();
1949 //      Row & row = cur.textRow();
1950 //      os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
1951 #endif
1952         return os.str();
1953 }
1954
1955
1956 docstring Text::getPossibleLabel(Cursor const & cur) const
1957 {
1958         pit_type pit = cur.pit();
1959
1960         Layout const * layout = &(pars_[pit].layout());
1961
1962         docstring text;
1963         docstring par_text = pars_[pit].asString();
1964
1965         // The return string of math matrices might contain linebreaks
1966         par_text = subst(par_text, '\n', '-');
1967         int const numwords = 3;
1968         for (int i = 0; i < numwords; ++i) {
1969                 if (par_text.empty())
1970                         break;
1971                 docstring head;
1972                 par_text = split(par_text, head, ' ');
1973                 // Is it legal to use spaces in labels ?
1974                 if (i > 0)
1975                         text += '-';
1976                 text += head;
1977         }
1978
1979         // Make sure it isn't too long
1980         unsigned int const max_label_length = 32;
1981         if (text.size() > max_label_length)
1982                 text.resize(max_label_length);
1983
1984         // Will contain the label prefix.
1985         docstring name;
1986
1987         // For section, subsection, etc...
1988         if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
1989                 Layout const * layout2 = &(pars_[pit - 1].layout());
1990                 if (layout2->latextype != LATEX_PARAGRAPH) {
1991                         --pit;
1992                         layout = layout2;
1993                 }
1994         }
1995         if (layout->latextype != LATEX_PARAGRAPH)
1996                 name = layout->refprefix;
1997
1998         // For captions, we just take the caption type
1999         Inset * caption_inset = cur.innerInsetOfType(CAPTION_CODE);
2000         if (caption_inset) {
2001                 string const & ftype = static_cast<InsetCaption *>(caption_inset)->floattype();
2002                 FloatList const & fl = cur.buffer()->params().documentClass().floats();
2003                 if (fl.typeExist(ftype)) {
2004                         Floating const & flt = fl.getType(ftype);
2005                         name = from_utf8(flt.refPrefix());
2006                 }
2007                 if (name.empty())
2008                         name = from_utf8(ftype.substr(0,3));
2009         }
2010
2011         // If none of the above worked, see if the inset knows.
2012         if (name.empty()) {
2013                 InsetLayout const & il = cur.inset().getLayout();
2014                 name = il.refprefix();
2015         }
2016
2017         if (!name.empty())
2018                 text = name + ':' + text;
2019
2020         // We need a unique label
2021         docstring label = text;
2022         int i = 1;
2023         while (cur.buffer()->insetLabel(label)) {
2024                         label = text + '-' + convert<docstring>(i);
2025                         ++i;
2026                 }
2027
2028         return label;
2029 }
2030
2031
2032 docstring Text::asString(int options) const
2033 {
2034         return asString(0, pars_.size(), options);
2035 }
2036
2037
2038 docstring Text::asString(pit_type beg, pit_type end, int options) const
2039 {
2040         size_t i = size_t(beg);
2041         docstring str = pars_[i].asString(options);
2042         for (++i; i != size_t(end); ++i) {
2043                 str += '\n';
2044                 str += pars_[i].asString(options);
2045         }
2046         return str;
2047 }
2048
2049
2050 void Text::forOutliner(docstring & os, size_t maxlen, bool shorten) const
2051 {
2052         if (maxlen == 0)
2053                 maxlen = std::numeric_limits<std::size_t>::max();
2054         else
2055                 LASSERT(maxlen >= 8, maxlen = TOC_ENTRY_LENGTH);
2056         for (size_t i = 0; i != pars_.size() && os.length() < maxlen; ++i)
2057                 pars_[i].forOutliner(os, maxlen);
2058         if (shorten && os.length() >= maxlen)
2059                 os = os.substr(0, maxlen - 3) + from_ascii("...");
2060 }
2061
2062
2063 void Text::charsTranspose(Cursor & cur)
2064 {
2065         LBUFERR(this == cur.text());
2066
2067         pos_type pos = cur.pos();
2068
2069         // If cursor is at beginning or end of paragraph, do nothing.
2070         if (pos == cur.lastpos() || pos == 0)
2071                 return;
2072
2073         Paragraph & par = cur.paragraph();
2074
2075         // Get the positions of the characters to be transposed.
2076         pos_type pos1 = pos - 1;
2077         pos_type pos2 = pos;
2078
2079         // In change tracking mode, ignore deleted characters.
2080         while (pos2 < cur.lastpos() && par.isDeleted(pos2))
2081                 ++pos2;
2082         if (pos2 == cur.lastpos())
2083                 return;
2084
2085         while (pos1 >= 0 && par.isDeleted(pos1))
2086                 --pos1;
2087         if (pos1 < 0)
2088                 return;
2089
2090         // Don't do anything if one of the "characters" is not regular text.
2091         if (par.isInset(pos1) || par.isInset(pos2))
2092                 return;
2093
2094         // Store the characters to be transposed (including font information).
2095         char_type const char1 = par.getChar(pos1);
2096         Font const font1 =
2097                 par.getFontSettings(cur.buffer()->params(), pos1);
2098
2099         char_type const char2 = par.getChar(pos2);
2100         Font const font2 =
2101                 par.getFontSettings(cur.buffer()->params(), pos2);
2102
2103         // And finally, we are ready to perform the transposition.
2104         // Track the changes if Change Tracking is enabled.
2105         bool const trackChanges = cur.buffer()->params().track_changes;
2106
2107         cur.recordUndo();
2108
2109         par.eraseChar(pos2, trackChanges);
2110         par.eraseChar(pos1, trackChanges);
2111         par.insertChar(pos1, char2, font2, trackChanges);
2112         par.insertChar(pos2, char1, font1, trackChanges);
2113
2114         cur.checkBufferStructure();
2115
2116         // After the transposition, move cursor to after the transposition.
2117         setCursor(cur, cur.pit(), pos2);
2118         cur.forwardPos();
2119 }
2120
2121
2122 DocIterator Text::macrocontextPosition() const
2123 {
2124         return macrocontext_position_;
2125 }
2126
2127
2128 void Text::setMacrocontextPosition(DocIterator const & pos)
2129 {
2130         macrocontext_position_ = pos;
2131 }
2132
2133
2134 docstring Text::previousWord(CursorSlice const & sl) const
2135 {
2136         CursorSlice from = sl;
2137         CursorSlice to = sl;
2138         getWord(from, to, PREVIOUS_WORD);
2139         if (sl == from || to == from)
2140                 return docstring();
2141
2142         Paragraph const & par = sl.paragraph();
2143         return par.asString(from.pos(), to.pos());
2144 }
2145
2146
2147 bool Text::completionSupported(Cursor const & cur) const
2148 {
2149         Paragraph const & par = cur.paragraph();
2150         return cur.pos() > 0
2151                 && (cur.pos() >= par.size() || par.isWordSeparator(cur.pos()))
2152                 && !par.isWordSeparator(cur.pos() - 1);
2153 }
2154
2155
2156 CompletionList const * Text::createCompletionList(Cursor const & cur) const
2157 {
2158         WordList const * list = theWordList(cur.getFont().language()->lang());
2159         return new TextCompletionList(cur, list);
2160 }
2161
2162
2163 bool Text::insertCompletion(Cursor & cur, docstring const & s, bool /*finished*/)
2164 {
2165         LBUFERR(cur.bv().cursor() == cur);
2166         cur.insert(s);
2167         cur.bv().cursor() = cur;
2168         if (!(cur.result().screenUpdate() & Update::Force))
2169                 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
2170         return true;
2171 }
2172
2173
2174 docstring Text::completionPrefix(Cursor const & cur) const
2175 {
2176         return previousWord(cur.top());
2177 }
2178
2179 } // namespace lyx