]> git.lyx.org Git - lyx.git/blob - src/Text.cpp
typo
[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         if (inset().allowMultiPar())
623                 par.setChange(par.size(), change);
624
625         // Initialize begin_of_body_ on load; redoParagraph maintains
626         par.setBeginOfBody();
627
628         // mark paragraph for spell checking on load
629         // par.requestSpellCheck();
630 }
631
632
633 class TextCompletionList : public CompletionList
634 {
635 public:
636         ///
637         TextCompletionList(Cursor const & cur, WordList const & list)
638                 : buffer_(cur.buffer()), list_(list)
639         {}
640         ///
641         virtual ~TextCompletionList() {}
642
643         ///
644         virtual bool sorted() const { return true; }
645         ///
646         virtual size_t size() const
647         {
648                 return list_.size();
649         }
650         ///
651         virtual docstring const & data(size_t idx) const
652         {
653                 return list_.word(idx);
654         }
655
656 private:
657         ///
658         Buffer const * buffer_;
659         ///
660         WordList const & list_;
661 };
662
663
664 bool Text::empty() const
665 {
666         return pars_.empty() || (pars_.size() == 1 && pars_[0].empty()
667                 // FIXME: Should we consider the labeled type as empty too?
668                 && pars_[0].layout().labeltype == LABEL_NO_LABEL);
669 }
670
671
672 double Text::spacing(Paragraph const & par) const
673 {
674         if (par.params().spacing().isDefault())
675                 return owner_->buffer().params().spacing().getValue();
676         return par.params().spacing().getValue();
677 }
678
679
680 /**
681  * This breaks a paragraph at the specified position.
682  * The new paragraph will:
683  * - Decrease depth by one (or change layout to default layout) when
684  *    keep_layout == false
685  * - keep current depth and layout when keep_layout == true
686  */
687 static void breakParagraph(Text & text, pit_type par_offset, pos_type pos,
688                     bool keep_layout)
689 {
690         BufferParams const & bparams = text.inset().buffer().params();
691         ParagraphList & pars = text.paragraphs();
692         // create a new paragraph, and insert into the list
693         ParagraphList::iterator tmp =
694                 pars.insert(pars.iterator_at(par_offset + 1), Paragraph());
695
696         Paragraph & par = pars[par_offset];
697
698         // remember to set the inset_owner
699         tmp->setInsetOwner(&par.inInset());
700         // without doing that we get a crash when typing <Return> at the
701         // end of a paragraph
702         tmp->setPlainOrDefaultLayout(bparams.documentClass());
703
704         if (keep_layout) {
705                 tmp->setLayout(par.layout());
706                 tmp->setLabelWidthString(par.params().labelWidthString());
707                 tmp->params().depth(par.params().depth());
708         } else if (par.params().depth() > 0) {
709                 Paragraph const & hook = pars[text.outerHook(par_offset)];
710                 tmp->setLayout(hook.layout());
711                 // not sure the line below is useful
712                 tmp->setLabelWidthString(par.params().labelWidthString());
713                 tmp->params().depth(hook.params().depth());
714         }
715
716         bool const isempty = (par.allowEmpty() && par.empty());
717
718         if (!isempty && (par.size() > pos || par.empty())) {
719                 tmp->setLayout(par.layout());
720                 tmp->params().align(par.params().align());
721                 tmp->setLabelWidthString(par.params().labelWidthString());
722
723                 tmp->params().depth(par.params().depth());
724                 tmp->params().noindent(par.params().noindent());
725                 tmp->params().spacing(par.params().spacing());
726
727                 // move everything behind the break position
728                 // to the new paragraph
729
730                 /* Note: if !keepempty, empty() == true, then we reach
731                  * here with size() == 0. So pos_end becomes - 1. This
732                  * doesn't cause problems because both loops below
733                  * enforce pos <= pos_end and 0 <= pos
734                  */
735                 pos_type pos_end = par.size() - 1;
736
737                 for (pos_type i = pos, j = 0; i <= pos_end; ++i) {
738                         if (moveItem(par, pos, *tmp, j, bparams)) {
739                                 ++j;
740                         }
741                 }
742         }
743
744         // Move over the end-of-par change information
745         tmp->setChange(tmp->size(), par.lookupChange(par.size()));
746         par.setChange(par.size(), Change(bparams.track_changes ?
747                                            Change::INSERTED : Change::UNCHANGED));
748
749         if (pos) {
750                 // Make sure that we keep the language when
751                 // breaking paragraph.
752                 if (tmp->empty()) {
753                         Font changed = tmp->getFirstFontSettings(bparams);
754                         Font const & old = par.getFontSettings(bparams, par.size());
755                         changed.setLanguage(old.language());
756                         tmp->setFont(0, changed);
757                 }
758
759                 return;
760         }
761
762         if (!isempty) {
763                 bool const soa = par.params().startOfAppendix();
764                 par.params().clear();
765                 // do not lose start of appendix marker (bug 4212)
766                 par.params().startOfAppendix(soa);
767                 par.setPlainOrDefaultLayout(bparams.documentClass());
768         }
769
770         if (keep_layout) {
771                 par.setLayout(tmp->layout());
772                 par.setLabelWidthString(tmp->params().labelWidthString());
773                 par.params().depth(tmp->params().depth());
774         }
775 }
776
777
778 void Text::breakParagraph(Cursor & cur, bool inverse_logic)
779 {
780         LBUFERR(this == cur.text());
781
782         Paragraph & cpar = cur.paragraph();
783         pit_type cpit = cur.pit();
784
785         DocumentClass const & tclass = cur.buffer()->params().documentClass();
786         Layout const & layout = cpar.layout();
787
788         if (cur.lastpos() == 0 && !cpar.allowEmpty()) {
789                 if (changeDepthAllowed(cur, DEC_DEPTH)) {
790                         changeDepth(cur, DEC_DEPTH);
791                         pit_type const prev = depthHook(cpit, cpar.getDepth());
792                         docstring const & lay = pars_[prev].layout().name();
793                         if (lay != layout.name())
794                                 setLayout(cur, lay);
795                 } else {
796                         docstring const & lay = cur.paragraph().usePlainLayout()
797                             ? tclass.plainLayoutName() : tclass.defaultLayoutName();
798                         if (lay != layout.name())
799                                 setLayout(cur, lay);
800                 }
801                 return;
802         }
803
804         cur.recordUndo();
805
806         // Always break behind a space
807         // It is better to erase the space (Dekel)
808         if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
809                 cpar.eraseChar(cur.pos(), cur.buffer()->params().track_changes);
810
811         // What should the layout for the new paragraph be?
812         bool keep_layout = layout.isEnvironment()
813                 || (layout.isParagraph() && layout.parbreak_is_newline);
814         if (inverse_logic)
815                 keep_layout = !keep_layout;
816
817         // We need to remember this before we break the paragraph, because
818         // that invalidates the layout variable
819         bool sensitive = layout.labeltype == LABEL_SENSITIVE;
820
821         // we need to set this before we insert the paragraph.
822         bool const isempty = cpar.allowEmpty() && cpar.empty();
823
824         lyx::breakParagraph(*this, cpit, cur.pos(), keep_layout);
825
826         // After this, neither paragraph contains any rows!
827
828         cpit = cur.pit();
829         pit_type next_par = cpit + 1;
830
831         // well this is the caption hack since one caption is really enough
832         if (sensitive) {
833                 if (cur.pos() == 0)
834                         // set to standard-layout
835                 //FIXME Check if this should be plainLayout() in some cases
836                         pars_[cpit].applyLayout(tclass.defaultLayout());
837                 else
838                         // set to standard-layout
839                         //FIXME Check if this should be plainLayout() in some cases
840                         pars_[next_par].applyLayout(tclass.defaultLayout());
841         }
842
843         while (!pars_[next_par].empty() && pars_[next_par].isNewline(0)) {
844                 if (!pars_[next_par].eraseChar(0, cur.buffer()->params().track_changes))
845                         break; // the character couldn't be deleted physically due to change tracking
846         }
847
848         // A singlePar update is not enough in this case.
849         cur.screenUpdateFlags(Update::Force);
850         cur.forceBufferUpdate();
851
852         // This check is necessary. Otherwise the new empty paragraph will
853         // be deleted automatically. And it is more friendly for the user!
854         if (cur.pos() != 0 || isempty)
855                 setCursor(cur, cur.pit() + 1, 0);
856         else
857                 setCursor(cur, cur.pit(), 0);
858 }
859
860
861 // needed to insert the selection
862 void Text::insertStringAsLines(Cursor & cur, docstring const & str,
863                 Font const & font)
864 {
865         BufferParams const & bparams = owner_->buffer().params();
866         pit_type pit = cur.pit();
867         pos_type pos = cur.pos();
868
869         // The special chars we handle
870         map<wchar_t, InsetSpecialChar::Kind> specialchars;
871         specialchars[0x200c] = InsetSpecialChar::LIGATURE_BREAK;
872         specialchars[0x200b] = InsetSpecialChar::ALLOWBREAK;
873         specialchars[0x2026] = InsetSpecialChar::LDOTS;
874         specialchars[0x2011] = InsetSpecialChar::NOBREAKDASH;
875
876         // insert the string, don't insert doublespace
877         bool space_inserted = true;
878         for (auto const & ch : str) {
879                 Paragraph & par = pars_[pit];
880                 if (ch == '\n') {
881                         if (inset().allowMultiPar() && (!par.empty() || par.allowEmpty())) {
882                                 lyx::breakParagraph(*this, pit, pos,
883                                         par.layout().isEnvironment());
884                                 ++pit;
885                                 pos = 0;
886                                 space_inserted = true;
887                         } else {
888                                 continue;
889                         }
890                 // do not insert consecutive spaces if !free_spacing
891                 } else if ((ch == ' ' || ch == '\t') &&
892                            space_inserted && !par.isFreeSpacing()) {
893                         continue;
894                 } else if (ch == '\t') {
895                         if (!par.isFreeSpacing()) {
896                                 // tabs are like spaces here
897                                 par.insertChar(pos, ' ', font, bparams.track_changes);
898                                 ++pos;
899                                 space_inserted = true;
900                         } else {
901                                 par.insertChar(pos, ch, font, bparams.track_changes);
902                                 ++pos;
903                                 space_inserted = true;
904                         }
905                 } else if (specialchars.find(ch) != specialchars.end()) {
906                         par.insertInset(pos, new InsetSpecialChar(specialchars.find(ch)->second),
907                                         font, bparams.track_changes ?
908                                                 Change(Change::INSERTED)
909                                               : Change(Change::UNCHANGED));
910                         ++pos;
911                         space_inserted = false;
912                 } else if (!isPrintable(ch)) {
913                         // Ignore (other) unprintables
914                         continue;
915                 } else {
916                         // just insert the character
917                         par.insertChar(pos, ch, font, bparams.track_changes);
918                         ++pos;
919                         space_inserted = (ch == ' ');
920                 }
921         }
922         setCursor(cur, pit, pos);
923 }
924
925
926 // turn double CR to single CR, others are converted into one
927 // blank. Then insertStringAsLines is called
928 void Text::insertStringAsParagraphs(Cursor & cur, docstring const & str,
929                 Font const & font)
930 {
931         docstring linestr = str;
932         bool newline_inserted = false;
933
934         for (string::size_type i = 0, siz = linestr.size(); i < siz; ++i) {
935                 if (linestr[i] == '\n') {
936                         if (newline_inserted) {
937                                 // we know that \r will be ignored by
938                                 // insertStringAsLines. Of course, it is a dirty
939                                 // trick, but it works...
940                                 linestr[i - 1] = '\r';
941                                 linestr[i] = '\n';
942                         } else {
943                                 linestr[i] = ' ';
944                                 newline_inserted = true;
945                         }
946                 } else if (isPrintable(linestr[i])) {
947                         newline_inserted = false;
948                 }
949         }
950         insertStringAsLines(cur, linestr, font);
951 }
952
953
954 namespace {
955
956 bool canInsertChar(Cursor const & cur, char_type c)
957 {
958         Paragraph const & par = cur.paragraph();
959         // If not in free spacing mode, check if there will be two blanks together or a blank at
960         // the beginning of a paragraph.
961         if (!par.isFreeSpacing() && isLineSeparatorChar(c)) {
962                 if (cur.pos() == 0) {
963                         cur.message(_(
964                                         "You cannot insert a space at the "
965                                         "beginning of a paragraph. Please read the Tutorial."));
966                         return false;
967                 }
968                 // If something is wrong, ignore this character.
969                 LASSERT(cur.pos() > 0, return false);
970                 if ((par.isLineSeparator(cur.pos() - 1) || par.isNewline(cur.pos() - 1))
971                                 && !par.isDeleted(cur.pos() - 1)) {
972                         cur.message(_(
973                                         "You cannot type two spaces this way. "
974                                         "Please read the Tutorial."));
975                         return false;
976                 }
977         }
978
979         // Prevent to insert uncodable characters in verbatim and ERT.
980         // The encoding is inherited from the context here.
981         if (par.isPassThru() && cur.getEncoding()) {
982                 Encoding const * e = cur.getEncoding();
983                 if (!e->encodable(c)) {
984                         cur.message(_("Character is uncodable in this verbatim context."));
985                         return false;
986                 }
987         }
988         return true;
989 }
990
991 } // namespace
992
993
994 // insert a character, moves all the following breaks in the
995 // same Paragraph one to the right and make a rebreak
996 void Text::insertChar(Cursor & cur, char_type c)
997 {
998         LBUFERR(this == cur.text());
999
1000         if (!canInsertChar(cur,c))
1001                 return;
1002
1003         cur.recordUndo(INSERT_UNDO);
1004
1005         TextMetrics const & tm = cur.bv().textMetrics(this);
1006         Buffer const & buffer = *cur.buffer();
1007         Paragraph & par = cur.paragraph();
1008         // try to remove this
1009         pit_type const pit = cur.pit();
1010
1011         if (lyxrc.auto_number) {
1012                 static docstring const number_operators = from_ascii("+-/*");
1013                 static docstring const number_unary_operators = from_ascii("+-");
1014
1015                 // Common Number Separators: comma, dot etc.
1016                 // European Number Terminators: percent, permille, degree, euro etc.
1017                 if (cur.current_font.fontInfo().number() == FONT_ON) {
1018                         if (!isDigitASCII(c) && !contains(number_operators, c) &&
1019                             !(isCommonNumberSeparator(c) &&
1020                               cur.pos() != 0 &&
1021                               cur.pos() != cur.lastpos() &&
1022                               tm.displayFont(pit, cur.pos()).fontInfo().number() == FONT_ON &&
1023                               tm.displayFont(pit, cur.pos() - 1).fontInfo().number() == FONT_ON) &&
1024                             !(isEuropeanNumberTerminator(c) &&
1025                               cur.pos() != 0 &&
1026                               tm.displayFont(pit, cur.pos()).fontInfo().number() == FONT_ON &&
1027                               tm.displayFont(pit, cur.pos() - 1).fontInfo().number() == FONT_ON)
1028                            )
1029                                 number(cur); // Set current_font.number to OFF
1030                 } else if (isDigitASCII(c) &&
1031                            cur.real_current_font.isVisibleRightToLeft()) {
1032                         number(cur); // Set current_font.number to ON
1033
1034                         if (cur.pos() != 0) {
1035                                 char_type const ch = par.getChar(cur.pos() - 1);
1036                                 if (contains(number_unary_operators, ch) &&
1037                                     (cur.pos() == 1
1038                                      || par.isSeparator(cur.pos() - 2)
1039                                      || par.isEnvSeparator(cur.pos() - 2)
1040                                      || par.isNewline(cur.pos() - 2))
1041                                   ) {
1042                                         setCharFont(pit, cur.pos() - 1, cur.current_font,
1043                                                 tm.font_);
1044                                 } else if (isCommonNumberSeparator(ch)
1045                                      && cur.pos() >= 2
1046                                      && tm.displayFont(pit, cur.pos() - 2).fontInfo().number() == FONT_ON) {
1047                                         setCharFont(pit, cur.pos() - 1, cur.current_font,
1048                                                 tm.font_);
1049                                 }
1050                         }
1051                 }
1052         }
1053
1054         // In Bidi text, we want spaces to be treated in a special way: spaces
1055         // which are between words in different languages should get the
1056         // paragraph's language; otherwise, spaces should keep the language
1057         // they were originally typed in. This is only in effect while typing;
1058         // after the text is already typed in, the user can always go back and
1059         // explicitly set the language of a space as desired. But 99.9% of the
1060         // time, what we're doing here is what the user actually meant.
1061         //
1062         // The following cases are the ones in which the language of the space
1063         // should be changed to match that of the containing paragraph. In the
1064         // depictions, lowercase is LTR, uppercase is RTL, underscore (_)
1065         // represents a space, pipe (|) represents the cursor position (so the
1066         // character before it is the one just typed in). The different cases
1067         // are depicted logically (not visually), from left to right:
1068         //
1069         // 1. A_a|
1070         // 2. a_A|
1071         //
1072         // Theoretically, there are other situations that we should, perhaps, deal
1073         // with (e.g.: a|_A, A|_a). In practice, though, there really isn't any
1074         // point (to understand why, just try to create this situation...).
1075
1076         if ((cur.pos() >= 2) && (par.isLineSeparator(cur.pos() - 1))) {
1077                 // get font in front and behind the space in question. But do NOT
1078                 // use getFont(cur.pos()) because the character c is not inserted yet
1079                 Font const pre_space_font  = tm.displayFont(cur.pit(), cur.pos() - 2);
1080                 Font const & post_space_font = cur.real_current_font;
1081                 bool pre_space_rtl  = pre_space_font.isVisibleRightToLeft();
1082                 bool post_space_rtl = post_space_font.isVisibleRightToLeft();
1083
1084                 if (pre_space_rtl != post_space_rtl) {
1085                         // Set the space's language to match the language of the
1086                         // adjacent character whose direction is the paragraph's
1087                         // direction; don't touch other properties of the font
1088                         Language const * lang =
1089                                 (pre_space_rtl == par.isRTL(buffer.params())) ?
1090                                 pre_space_font.language() : post_space_font.language();
1091
1092                         Font space_font = tm.displayFont(cur.pit(), cur.pos() - 1);
1093                         space_font.setLanguage(lang);
1094                         par.setFont(cur.pos() - 1, space_font);
1095                 }
1096         }
1097
1098         pos_type pos = cur.pos();
1099         if (!cur.paragraph().isPassThru() && owner_->lyxCode() != IPA_CODE &&
1100             cur.real_current_font.fontInfo().family() != TYPEWRITER_FAMILY &&
1101             c == '-' && pos > 0) {
1102                 if (par.getChar(pos - 1) == '-') {
1103                         // convert "--" to endash
1104                         par.eraseChar(pos - 1, cur.buffer()->params().track_changes);
1105                         c = 0x2013;
1106                         pos--;
1107                 } else if (par.getChar(pos - 1) == 0x2013) {
1108                         // convert "---" to emdash
1109                         par.eraseChar(pos - 1, cur.buffer()->params().track_changes);
1110                         c = 0x2014;
1111                         pos--;
1112                 }
1113         }
1114
1115         par.insertChar(pos, c, cur.current_font,
1116                 cur.buffer()->params().track_changes);
1117         cur.checkBufferStructure();
1118
1119 //              cur.screenUpdateFlags(Update::Force);
1120         bool boundary = cur.boundary()
1121                 || tm.isRTLBoundary(cur.pit(), pos + 1);
1122         setCursor(cur, cur.pit(), pos + 1, false, boundary);
1123         charInserted(cur);
1124 }
1125
1126
1127 void Text::charInserted(Cursor & cur)
1128 {
1129         Paragraph & par = cur.paragraph();
1130
1131         // register word if a non-letter was entered
1132         if (cur.pos() > 1
1133             && !par.isWordSeparator(cur.pos() - 2)
1134             && par.isWordSeparator(cur.pos() - 1)) {
1135                 // get the word in front of cursor
1136                 LBUFERR(this == cur.text());
1137                 cur.paragraph().updateWords();
1138         }
1139 }
1140
1141
1142 // the cursor set functions have a special mechanism. When they
1143 // realize, that you left an empty paragraph, they will delete it.
1144
1145 bool Text::cursorForwardOneWord(Cursor & cur)
1146 {
1147         LBUFERR(this == cur.text());
1148
1149         pos_type const lastpos = cur.lastpos();
1150         pit_type pit = cur.pit();
1151         pos_type pos = cur.pos();
1152         Paragraph const & par = cur.paragraph();
1153
1154         // Paragraph boundary is a word boundary
1155         if (pos == lastpos || (pos + 1 == lastpos && par.isEnvSeparator(pos))) {
1156                 if (pit != cur.lastpit())
1157                         return setCursor(cur, pit + 1, 0);
1158                 else
1159                         return false;
1160         }
1161
1162         if (lyxrc.mac_like_cursor_movement) {
1163                 // Skip through trailing punctuation and spaces.
1164                 while (pos != lastpos && (par.isChar(pos) || par.isSpace(pos)))
1165                         ++pos;
1166
1167                 // Skip over either a non-char inset or a full word
1168                 if (pos != lastpos && par.isWordSeparator(pos))
1169                         ++pos;
1170                 else while (pos != lastpos && !par.isWordSeparator(pos))
1171                              ++pos;
1172         } else {
1173                 LASSERT(pos < lastpos, return false); // see above
1174                 if (!par.isWordSeparator(pos))
1175                         while (pos != lastpos && !par.isWordSeparator(pos))
1176                                 ++pos;
1177                 else if (par.isChar(pos))
1178                         while (pos != lastpos && par.isChar(pos))
1179                                 ++pos;
1180                 else if (!par.isSpace(pos)) // non-char inset
1181                         ++pos;
1182
1183                 // Skip over white space
1184                 while (pos != lastpos && par.isSpace(pos))
1185                              ++pos;
1186         }
1187
1188         // Don't skip a separator inset at the end of a paragraph
1189         if (pos == lastpos && pos && par.isEnvSeparator(pos - 1))
1190                 --pos;
1191
1192         return setCursor(cur, pit, pos);
1193 }
1194
1195
1196 bool Text::cursorBackwardOneWord(Cursor & cur)
1197 {
1198         LBUFERR(this == cur.text());
1199
1200         pit_type pit = cur.pit();
1201         pos_type pos = cur.pos();
1202         Paragraph & par = cur.paragraph();
1203
1204         // Paragraph boundary is a word boundary
1205         if (pos == 0 && pit != 0) {
1206                 Paragraph & prevpar = getPar(pit - 1);
1207                 pos = prevpar.size();
1208                 // Don't stop after an environment separator
1209                 if (pos && prevpar.isEnvSeparator(pos - 1))
1210                         --pos;
1211                 return setCursor(cur, pit - 1, pos);
1212         }
1213
1214         if (lyxrc.mac_like_cursor_movement) {
1215                 // Skip through punctuation and spaces.
1216                 while (pos != 0 && (par.isChar(pos - 1) || par.isSpace(pos - 1)))
1217                         --pos;
1218
1219                 // Skip over either a non-char inset or a full word
1220                 if (pos != 0 && par.isWordSeparator(pos - 1) && !par.isChar(pos - 1))
1221                         --pos;
1222                 else while (pos != 0 && !par.isWordSeparator(pos - 1))
1223                              --pos;
1224         } else {
1225                 // Skip over white space
1226                 while (pos != 0 && par.isSpace(pos - 1))
1227                              --pos;
1228
1229                 if (pos != 0 && !par.isWordSeparator(pos - 1))
1230                         while (pos != 0 && !par.isWordSeparator(pos - 1))
1231                                 --pos;
1232                 else if (pos != 0 && par.isChar(pos - 1))
1233                         while (pos != 0 && par.isChar(pos - 1))
1234                                 --pos;
1235                 else if (pos != 0 && !par.isSpace(pos - 1)) // non-char inset
1236                         --pos;
1237         }
1238
1239         return setCursor(cur, pit, pos);
1240 }
1241
1242
1243 bool Text::cursorVisLeftOneWord(Cursor & cur)
1244 {
1245         LBUFERR(this == cur.text());
1246
1247         pos_type left_pos, right_pos;
1248
1249         Cursor temp_cur = cur;
1250
1251         // always try to move at least once...
1252         while (temp_cur.posVisLeft(true /* skip_inset */)) {
1253
1254                 // collect some information about current cursor position
1255                 temp_cur.getSurroundingPos(left_pos, right_pos);
1256                 bool left_is_letter =
1257                         (left_pos > -1 ? !temp_cur.paragraph().isWordSeparator(left_pos) : false);
1258                 bool right_is_letter =
1259                         (right_pos > -1 ? !temp_cur.paragraph().isWordSeparator(right_pos) : false);
1260
1261                 // if we're not at a letter/non-letter boundary, continue moving
1262                 if (left_is_letter == right_is_letter)
1263                         continue;
1264
1265                 // we should stop when we have an LTR word on our right or an RTL word
1266                 // on our left
1267                 if ((left_is_letter && temp_cur.paragraph().getFontSettings(
1268                                 temp_cur.buffer()->params(), left_pos).isRightToLeft())
1269                         || (right_is_letter && !temp_cur.paragraph().getFontSettings(
1270                                 temp_cur.buffer()->params(), right_pos).isRightToLeft()))
1271                         break;
1272         }
1273
1274         return setCursor(cur, temp_cur.pit(), temp_cur.pos(),
1275                                          true, temp_cur.boundary());
1276 }
1277
1278
1279 bool Text::cursorVisRightOneWord(Cursor & cur)
1280 {
1281         LBUFERR(this == cur.text());
1282
1283         pos_type left_pos, right_pos;
1284
1285         Cursor temp_cur = cur;
1286
1287         // always try to move at least once...
1288         while (temp_cur.posVisRight(true /* skip_inset */)) {
1289
1290                 // collect some information about current cursor position
1291                 temp_cur.getSurroundingPos(left_pos, right_pos);
1292                 bool left_is_letter =
1293                         (left_pos > -1 ? !temp_cur.paragraph().isWordSeparator(left_pos) : false);
1294                 bool right_is_letter =
1295                         (right_pos > -1 ? !temp_cur.paragraph().isWordSeparator(right_pos) : false);
1296
1297                 // if we're not at a letter/non-letter boundary, continue moving
1298                 if (left_is_letter == right_is_letter)
1299                         continue;
1300
1301                 // we should stop when we have an LTR word on our right or an RTL word
1302                 // on our left
1303                 if ((left_is_letter && temp_cur.paragraph().getFontSettings(
1304                                 temp_cur.buffer()->params(),
1305                                 left_pos).isRightToLeft())
1306                         || (right_is_letter && !temp_cur.paragraph().getFontSettings(
1307                                 temp_cur.buffer()->params(),
1308                                 right_pos).isRightToLeft()))
1309                         break;
1310         }
1311
1312         return setCursor(cur, temp_cur.pit(), temp_cur.pos(),
1313                                          true, temp_cur.boundary());
1314 }
1315
1316
1317 void Text::selectWord(Cursor & cur, word_location loc)
1318 {
1319         LBUFERR(this == cur.text());
1320         CursorSlice from = cur.top();
1321         CursorSlice to;
1322         getWord(from, to, loc);
1323         if (cur.top() != from)
1324                 setCursor(cur, from.pit(), from.pos());
1325         if (to == from)
1326                 return;
1327         if (!cur.selection())
1328                 cur.resetAnchor();
1329         setCursor(cur, to.pit(), to.pos());
1330         cur.setSelection();
1331         cur.setWordSelection(true);
1332 }
1333
1334
1335 void Text::selectAll(Cursor & cur)
1336 {
1337         LBUFERR(this == cur.text());
1338         if (cur.lastpos() == 0 && cur.lastpit() == 0)
1339                 return;
1340         // If the cursor is at the beginning, make sure the cursor ends there
1341         if (cur.pit() == 0 && cur.pos() == 0) {
1342                 setCursor(cur, cur.lastpit(), getPar(cur.lastpit()).size());
1343                 cur.resetAnchor();
1344                 setCursor(cur, 0, 0);
1345         } else {
1346                 setCursor(cur, 0, 0);
1347                 cur.resetAnchor();
1348                 setCursor(cur, cur.lastpit(), getPar(cur.lastpit()).size());
1349         }
1350         cur.setSelection();
1351 }
1352
1353
1354 // Select the word currently under the cursor when no
1355 // selection is currently set
1356 bool Text::selectWordWhenUnderCursor(Cursor & cur, word_location loc)
1357 {
1358         LBUFERR(this == cur.text());
1359         if (cur.selection())
1360                 return false;
1361         selectWord(cur, loc);
1362         return cur.selection();
1363 }
1364
1365
1366 void Text::acceptOrRejectChanges(Cursor & cur, ChangeOp op)
1367 {
1368         LBUFERR(this == cur.text());
1369
1370         if (!cur.selection()) {
1371                 if (!selectChange(cur))
1372                         return;
1373         }
1374
1375         cur.recordUndoSelection();
1376
1377         pit_type begPit = cur.selectionBegin().pit();
1378         pit_type endPit = cur.selectionEnd().pit();
1379
1380         pos_type begPos = cur.selectionBegin().pos();
1381         pos_type endPos = cur.selectionEnd().pos();
1382
1383         // keep selection info, because endPos becomes invalid after the first loop
1384         bool const endsBeforeEndOfPar = (endPos < pars_[endPit].size());
1385
1386         // first, accept/reject changes within each individual paragraph (do not consider end-of-par)
1387         for (pit_type pit = begPit; pit <= endPit; ++pit) {
1388                 pos_type parSize = pars_[pit].size();
1389
1390                 // ignore empty paragraphs; otherwise, an assertion will fail for
1391                 // acceptChanges(bparams, 0, 0) or rejectChanges(bparams, 0, 0)
1392                 if (parSize == 0)
1393                         continue;
1394
1395                 // do not consider first paragraph if the cursor starts at pos size()
1396                 if (pit == begPit && begPos == parSize)
1397                         continue;
1398
1399                 // do not consider last paragraph if the cursor ends at pos 0
1400                 if (pit == endPit && endPos == 0)
1401                         break; // last iteration anyway
1402
1403                 pos_type const left  = (pit == begPit ? begPos : 0);
1404                 pos_type const right = (pit == endPit ? endPos : parSize);
1405
1406                 if (left == right)
1407                         // there is no change here
1408                         continue;
1409
1410                 if (op == ACCEPT) {
1411                         pars_[pit].acceptChanges(left, right);
1412                 } else {
1413                         pars_[pit].rejectChanges(left, right);
1414                 }
1415         }
1416
1417         // next, accept/reject imaginary end-of-par characters
1418
1419         for (pit_type pit = begPit; pit <= endPit; ++pit) {
1420                 pos_type pos = pars_[pit].size();
1421
1422                 // skip if the selection ends before the end-of-par
1423                 if (pit == endPit && endsBeforeEndOfPar)
1424                         break; // last iteration anyway
1425
1426                 // skip if this is not the last paragraph of the document
1427                 // note: the user should be able to accept/reject the par break of the last par!
1428                 if (pit == endPit && pit + 1 != int(pars_.size()))
1429                         break; // last iteration anway
1430
1431                 if (op == ACCEPT) {
1432                         if (pars_[pit].isInserted(pos)) {
1433                                 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1434                         } else if (pars_[pit].isDeleted(pos)) {
1435                                 if (pit + 1 == int(pars_.size())) {
1436                                         // we cannot remove a par break at the end of the last paragraph;
1437                                         // instead, we mark it unchanged
1438                                         pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1439                                 } else {
1440                                         mergeParagraph(cur.buffer()->params(), pars_, pit);
1441                                         --endPit;
1442                                         --pit;
1443                                 }
1444                         }
1445                 } else {
1446                         if (pars_[pit].isDeleted(pos)) {
1447                                 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1448                         } else if (pars_[pit].isInserted(pos)) {
1449                                 if (pit + 1 == int(pars_.size())) {
1450                                         // we mark the par break at the end of the last paragraph unchanged
1451                                         pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1452                                 } else {
1453                                         mergeParagraph(cur.buffer()->params(), pars_, pit);
1454                                         --endPit;
1455                                         --pit;
1456                                 }
1457                         }
1458                 }
1459         }
1460
1461         // finally, invoke the DEPM
1462         deleteEmptyParagraphMechanism(begPit, endPit, cur.buffer()->params().track_changes);
1463
1464         cur.finishUndo();
1465         cur.clearSelection();
1466         setCursorIntern(cur, begPit, begPos);
1467         cur.screenUpdateFlags(Update::Force);
1468         cur.forceBufferUpdate();
1469 }
1470
1471
1472 void Text::acceptChanges()
1473 {
1474         BufferParams const & bparams = owner_->buffer().params();
1475         lyx::acceptChanges(pars_, bparams);
1476         deleteEmptyParagraphMechanism(0, pars_.size() - 1, bparams.track_changes);
1477 }
1478
1479
1480 void Text::rejectChanges()
1481 {
1482         BufferParams const & bparams = owner_->buffer().params();
1483         pit_type pars_size = static_cast<pit_type>(pars_.size());
1484
1485         // first, reject changes within each individual paragraph
1486         // (do not consider end-of-par)
1487         for (pit_type pit = 0; pit < pars_size; ++pit) {
1488                 if (!pars_[pit].empty())   // prevent assertion failure
1489                         pars_[pit].rejectChanges(0, pars_[pit].size());
1490         }
1491
1492         // next, reject imaginary end-of-par characters
1493         for (pit_type pit = 0; pit < pars_size; ++pit) {
1494                 pos_type pos = pars_[pit].size();
1495
1496                 if (pars_[pit].isDeleted(pos)) {
1497                         pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1498                 } else if (pars_[pit].isInserted(pos)) {
1499                         if (pit == pars_size - 1) {
1500                                 // we mark the par break at the end of the last
1501                                 // paragraph unchanged
1502                                 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1503                         } else {
1504                                 mergeParagraph(bparams, pars_, pit);
1505                                 --pit;
1506                                 --pars_size;
1507                         }
1508                 }
1509         }
1510
1511         // finally, invoke the DEPM
1512         deleteEmptyParagraphMechanism(0, pars_size - 1, bparams.track_changes);
1513 }
1514
1515
1516 void Text::deleteWordForward(Cursor & cur, bool const force)
1517 {
1518         LBUFERR(this == cur.text());
1519         if (cur.lastpos() == 0)
1520                 cursorForward(cur);
1521         else {
1522                 cur.resetAnchor();
1523                 cur.selection(true);
1524                 cursorForwardOneWord(cur);
1525                 cur.setSelection();
1526                 if (force || !cur.confirmDeletion()) {
1527                         cutSelection(cur, false);
1528                         cur.checkBufferStructure();
1529                 }
1530         }
1531 }
1532
1533
1534 void Text::deleteWordBackward(Cursor & cur, bool const force)
1535 {
1536         LBUFERR(this == cur.text());
1537         if (cur.lastpos() == 0)
1538                 cursorBackward(cur);
1539         else {
1540                 cur.resetAnchor();
1541                 cur.selection(true);
1542                 cursorBackwardOneWord(cur);
1543                 cur.setSelection();
1544                 if (force || !cur.confirmDeletion()) {
1545                         cutSelection(cur, false);
1546                         cur.checkBufferStructure();
1547                 }
1548         }
1549 }
1550
1551
1552 // Kill to end of line.
1553 void Text::changeCase(Cursor & cur, TextCase action, bool partial)
1554 {
1555         LBUFERR(this == cur.text());
1556         CursorSlice from;
1557         CursorSlice to;
1558
1559         bool const gotsel = cur.selection();
1560         if (gotsel) {
1561                 from = cur.selBegin();
1562                 to = cur.selEnd();
1563         } else {
1564                 from = cur.top();
1565                 getWord(from, to, partial ? PARTIAL_WORD : WHOLE_WORD);
1566                 cursorForwardOneWord(cur);
1567         }
1568
1569         cur.recordUndoSelection();
1570
1571         pit_type begPit = from.pit();
1572         pit_type endPit = to.pit();
1573
1574         pos_type begPos = from.pos();
1575         pos_type endPos = to.pos();
1576
1577         pos_type right = 0; // needed after the for loop
1578
1579         for (pit_type pit = begPit; pit <= endPit; ++pit) {
1580                 Paragraph & par = pars_[pit];
1581                 pos_type const pos = (pit == begPit ? begPos : 0);
1582                 right = (pit == endPit ? endPos : par.size());
1583                 par.changeCase(cur.buffer()->params(), pos, right, action);
1584         }
1585
1586         // the selection may have changed due to logically-only deleted chars
1587         if (gotsel) {
1588                 setCursor(cur, begPit, begPos);
1589                 cur.resetAnchor();
1590                 setCursor(cur, endPit, right);
1591                 cur.setSelection();
1592         } else
1593                 setCursor(cur, endPit, right);
1594
1595         cur.checkBufferStructure();
1596 }
1597
1598
1599 bool Text::handleBibitems(Cursor & cur)
1600 {
1601         if (cur.paragraph().layout().labeltype != LABEL_BIBLIO)
1602                 return false;
1603
1604         if (cur.pos() != 0)
1605                 return false;
1606
1607         BufferParams const & bufparams = cur.buffer()->params();
1608         Paragraph const & par = cur.paragraph();
1609         Cursor prevcur = cur;
1610         if (cur.pit() > 0) {
1611                 --prevcur.pit();
1612                 prevcur.pos() = prevcur.lastpos();
1613         }
1614         Paragraph const & prevpar = prevcur.paragraph();
1615
1616         // if a bibitem is deleted, merge with previous paragraph
1617         // if this is a bibliography item as well
1618         if (cur.pit() > 0 && par.layout() == prevpar.layout()) {
1619                 cur.recordUndo(prevcur.pit());
1620                 mergeParagraph(bufparams, cur.text()->paragraphs(),
1621                                                         prevcur.pit());
1622                 cur.forceBufferUpdate();
1623                 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1624                 cur.screenUpdateFlags(Update::Force);
1625                 return true;
1626         }
1627
1628         // otherwise reset to default
1629         cur.paragraph().setPlainOrDefaultLayout(bufparams.documentClass());
1630         return true;
1631 }
1632
1633
1634 bool Text::erase(Cursor & cur)
1635 {
1636         LASSERT(this == cur.text(), return false);
1637         bool needsUpdate = false;
1638         Paragraph & par = cur.paragraph();
1639
1640         if (cur.pos() != cur.lastpos()) {
1641                 // this is the code for a normal delete, not pasting
1642                 // any paragraphs
1643                 cur.recordUndo(DELETE_UNDO);
1644                 bool const was_inset = cur.paragraph().isInset(cur.pos());
1645                 if(!par.eraseChar(cur.pos(), cur.buffer()->params().track_changes))
1646                         // the character has been logically deleted only => skip it
1647                         cur.top().forwardPos();
1648
1649                 if (was_inset)
1650                         cur.forceBufferUpdate();
1651                 else
1652                         cur.checkBufferStructure();
1653                 needsUpdate = true;
1654         } else {
1655                 if (cur.pit() == cur.lastpit())
1656                         return dissolveInset(cur);
1657
1658                 if (!par.isMergedOnEndOfParDeletion(cur.buffer()->params().track_changes)) {
1659                         cur.recordUndo(DELETE_UNDO);
1660                         par.setChange(cur.pos(), Change(Change::DELETED));
1661                         cur.forwardPos();
1662                         needsUpdate = true;
1663                 } else {
1664                         setCursorIntern(cur, cur.pit() + 1, 0);
1665                         needsUpdate = backspacePos0(cur);
1666                 }
1667         }
1668
1669         needsUpdate |= handleBibitems(cur);
1670
1671         if (needsUpdate) {
1672                 // Make sure the cursor is correct. Is this really needed?
1673                 // No, not really... at least not here!
1674                 cur.top().setPitPos(cur.pit(), cur.pos());
1675                 cur.checkBufferStructure();
1676         }
1677
1678         return needsUpdate;
1679 }
1680
1681
1682 bool Text::backspacePos0(Cursor & cur)
1683 {
1684         LBUFERR(this == cur.text());
1685         if (cur.pit() == 0)
1686                 return false;
1687
1688         bool needsUpdate = false;
1689
1690         BufferParams const & bufparams = cur.buffer()->params();
1691         DocumentClass const & tclass = bufparams.documentClass();
1692         ParagraphList & plist = cur.text()->paragraphs();
1693         Paragraph const & par = cur.paragraph();
1694         Cursor prevcur = cur;
1695         --prevcur.pit();
1696         prevcur.pos() = prevcur.lastpos();
1697         Paragraph const & prevpar = prevcur.paragraph();
1698
1699         // is it an empty paragraph?
1700         if (cur.lastpos() == 0
1701             || (cur.lastpos() == 1 && par.isSeparator(0))) {
1702                 cur.recordUndo(prevcur.pit());
1703                 plist.erase(plist.iterator_at(cur.pit()));
1704                 needsUpdate = true;
1705         }
1706         // is previous par empty?
1707         else if (prevcur.lastpos() == 0
1708                  || (prevcur.lastpos() == 1 && prevpar.isSeparator(0))) {
1709                 cur.recordUndo(prevcur.pit());
1710                 plist.erase(plist.iterator_at(prevcur.pit()));
1711                 needsUpdate = true;
1712         }
1713         // FIXME: Do we really not want to allow this???
1714         // Pasting is not allowed, if the paragraphs have different
1715         // layouts. I think it is a real bug of all other
1716         // word processors to allow it. It confuses the user.
1717         // Correction: Pasting is always allowed with standard-layout
1718         // or the empty layout.
1719         else if (par.layout() == prevpar.layout()
1720                  || tclass.isDefaultLayout(par.layout())
1721                  || tclass.isPlainLayout(par.layout())) {
1722                 cur.recordUndo(prevcur.pit());
1723                 mergeParagraph(bufparams, plist, prevcur.pit());
1724                 needsUpdate = true;
1725         }
1726
1727         if (needsUpdate) {
1728                 cur.forceBufferUpdate();
1729                 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1730         }
1731
1732         return needsUpdate;
1733 }
1734
1735
1736 bool Text::backspace(Cursor & cur)
1737 {
1738         LBUFERR(this == cur.text());
1739         bool needsUpdate = false;
1740         if (cur.pos() == 0) {
1741                 if (cur.pit() == 0)
1742                         return dissolveInset(cur);
1743
1744                 Cursor prev_cur = cur;
1745                 --prev_cur.pit();
1746
1747                 if (cur.paragraph().size() > 0
1748                     && !prev_cur.paragraph().isMergedOnEndOfParDeletion(cur.buffer()->params().track_changes)) {
1749                         cur.recordUndo(prev_cur.pit(), prev_cur.pit());
1750                         prev_cur.paragraph().setChange(prev_cur.lastpos(), Change(Change::DELETED));
1751                         setCursorIntern(cur, prev_cur.pit(), prev_cur.lastpos());
1752                         return true;
1753                 }
1754                 // The cursor is at the beginning of a paragraph, so
1755                 // the backspace will collapse two paragraphs into one.
1756                 needsUpdate = backspacePos0(cur);
1757
1758         } else {
1759                 // this is the code for a normal backspace, not pasting
1760                 // any paragraphs
1761                 cur.recordUndo(DELETE_UNDO);
1762                 // We used to do cursorBackwardIntern() here, but it is
1763                 // not a good idea since it triggers the auto-delete
1764                 // mechanism. So we do a cursorBackwardIntern()-lite,
1765                 // without the dreaded mechanism. (JMarc)
1766                 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1767                                 false, cur.boundary());
1768                 bool const was_inset = cur.paragraph().isInset(cur.pos());
1769                 cur.paragraph().eraseChar(cur.pos(), cur.buffer()->params().track_changes);
1770                 if (was_inset)
1771                         cur.forceBufferUpdate();
1772                 else
1773                         cur.checkBufferStructure();
1774         }
1775
1776         if (cur.pos() == cur.lastpos())
1777                 cur.setCurrentFont();
1778
1779         needsUpdate |= handleBibitems(cur);
1780
1781         // A singlePar update is not enough in this case.
1782         // cur.screenUpdateFlags(Update::Force);
1783         cur.top().setPitPos(cur.pit(), cur.pos());
1784
1785         return needsUpdate;
1786 }
1787
1788
1789 bool Text::dissolveInset(Cursor & cur)
1790 {
1791         LASSERT(this == cur.text(), return false);
1792
1793         if (isMainText() || cur.inset().nargs() != 1)
1794                 return false;
1795
1796         cur.recordUndoInset();
1797         cur.setMark(false);
1798         cur.selHandle(false);
1799         // save position inside inset
1800         pos_type spos = cur.pos();
1801         pit_type spit = cur.pit();
1802         bool const inset_non_empty = cur.lastpit() != 0 || cur.lastpos() != 0;
1803         cur.popBackward();
1804         // update cursor offset
1805         if (spit == 0)
1806                 spos += cur.pos();
1807         spit += cur.pit();
1808         // remember position outside inset to delete inset later
1809         // we do not do it now to avoid memory reuse issues (see #10667).
1810         DocIterator inset_it = cur;
1811         // jump over inset
1812         ++cur.pos();
1813
1814         Buffer & b = *cur.buffer();
1815         // Is there anything in this text?
1816         if (inset_non_empty) {
1817                 // see bug 7319
1818                 // we clear the cache so that we won't get conflicts with labels
1819                 // that get pasted into the buffer. we should update this before
1820                 // its being empty matters. if not (i.e., if we encounter bugs),
1821                 // then this should instead be:
1822                 //        cur.buffer().updateBuffer();
1823                 // but we'll try the cheaper solution here.
1824                 cur.buffer()->clearReferenceCache();
1825
1826                 ParagraphList & plist = paragraphs();
1827                 if (!lyxrc.ct_markup_copied)
1828                         // Do not revive deleted text
1829                         lyx::acceptChanges(plist, b.params());
1830
1831                 // ERT paragraphs have the Language latex_language.
1832                 // This is invalid outside of ERT, so we need to
1833                 // change it to the buffer language.
1834                 for (auto & p : plist)
1835                         p.changeLanguage(b.params(), latex_language, b.language());
1836
1837                 /* If the inset is the only thing in paragraph and the layout
1838                  * is not plain, then the layout of the first paragraph of
1839                  * inset should be remembered.
1840                  * FIXME: this does not work as expected when change tracking
1841                  *   is on However, we do not really know what to do in this
1842                  *   case.
1843                  */
1844                 DocumentClass const & tclass = cur.buffer()->params().documentClass();
1845                 if (inset_it.lastpos() == 1
1846                     && plist[0].layout().name() != tclass.plainLayoutName())
1847                         cur.paragraph().makeSameLayout(plist[0]);
1848
1849                 pasteParagraphList(cur, plist, b.params().documentClassPtr(),
1850                                    b.errorList("Paste"));
1851         }
1852
1853         // delete the inset now
1854         inset_it.paragraph().eraseChar(inset_it.pos(), b.params().track_changes);
1855
1856         // restore position
1857         cur.pit() = min(cur.lastpit(), spit);
1858         cur.pos() = min(cur.lastpos(), spos);
1859         // Ensure the current language is set correctly (bug 6292)
1860         cur.text()->setCursor(cur, cur.pit(), cur.pos());
1861         cur.clearSelection();
1862         cur.resetAnchor();
1863         cur.forceBufferUpdate();
1864
1865         return true;
1866 }
1867
1868
1869 void Text::getWord(CursorSlice & from, CursorSlice & to,
1870         word_location const loc) const
1871 {
1872         to = from;
1873         pars_[to.pit()].locateWord(from.pos(), to.pos(), loc);
1874 }
1875
1876
1877 void Text::write(ostream & os) const
1878 {
1879         Buffer const & buf = owner_->buffer();
1880         ParagraphList::const_iterator pit = paragraphs().begin();
1881         ParagraphList::const_iterator end = paragraphs().end();
1882         depth_type dth = 0;
1883         for (; pit != end; ++pit)
1884                 pit->write(os, buf.params(), dth);
1885
1886         // Close begin_deeper
1887         for(; dth > 0; --dth)
1888                 os << "\n\\end_deeper";
1889 }
1890
1891
1892 bool Text::read(Lexer & lex,
1893                 ErrorList & errorList, InsetText * insetPtr)
1894 {
1895         Buffer const & buf = owner_->buffer();
1896         depth_type depth = 0;
1897         bool res = true;
1898
1899         while (lex.isOK()) {
1900                 lex.nextToken();
1901                 string const token = lex.getString();
1902
1903                 if (token.empty())
1904                         continue;
1905
1906                 if (token == "\\end_inset")
1907                         break;
1908
1909                 if (token == "\\end_body")
1910                         continue;
1911
1912                 if (token == "\\begin_body")
1913                         continue;
1914
1915                 if (token == "\\end_document") {
1916                         res = false;
1917                         break;
1918                 }
1919
1920                 if (token == "\\begin_layout") {
1921                         lex.pushToken(token);
1922
1923                         Paragraph par;
1924                         par.setInsetOwner(insetPtr);
1925                         par.params().depth(depth);
1926                         par.setFont(0, Font(inherit_font, buf.params().language));
1927                         pars_.push_back(par);
1928                         readParagraph(pars_.back(), lex, errorList);
1929
1930                         // register the words in the global word list
1931                         pars_.back().updateWords();
1932                 } else if (token == "\\begin_deeper") {
1933                         ++depth;
1934                 } else if (token == "\\end_deeper") {
1935                         if (!depth)
1936                                 lex.printError("\\end_deeper: " "depth is already null");
1937                         else
1938                                 --depth;
1939                 } else {
1940                         LYXERR0("Handling unknown body token: `" << token << '\'');
1941                 }
1942         }
1943
1944         // avoid a crash on weird documents (bug 4859)
1945         if (pars_.empty()) {
1946                 Paragraph par;
1947                 par.setInsetOwner(insetPtr);
1948                 par.params().depth(depth);
1949                 par.setFont(0, Font(inherit_font,
1950                                     buf.params().language));
1951                 par.setPlainOrDefaultLayout(buf.params().documentClass());
1952                 pars_.push_back(par);
1953         }
1954
1955         return res;
1956 }
1957
1958
1959 // Returns the current font and depth as a message.
1960 docstring Text::currentState(CursorData const & cur, bool devel_mode) const
1961 {
1962         LBUFERR(this == cur.text());
1963         Buffer & buf = *cur.buffer();
1964         Paragraph const & par = cur.paragraph();
1965         odocstringstream os;
1966
1967         if (buf.params().track_changes)
1968                 os << _("[Change Tracking] ");
1969
1970         Change change = par.lookupChange(cur.pos());
1971
1972         if (change.changed()) {
1973                 docstring const author =
1974                         buf.params().authors().get(change.author).nameAndEmail();
1975                 docstring const date = formatted_datetime(change.changetime);
1976                 os << bformat(_("Changed by %1$s[[author]] on %2$s[[date]]. "),
1977                               author, date);
1978         }
1979
1980         // I think we should only show changes from the default
1981         // font. (Asger)
1982         // No, from the document font (MV)
1983         Font font = cur.real_current_font;
1984         font.fontInfo().reduce(buf.params().getFont().fontInfo());
1985
1986         os << bformat(_("Font: %1$s"), font.stateText(&buf.params()));
1987
1988         // The paragraph depth
1989         int depth = cur.paragraph().getDepth();
1990         if (depth > 0)
1991                 os << bformat(_(", Depth: %1$d"), depth);
1992
1993         // The paragraph spacing, but only if different from
1994         // buffer spacing.
1995         Spacing const & spacing = par.params().spacing();
1996         if (!spacing.isDefault()) {
1997                 os << _(", Spacing: ");
1998                 switch (spacing.getSpace()) {
1999                 case Spacing::Single:
2000                         os << _("Single");
2001                         break;
2002                 case Spacing::Onehalf:
2003                         os << _("OneHalf");
2004                         break;
2005                 case Spacing::Double:
2006                         os << _("Double");
2007                         break;
2008                 case Spacing::Other:
2009                         os << _("Other (") << from_ascii(spacing.getValueAsString()) << ')';
2010                         break;
2011                 case Spacing::Default:
2012                         // should never happen, do nothing
2013                         break;
2014                 }
2015         }
2016
2017         if (devel_mode) {
2018                 os << _(", Inset: ") << &cur.inset();
2019                 if (cur.lastidx() > 0)
2020                         os << _(", Cell: ") << cur.idx();
2021                 os << _(", Paragraph: ") << cur.pit();
2022                 os << _(", Id: ") << par.id();
2023                 os << _(", Position: ") << cur.pos();
2024                 // FIXME: Why is the check for par.size() needed?
2025                 // We are called with cur.pos() == par.size() quite often.
2026                 if (!par.empty() && cur.pos() < par.size()) {
2027                         // Force output of code point, not character
2028                         size_t const c = par.getChar(cur.pos());
2029                         os << _(", Char: 0x") << hex << c;
2030                 }
2031                 os << _(", Boundary: ") << cur.boundary();
2032 //              Row & row = cur.textRow();
2033 //              os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
2034         }
2035         return os.str();
2036 }
2037
2038
2039 docstring Text::getPossibleLabel(DocIterator const & cur) const
2040 {
2041         pit_type textpit = cur.pit();
2042         Layout const * layout = &(pars_[textpit].layout());
2043
2044         // Will contain the label prefix.
2045         docstring name;
2046
2047         // For captions, we just take the caption type
2048         Inset * caption_inset = cur.innerInsetOfType(CAPTION_CODE);
2049         if (caption_inset) {
2050                 string const & ftype = static_cast<InsetCaption *>(caption_inset)->floattype();
2051                 FloatList const & fl = cur.buffer()->params().documentClass().floats();
2052                 if (fl.typeExist(ftype)) {
2053                         Floating const & flt = fl.getType(ftype);
2054                         name = from_utf8(flt.refPrefix());
2055                 }
2056                 if (name.empty())
2057                         name = from_utf8(ftype.substr(0,3));
2058         } else {
2059                 // For section, subsection, etc...
2060                 if (layout->latextype == LATEX_PARAGRAPH && textpit != 0) {
2061                         Layout const * layout2 = &(pars_[textpit - 1].layout());
2062                         if (layout2->latextype != LATEX_PARAGRAPH) {
2063                                 --textpit;
2064                                 layout = layout2;
2065                         }
2066                 }
2067                 if (layout->latextype != LATEX_PARAGRAPH)
2068                         name = layout->refprefix;
2069
2070                 // If none of the above worked, see if the inset knows.
2071                 if (name.empty()) {
2072                         InsetLayout const & il = cur.inset().getLayout();
2073                         name = il.refprefix();
2074                 }
2075         }
2076
2077         docstring text;
2078         docstring par_text = pars_[textpit].asString(AS_STR_SKIPDELETE);
2079
2080         // The return string of math matrices might contain linebreaks
2081         par_text = subst(par_text, '\n', '-');
2082         int const numwords = 3;
2083         for (int i = 0; i < numwords; ++i) {
2084                 if (par_text.empty())
2085                         break;
2086                 docstring head;
2087                 par_text = split(par_text, head, ' ');
2088                 // Is it legal to use spaces in labels ?
2089                 if (i > 0)
2090                         text += '-';
2091                 text += head;
2092         }
2093
2094         // Make sure it isn't too long
2095         unsigned int const max_label_length = 32;
2096         if (text.size() > max_label_length)
2097                 text.resize(max_label_length);
2098
2099         if (!name.empty())
2100                 text = name + ':' + text;
2101
2102         // We need a unique label
2103         docstring label = text;
2104         int i = 1;
2105         while (cur.buffer()->activeLabel(label)) {
2106                         label = text + '-' + convert<docstring>(i);
2107                         ++i;
2108                 }
2109
2110         return label;
2111 }
2112
2113
2114 docstring Text::asString(int options) const
2115 {
2116         return asString(0, pars_.size(), options);
2117 }
2118
2119
2120 docstring Text::asString(pit_type beg, pit_type end, int options) const
2121 {
2122         size_t i = size_t(beg);
2123         docstring str = pars_[i].asString(options);
2124         for (++i; i != size_t(end); ++i) {
2125                 str += '\n';
2126                 str += pars_[i].asString(options);
2127         }
2128         return str;
2129 }
2130
2131
2132 void Text::shortenForOutliner(docstring & str, size_t const maxlen)
2133 {
2134         support::truncateWithEllipsis(str, maxlen);
2135         for (char_type & c : str)
2136                 if (c == L'\n' || c == L'\t')
2137                         c = L' ';
2138 }
2139
2140
2141 void Text::forOutliner(docstring & os, size_t const maxlen,
2142                        bool const shorten) const
2143 {
2144         pit_type end = pars_.size() - 1;
2145         if (0 <= end && !pars_[0].labelString().empty())
2146                 os += pars_[0].labelString() + ' ';
2147         forOutliner(os, maxlen, 0, end, shorten);
2148 }
2149
2150
2151 void Text::forOutliner(docstring & os, size_t const maxlen,
2152                        pit_type pit_start, pit_type pit_end,
2153                        bool const shorten) const
2154 {
2155         size_t tmplen = shorten ? maxlen + 1 : maxlen;
2156         pit_type end = min(size_t(pit_end), pars_.size() - 1);
2157         bool first = true;
2158         for (pit_type i = pit_start; i <= end && os.length() < tmplen; ++i) {
2159                 if (!first)
2160                         os += ' ';
2161                 // This function lets the first label be treated separately
2162                 pars_[i].forOutliner(os, tmplen, false, !first);
2163                 first = false;
2164         }
2165         if (shorten)
2166                 shortenForOutliner(os, maxlen);
2167 }
2168
2169
2170 void Text::charsTranspose(Cursor & cur)
2171 {
2172         LBUFERR(this == cur.text());
2173
2174         pos_type pos = cur.pos();
2175
2176         // If cursor is at beginning or end of paragraph, do nothing.
2177         if (pos == cur.lastpos() || pos == 0)
2178                 return;
2179
2180         Paragraph & par = cur.paragraph();
2181
2182         // Get the positions of the characters to be transposed.
2183         pos_type pos1 = pos - 1;
2184         pos_type pos2 = pos;
2185
2186         // In change tracking mode, ignore deleted characters.
2187         while (pos2 < cur.lastpos() && par.isDeleted(pos2))
2188                 ++pos2;
2189         if (pos2 == cur.lastpos())
2190                 return;
2191
2192         while (pos1 >= 0 && par.isDeleted(pos1))
2193                 --pos1;
2194         if (pos1 < 0)
2195                 return;
2196
2197         // Don't do anything if one of the "characters" is not regular text.
2198         if (par.isInset(pos1) || par.isInset(pos2))
2199                 return;
2200
2201         // Store the characters to be transposed (including font information).
2202         char_type const char1 = par.getChar(pos1);
2203         Font const font1 =
2204                 par.getFontSettings(cur.buffer()->params(), pos1);
2205
2206         char_type const char2 = par.getChar(pos2);
2207         Font const font2 =
2208                 par.getFontSettings(cur.buffer()->params(), pos2);
2209
2210         // And finally, we are ready to perform the transposition.
2211         // Track the changes if Change Tracking is enabled.
2212         bool const trackChanges = cur.buffer()->params().track_changes;
2213
2214         cur.recordUndo();
2215
2216         par.eraseChar(pos2, trackChanges);
2217         par.eraseChar(pos1, trackChanges);
2218         par.insertChar(pos1, char2, font2, trackChanges);
2219         par.insertChar(pos2, char1, font1, trackChanges);
2220
2221         cur.checkBufferStructure();
2222
2223         // After the transposition, move cursor to after the transposition.
2224         setCursor(cur, cur.pit(), pos2);
2225         cur.forwardPos();
2226 }
2227
2228
2229 DocIterator Text::macrocontextPosition() const
2230 {
2231         return macrocontext_position_;
2232 }
2233
2234
2235 void Text::setMacrocontextPosition(DocIterator const & pos)
2236 {
2237         macrocontext_position_ = pos;
2238 }
2239
2240
2241 docstring Text::previousWord(CursorSlice const & sl) const
2242 {
2243         CursorSlice from = sl;
2244         CursorSlice to = sl;
2245         getWord(from, to, PREVIOUS_WORD);
2246         if (sl == from || to == from)
2247                 return docstring();
2248
2249         Paragraph const & par = sl.paragraph();
2250         return par.asString(from.pos(), to.pos());
2251 }
2252
2253
2254 bool Text::completionSupported(Cursor const & cur) const
2255 {
2256         Paragraph const & par = cur.paragraph();
2257         return !cur.selection()
2258                 && cur.pos() > 0
2259                 && (cur.pos() >= par.size() || par.isWordSeparator(cur.pos()))
2260                 && !par.isWordSeparator(cur.pos() - 1);
2261 }
2262
2263
2264 CompletionList const * Text::createCompletionList(Cursor const & cur) const
2265 {
2266         WordList const & list = theWordList(cur.getFont().language()->lang());
2267         return new TextCompletionList(cur, list);
2268 }
2269
2270
2271 bool Text::insertCompletion(Cursor & cur, docstring const & s, bool /*finished*/)
2272 {
2273         LBUFERR(cur.bv().cursor() == cur);
2274         cur.insert(s);
2275         cur.bv().cursor() = cur;
2276         if (!(cur.result().screenUpdate() & Update::Force))
2277                 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
2278         return true;
2279 }
2280
2281
2282 docstring Text::completionPrefix(Cursor const & cur) const
2283 {
2284         return previousWord(cur.top());
2285 }
2286
2287 } // namespace lyx