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