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