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