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