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