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