]> git.lyx.org Git - lyx.git/blob - src/Text.cpp
Make sure a temporary file is always created in the global temporary dir.
[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), autoBreakRows_(false), undo_counter_(0)
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), autoBreakRows_(text.autoBreakRows_), undo_counter_(0)
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 (autoBreakRows_ && (!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         // Here we call finishUndo for every 20 characters inserted.
1085         // This is from my experience how emacs does it. (Lgb)
1086         if (undo_counter_ < 20) {
1087                 ++undo_counter_;
1088         } else {
1089                 cur.finishUndo();
1090                 undo_counter_ = 0;
1091         }
1092
1093         // register word if a non-letter was entered
1094         if (cur.pos() > 1
1095             && !par.isWordSeparator(cur.pos() - 2)
1096             && par.isWordSeparator(cur.pos() - 1)) {
1097                 // get the word in front of cursor
1098                 LBUFERR(this == cur.text());
1099                 cur.paragraph().updateWords();
1100         }
1101 }
1102
1103
1104 // the cursor set functions have a special mechanism. When they
1105 // realize, that you left an empty paragraph, they will delete it.
1106
1107 bool Text::cursorForwardOneWord(Cursor & cur)
1108 {
1109         LBUFERR(this == cur.text());
1110
1111         pos_type const lastpos = cur.lastpos();
1112         pit_type pit = cur.pit();
1113         pos_type pos = cur.pos();
1114         Paragraph const & par = cur.paragraph();
1115
1116         // Paragraph boundary is a word boundary
1117         if (pos == lastpos) {
1118                 if (pit != cur.lastpit())
1119                         return setCursor(cur, pit + 1, 0);
1120                 else
1121                         return false;
1122         }
1123
1124         if (lyxrc.mac_like_cursor_movement) {
1125                 // Skip through trailing punctuation and spaces.
1126                 while (pos != lastpos && (par.isChar(pos) || par.isSpace(pos)))
1127                         ++pos;
1128
1129                 // Skip over either a non-char inset or a full word
1130                 if (pos != lastpos && par.isWordSeparator(pos))
1131                         ++pos;
1132                 else while (pos != lastpos && !par.isWordSeparator(pos))
1133                              ++pos;
1134         } else {
1135                 LASSERT(pos < lastpos, return false); // see above
1136                 if (!par.isWordSeparator(pos))
1137                         while (pos != lastpos && !par.isWordSeparator(pos))
1138                                 ++pos;
1139                 else if (par.isChar(pos))
1140                         while (pos != lastpos && par.isChar(pos))
1141                                 ++pos;
1142                 else if (!par.isSpace(pos)) // non-char inset
1143                         ++pos;
1144
1145                 // Skip over white space
1146                 while (pos != lastpos && par.isSpace(pos))
1147                              ++pos;
1148         }
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                 return setCursor(cur, pit - 1, getPar(pit - 1).size());
1165
1166         if (lyxrc.mac_like_cursor_movement) {
1167                 // Skip through punctuation and spaces.
1168                 while (pos != 0 && (par.isChar(pos - 1) || par.isSpace(pos - 1)))
1169                         --pos;
1170
1171                 // Skip over either a non-char inset or a full word
1172                 if (pos != 0 && par.isWordSeparator(pos - 1) && !par.isChar(pos - 1))
1173                         --pos;
1174                 else while (pos != 0 && !par.isWordSeparator(pos - 1))
1175                              --pos;
1176         } else {
1177                 // Skip over white space
1178                 while (pos != 0 && par.isSpace(pos - 1))
1179                              --pos;
1180
1181                 if (pos != 0 && !par.isWordSeparator(pos - 1))
1182                         while (pos != 0 && !par.isWordSeparator(pos - 1))
1183                                 --pos;
1184                 else if (pos != 0 && par.isChar(pos - 1))
1185                         while (pos != 0 && par.isChar(pos - 1))
1186                                 --pos;
1187                 else if (pos != 0 && !par.isSpace(pos - 1)) // non-char inset
1188                         --pos;
1189         }
1190
1191         return setCursor(cur, pit, pos);
1192 }
1193
1194
1195 bool Text::cursorVisLeftOneWord(Cursor & cur)
1196 {
1197         LBUFERR(this == cur.text());
1198
1199         pos_type left_pos, right_pos;
1200         bool left_is_letter, right_is_letter;
1201
1202         Cursor temp_cur = cur;
1203
1204         // always try to move at least once...
1205         while (temp_cur.posVisLeft(true /* skip_inset */)) {
1206
1207                 // collect some information about current cursor position
1208                 temp_cur.getSurroundingPos(left_pos, right_pos);
1209                 left_is_letter =
1210                         (left_pos > -1 ? !temp_cur.paragraph().isWordSeparator(left_pos) : false);
1211                 right_is_letter =
1212                         (right_pos > -1 ? !temp_cur.paragraph().isWordSeparator(right_pos) : false);
1213
1214                 // if we're not at a letter/non-letter boundary, continue moving
1215                 if (left_is_letter == right_is_letter)
1216                         continue;
1217
1218                 // we should stop when we have an LTR word on our right or an RTL word
1219                 // on our left
1220                 if ((left_is_letter && temp_cur.paragraph().getFontSettings(
1221                                 temp_cur.buffer()->params(), left_pos).isRightToLeft())
1222                         || (right_is_letter && !temp_cur.paragraph().getFontSettings(
1223                                 temp_cur.buffer()->params(), right_pos).isRightToLeft()))
1224                         break;
1225         }
1226
1227         return setCursor(cur, temp_cur.pit(), temp_cur.pos(),
1228                                          true, temp_cur.boundary());
1229 }
1230
1231
1232 bool Text::cursorVisRightOneWord(Cursor & cur)
1233 {
1234         LBUFERR(this == cur.text());
1235
1236         pos_type left_pos, right_pos;
1237         bool left_is_letter, right_is_letter;
1238
1239         Cursor temp_cur = cur;
1240
1241         // always try to move at least once...
1242         while (temp_cur.posVisRight(true /* skip_inset */)) {
1243
1244                 // collect some information about current cursor position
1245                 temp_cur.getSurroundingPos(left_pos, right_pos);
1246                 left_is_letter =
1247                         (left_pos > -1 ? !temp_cur.paragraph().isWordSeparator(left_pos) : false);
1248                 right_is_letter =
1249                         (right_pos > -1 ? !temp_cur.paragraph().isWordSeparator(right_pos) : false);
1250
1251                 // if we're not at a letter/non-letter boundary, continue moving
1252                 if (left_is_letter == right_is_letter)
1253                         continue;
1254
1255                 // we should stop when we have an LTR word on our right or an RTL word
1256                 // on our left
1257                 if ((left_is_letter && temp_cur.paragraph().getFontSettings(
1258                                 temp_cur.buffer()->params(),
1259                                 left_pos).isRightToLeft())
1260                         || (right_is_letter && !temp_cur.paragraph().getFontSettings(
1261                                 temp_cur.buffer()->params(),
1262                                 right_pos).isRightToLeft()))
1263                         break;
1264         }
1265
1266         return setCursor(cur, temp_cur.pit(), temp_cur.pos(),
1267                                          true, temp_cur.boundary());
1268 }
1269
1270
1271 void Text::selectWord(Cursor & cur, word_location loc)
1272 {
1273         LBUFERR(this == cur.text());
1274         CursorSlice from = cur.top();
1275         CursorSlice to = cur.top();
1276         getWord(from, to, loc);
1277         if (cur.top() != from)
1278                 setCursor(cur, from.pit(), from.pos());
1279         if (to == from)
1280                 return;
1281         if (!cur.selection())
1282                 cur.resetAnchor();
1283         setCursor(cur, to.pit(), to.pos());
1284         cur.setSelection();
1285         cur.setWordSelection(true);
1286 }
1287
1288
1289 void Text::selectAll(Cursor & cur)
1290 {
1291         LBUFERR(this == cur.text());
1292         if (cur.lastpos() == 0 && cur.lastpit() == 0)
1293                 return;
1294         // If the cursor is at the beginning, make sure the cursor ends there
1295         if (cur.pit() == 0 && cur.pos() == 0) {
1296                 setCursor(cur, cur.lastpit(), getPar(cur.lastpit()).size());
1297                 cur.resetAnchor();
1298                 setCursor(cur, 0, 0);
1299         } else {
1300                 setCursor(cur, 0, 0);
1301                 cur.resetAnchor();
1302                 setCursor(cur, cur.lastpit(), getPar(cur.lastpit()).size());
1303         }
1304         cur.setSelection();
1305 }
1306
1307
1308 // Select the word currently under the cursor when no
1309 // selection is currently set
1310 bool Text::selectWordWhenUnderCursor(Cursor & cur, word_location loc)
1311 {
1312         LBUFERR(this == cur.text());
1313         if (cur.selection())
1314                 return false;
1315         selectWord(cur, loc);
1316         return cur.selection();
1317 }
1318
1319
1320 void Text::acceptOrRejectChanges(Cursor & cur, ChangeOp op)
1321 {
1322         LBUFERR(this == cur.text());
1323
1324         if (!cur.selection()) {
1325                 if (!selectChange(cur))
1326                         return;
1327         }
1328
1329         cur.recordUndoSelection();
1330
1331         pit_type begPit = cur.selectionBegin().pit();
1332         pit_type endPit = cur.selectionEnd().pit();
1333
1334         pos_type begPos = cur.selectionBegin().pos();
1335         pos_type endPos = cur.selectionEnd().pos();
1336
1337         // keep selection info, because endPos becomes invalid after the first loop
1338         bool endsBeforeEndOfPar = (endPos < pars_[endPit].size());
1339
1340         // first, accept/reject changes within each individual paragraph (do not consider end-of-par)
1341         for (pit_type pit = begPit; pit <= endPit; ++pit) {
1342                 pos_type parSize = pars_[pit].size();
1343
1344                 // ignore empty paragraphs; otherwise, an assertion will fail for
1345                 // acceptChanges(bparams, 0, 0) or rejectChanges(bparams, 0, 0)
1346                 if (parSize == 0)
1347                         continue;
1348
1349                 // do not consider first paragraph if the cursor starts at pos size()
1350                 if (pit == begPit && begPos == parSize)
1351                         continue;
1352
1353                 // do not consider last paragraph if the cursor ends at pos 0
1354                 if (pit == endPit && endPos == 0)
1355                         break; // last iteration anyway
1356
1357                 pos_type left  = (pit == begPit ? begPos : 0);
1358                 pos_type right = (pit == endPit ? endPos : parSize);
1359
1360                 if (left == right)
1361                         // there is no change here
1362                         continue;
1363
1364                 if (op == ACCEPT) {
1365                         pars_[pit].acceptChanges(left, right);
1366                 } else {
1367                         pars_[pit].rejectChanges(left, right);
1368                 }
1369         }
1370
1371         // next, accept/reject imaginary end-of-par characters
1372
1373         for (pit_type pit = begPit; pit <= endPit; ++pit) {
1374                 pos_type pos = pars_[pit].size();
1375
1376                 // skip if the selection ends before the end-of-par
1377                 if (pit == endPit && endsBeforeEndOfPar)
1378                         break; // last iteration anyway
1379
1380                 // skip if this is not the last paragraph of the document
1381                 // note: the user should be able to accept/reject the par break of the last par!
1382                 if (pit == endPit && pit + 1 != int(pars_.size()))
1383                         break; // last iteration anway
1384
1385                 if (op == ACCEPT) {
1386                         if (pars_[pit].isInserted(pos)) {
1387                                 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1388                         } else if (pars_[pit].isDeleted(pos)) {
1389                                 if (pit + 1 == int(pars_.size())) {
1390                                         // we cannot remove a par break at the end of the last paragraph;
1391                                         // instead, we mark it unchanged
1392                                         pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1393                                 } else {
1394                                         mergeParagraph(cur.buffer()->params(), pars_, pit);
1395                                         --endPit;
1396                                         --pit;
1397                                 }
1398                         }
1399                 } else {
1400                         if (pars_[pit].isDeleted(pos)) {
1401                                 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1402                         } else if (pars_[pit].isInserted(pos)) {
1403                                 if (pit + 1 == int(pars_.size())) {
1404                                         // we mark the par break at the end of the last paragraph unchanged
1405                                         pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1406                                 } else {
1407                                         mergeParagraph(cur.buffer()->params(), pars_, pit);
1408                                         --endPit;
1409                                         --pit;
1410                                 }
1411                         }
1412                 }
1413         }
1414
1415         // finally, invoke the DEPM
1416         deleteEmptyParagraphMechanism(begPit, endPit, cur.buffer()->params().track_changes);
1417
1418         cur.finishUndo();
1419         cur.clearSelection();
1420         setCursorIntern(cur, begPit, begPos);
1421         cur.screenUpdateFlags(Update::Force);
1422         cur.forceBufferUpdate();
1423 }
1424
1425
1426 void Text::acceptChanges()
1427 {
1428         BufferParams const & bparams = owner_->buffer().params();
1429         lyx::acceptChanges(pars_, bparams);
1430         deleteEmptyParagraphMechanism(0, pars_.size() - 1, bparams.track_changes);
1431 }
1432
1433
1434 void Text::rejectChanges()
1435 {
1436         BufferParams const & bparams = owner_->buffer().params();
1437         pit_type pars_size = static_cast<pit_type>(pars_.size());
1438
1439         // first, reject changes within each individual paragraph
1440         // (do not consider end-of-par)
1441         for (pit_type pit = 0; pit < pars_size; ++pit) {
1442                 if (!pars_[pit].empty())   // prevent assertion failure
1443                         pars_[pit].rejectChanges(0, pars_[pit].size());
1444         }
1445
1446         // next, reject imaginary end-of-par characters
1447         for (pit_type pit = 0; pit < pars_size; ++pit) {
1448                 pos_type pos = pars_[pit].size();
1449
1450                 if (pars_[pit].isDeleted(pos)) {
1451                         pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1452                 } else if (pars_[pit].isInserted(pos)) {
1453                         if (pit == pars_size - 1) {
1454                                 // we mark the par break at the end of the last
1455                                 // paragraph unchanged
1456                                 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
1457                         } else {
1458                                 mergeParagraph(bparams, pars_, pit);
1459                                 --pit;
1460                                 --pars_size;
1461                         }
1462                 }
1463         }
1464
1465         // finally, invoke the DEPM
1466         deleteEmptyParagraphMechanism(0, pars_size - 1, bparams.track_changes);
1467 }
1468
1469
1470 void Text::deleteWordForward(Cursor & cur)
1471 {
1472         LBUFERR(this == cur.text());
1473         if (cur.lastpos() == 0)
1474                 cursorForward(cur);
1475         else {
1476                 cur.resetAnchor();
1477                 cur.setSelection(true);
1478                 cursorForwardOneWord(cur);
1479                 cur.setSelection();
1480                 cutSelection(cur, true, false);
1481                 cur.checkBufferStructure();
1482         }
1483 }
1484
1485
1486 void Text::deleteWordBackward(Cursor & cur)
1487 {
1488         LBUFERR(this == cur.text());
1489         if (cur.lastpos() == 0)
1490                 cursorBackward(cur);
1491         else {
1492                 cur.resetAnchor();
1493                 cur.setSelection(true);
1494                 cursorBackwardOneWord(cur);
1495                 cur.setSelection();
1496                 cutSelection(cur, true, false);
1497                 cur.checkBufferStructure();
1498         }
1499 }
1500
1501
1502 // Kill to end of line.
1503 void Text::changeCase(Cursor & cur, TextCase action)
1504 {
1505         LBUFERR(this == cur.text());
1506         CursorSlice from;
1507         CursorSlice to;
1508
1509         bool gotsel = false;
1510         if (cur.selection()) {
1511                 from = cur.selBegin();
1512                 to = cur.selEnd();
1513                 gotsel = true;
1514         } else {
1515                 from = cur.top();
1516                 getWord(from, to, PARTIAL_WORD);
1517                 cursorForwardOneWord(cur);
1518         }
1519
1520         cur.recordUndoSelection();
1521
1522         pit_type begPit = from.pit();
1523         pit_type endPit = to.pit();
1524
1525         pos_type begPos = from.pos();
1526         pos_type endPos = to.pos();
1527
1528         pos_type right = 0; // needed after the for loop
1529
1530         for (pit_type pit = begPit; pit <= endPit; ++pit) {
1531                 Paragraph & par = pars_[pit];
1532                 pos_type const pos = (pit == begPit ? begPos : 0);
1533                 right = (pit == endPit ? endPos : par.size());
1534                 par.changeCase(cur.buffer()->params(), pos, right, action);
1535         }
1536
1537         // the selection may have changed due to logically-only deleted chars
1538         if (gotsel) {
1539                 setCursor(cur, begPit, begPos);
1540                 cur.resetAnchor();
1541                 setCursor(cur, endPit, right);
1542                 cur.setSelection();
1543         } else
1544                 setCursor(cur, endPit, right);
1545
1546         cur.checkBufferStructure();
1547 }
1548
1549
1550 bool Text::handleBibitems(Cursor & cur)
1551 {
1552         if (cur.paragraph().layout().labeltype != LABEL_BIBLIO)
1553                 return false;
1554
1555         if (cur.pos() != 0)
1556                 return false;
1557
1558         BufferParams const & bufparams = cur.buffer()->params();
1559         Paragraph const & par = cur.paragraph();
1560         Cursor prevcur = cur;
1561         if (cur.pit() > 0) {
1562                 --prevcur.pit();
1563                 prevcur.pos() = prevcur.lastpos();
1564         }
1565         Paragraph const & prevpar = prevcur.paragraph();
1566
1567         // if a bibitem is deleted, merge with previous paragraph
1568         // if this is a bibliography item as well
1569         if (cur.pit() > 0 && par.layout() == prevpar.layout()) {
1570                 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
1571                 mergeParagraph(bufparams, cur.text()->paragraphs(),
1572                                                         prevcur.pit());
1573                 cur.forceBufferUpdate();
1574                 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1575                 cur.screenUpdateFlags(Update::Force);
1576                 return true;
1577         }
1578
1579         // otherwise reset to default
1580         cur.paragraph().setPlainOrDefaultLayout(bufparams.documentClass());
1581         return true;
1582 }
1583
1584
1585 bool Text::erase(Cursor & cur)
1586 {
1587         LASSERT(this == cur.text(), return false);
1588         bool needsUpdate = false;
1589         Paragraph & par = cur.paragraph();
1590
1591         if (cur.pos() != cur.lastpos()) {
1592                 // this is the code for a normal delete, not pasting
1593                 // any paragraphs
1594                 cur.recordUndo(DELETE_UNDO);
1595                 bool const was_inset = cur.paragraph().isInset(cur.pos());
1596                 if(!par.eraseChar(cur.pos(), cur.buffer()->params().track_changes))
1597                         // the character has been logically deleted only => skip it
1598                         cur.top().forwardPos();
1599
1600                 if (was_inset)
1601                         cur.forceBufferUpdate();
1602                 else
1603                         cur.checkBufferStructure();
1604                 needsUpdate = true;
1605         } else {
1606                 if (cur.pit() == cur.lastpit())
1607                         return dissolveInset(cur);
1608
1609                 if (!par.isMergedOnEndOfParDeletion(cur.buffer()->params().track_changes)) {
1610                         par.setChange(cur.pos(), Change(Change::DELETED));
1611                         cur.forwardPos();
1612                         needsUpdate = true;
1613                 } else {
1614                         setCursorIntern(cur, cur.pit() + 1, 0);
1615                         needsUpdate = backspacePos0(cur);
1616                 }
1617         }
1618
1619         needsUpdate |= handleBibitems(cur);
1620
1621         if (needsUpdate) {
1622                 // Make sure the cursor is correct. Is this really needed?
1623                 // No, not really... at least not here!
1624                 cur.text()->setCursor(cur.top(), cur.pit(), cur.pos());
1625                 cur.checkBufferStructure();
1626         }
1627
1628         return needsUpdate;
1629 }
1630
1631
1632 bool Text::backspacePos0(Cursor & cur)
1633 {
1634         LBUFERR(this == cur.text());
1635         if (cur.pit() == 0)
1636                 return false;
1637
1638         bool needsUpdate = false;
1639
1640         BufferParams const & bufparams = cur.buffer()->params();
1641         DocumentClass const & tclass = bufparams.documentClass();
1642         ParagraphList & plist = cur.text()->paragraphs();
1643         Paragraph const & par = cur.paragraph();
1644         Cursor prevcur = cur;
1645         --prevcur.pit();
1646         prevcur.pos() = prevcur.lastpos();
1647         Paragraph const & prevpar = prevcur.paragraph();
1648
1649         // is it an empty paragraph?
1650         if (cur.lastpos() == 0
1651             || (cur.lastpos() == 1 && par.isSeparator(0))) {
1652                 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1653                 plist.erase(boost::next(plist.begin(), cur.pit()));
1654                 needsUpdate = true;
1655         }
1656         // is previous par empty?
1657         else if (prevcur.lastpos() == 0
1658                  || (prevcur.lastpos() == 1 && prevpar.isSeparator(0))) {
1659                 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1660                 plist.erase(boost::next(plist.begin(), prevcur.pit()));
1661                 needsUpdate = true;
1662         }
1663         // Pasting is not allowed, if the paragraphs have different
1664         // layouts. I think it is a real bug of all other
1665         // word processors to allow it. It confuses the user.
1666         // Correction: Pasting is always allowed with standard-layout
1667         // or the empty layout.
1668         else if (par.layout() == prevpar.layout()
1669                  || tclass.isDefaultLayout(par.layout())
1670                  || tclass.isPlainLayout(par.layout())) {
1671                 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
1672                 mergeParagraph(bufparams, plist, prevcur.pit());
1673                 needsUpdate = true;
1674         }
1675
1676         if (needsUpdate) {
1677                 cur.forceBufferUpdate();
1678                 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1679         }
1680
1681         return needsUpdate;
1682 }
1683
1684
1685 bool Text::backspace(Cursor & cur)
1686 {
1687         LBUFERR(this == cur.text());
1688         bool needsUpdate = false;
1689         if (cur.pos() == 0) {
1690                 if (cur.pit() == 0)
1691                         return dissolveInset(cur);
1692
1693                 Cursor prev_cur = cur;
1694                 --prev_cur.pit();
1695
1696                 if (!prev_cur.paragraph().isMergedOnEndOfParDeletion(cur.buffer()->params().track_changes)) {
1697                         cur.recordUndo(ATOMIC_UNDO, prev_cur.pit(), prev_cur.pit());
1698                         prev_cur.paragraph().setChange(prev_cur.lastpos(), Change(Change::DELETED));
1699                         setCursorIntern(cur, prev_cur.pit(), prev_cur.lastpos());
1700                         return true;
1701                 }
1702                 // The cursor is at the beginning of a paragraph, so
1703                 // the backspace will collapse two paragraphs into one.
1704                 needsUpdate = backspacePos0(cur);
1705
1706         } else {
1707                 // this is the code for a normal backspace, not pasting
1708                 // any paragraphs
1709                 cur.recordUndo(DELETE_UNDO);
1710                 // We used to do cursorBackwardIntern() here, but it is
1711                 // not a good idea since it triggers the auto-delete
1712                 // mechanism. So we do a cursorBackwardIntern()-lite,
1713                 // without the dreaded mechanism. (JMarc)
1714                 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1715                                 false, cur.boundary());
1716                 bool const was_inset = cur.paragraph().isInset(cur.pos());
1717                 cur.paragraph().eraseChar(cur.pos(), cur.buffer()->params().track_changes);
1718                 if (was_inset)
1719                         cur.forceBufferUpdate();
1720                 else
1721                         cur.checkBufferStructure();
1722         }
1723
1724         if (cur.pos() == cur.lastpos())
1725                 cur.setCurrentFont();
1726
1727         needsUpdate |= handleBibitems(cur);
1728
1729         // A singlePar update is not enough in this case.
1730 //              cur.screenUpdateFlags(Update::Force);
1731         setCursor(cur.top(), cur.pit(), cur.pos());
1732
1733         return needsUpdate;
1734 }
1735
1736
1737 bool Text::dissolveInset(Cursor & cur)
1738 {
1739         LASSERT(this == cur.text(), return false);
1740
1741         if (isMainText() || cur.inset().nargs() != 1)
1742                 return false;
1743
1744         cur.recordUndoInset();
1745         cur.setMark(false);
1746         cur.selHandle(false);
1747         // save position
1748         pos_type spos = cur.pos();
1749         pit_type spit = cur.pit();
1750         ParagraphList plist;
1751         if (cur.lastpit() != 0 || cur.lastpos() != 0)
1752                 plist = paragraphs();
1753         cur.popBackward();
1754         // store cursor offset
1755         if (spit == 0)
1756                 spos += cur.pos();
1757         spit += cur.pit();
1758         Buffer & b = *cur.buffer();
1759         cur.paragraph().eraseChar(cur.pos(), b.params().track_changes);
1760
1761         if (!plist.empty()) {
1762                 // see bug 7319
1763                 // we clear the cache so that we won't get conflicts with labels
1764                 // that get pasted into the buffer. we should update this before
1765                 // its being empty matters. if not (i.e., if we encounter bugs),
1766                 // then this should instead be:
1767                 //        cur.buffer().updateBuffer();
1768                 // but we'll try the cheaper solution here.
1769                 cur.buffer()->clearReferenceCache();
1770
1771                 // ERT paragraphs have the Language latex_language.
1772                 // This is invalid outside of ERT, so we need to
1773                 // change it to the buffer language.
1774                 ParagraphList::iterator it = plist.begin();
1775                 ParagraphList::iterator it_end = plist.end();
1776                 for (; it != it_end; ++it)
1777                         it->changeLanguage(b.params(), latex_language, b.language());
1778
1779                 pasteParagraphList(cur, plist, b.params().documentClassPtr(),
1780                                    b.errorList("Paste"));
1781                 // restore position
1782                 cur.pit() = min(cur.lastpit(), spit);
1783                 cur.pos() = min(cur.lastpos(), spos);
1784         }
1785
1786         cur.forceBufferUpdate();
1787
1788         // Ensure the current language is set correctly (bug 6292)
1789         cur.text()->setCursor(cur, cur.pit(), cur.pos());
1790         cur.clearSelection();
1791         cur.resetAnchor();
1792         return true;
1793 }
1794
1795
1796 void Text::getWord(CursorSlice & from, CursorSlice & to,
1797         word_location const loc) const
1798 {
1799         to = from;
1800         pars_[to.pit()].locateWord(from.pos(), to.pos(), loc);
1801 }
1802
1803
1804 void Text::write(ostream & os) const
1805 {
1806         Buffer const & buf = owner_->buffer();
1807         ParagraphList::const_iterator pit = paragraphs().begin();
1808         ParagraphList::const_iterator end = paragraphs().end();
1809         depth_type dth = 0;
1810         for (; pit != end; ++pit)
1811                 pit->write(os, buf.params(), dth);
1812
1813         // Close begin_deeper
1814         for(; dth > 0; --dth)
1815                 os << "\n\\end_deeper";
1816 }
1817
1818
1819 bool Text::read(Lexer & lex,
1820                 ErrorList & errorList, InsetText * insetPtr)
1821 {
1822         Buffer const & buf = owner_->buffer();
1823         depth_type depth = 0;
1824         bool res = true;
1825
1826         while (lex.isOK()) {
1827                 lex.nextToken();
1828                 string const token = lex.getString();
1829
1830                 if (token.empty())
1831                         continue;
1832
1833                 if (token == "\\end_inset")
1834                         break;
1835
1836                 if (token == "\\end_body")
1837                         continue;
1838
1839                 if (token == "\\begin_body")
1840                         continue;
1841
1842                 if (token == "\\end_document") {
1843                         res = false;
1844                         break;
1845                 }
1846
1847                 if (token == "\\begin_layout") {
1848                         lex.pushToken(token);
1849
1850                         Paragraph par;
1851                         par.setInsetOwner(insetPtr);
1852                         par.params().depth(depth);
1853                         par.setFont(0, Font(inherit_font, buf.params().language));
1854                         pars_.push_back(par);
1855                         readParagraph(pars_.back(), lex, errorList);
1856
1857                         // register the words in the global word list
1858                         pars_.back().updateWords();
1859                 } else if (token == "\\begin_deeper") {
1860                         ++depth;
1861                 } else if (token == "\\end_deeper") {
1862                         if (!depth)
1863                                 lex.printError("\\end_deeper: " "depth is already null");
1864                         else
1865                                 --depth;
1866                 } else {
1867                         LYXERR0("Handling unknown body token: `" << token << '\'');
1868                 }
1869         }
1870
1871         // avoid a crash on weird documents (bug 4859)
1872         if (pars_.empty()) {
1873                 Paragraph par;
1874                 par.setInsetOwner(insetPtr);
1875                 par.params().depth(depth);
1876                 par.setFont(0, Font(inherit_font,
1877                                     buf.params().language));
1878                 par.setPlainOrDefaultLayout(buf.params().documentClass());
1879                 pars_.push_back(par);
1880         }
1881
1882         return res;
1883 }
1884
1885
1886 // Returns the current font and depth as a message.
1887 docstring Text::currentState(Cursor const & cur) const
1888 {
1889         LBUFERR(this == cur.text());
1890         Buffer & buf = *cur.buffer();
1891         Paragraph const & par = cur.paragraph();
1892         odocstringstream os;
1893
1894         if (buf.params().track_changes)
1895                 os << _("[Change Tracking] ");
1896
1897         Change change = par.lookupChange(cur.pos());
1898
1899         if (change.changed()) {
1900                 Author const & a = buf.params().authors().get(change.author);
1901                 os << _("Change: ") << a.name();
1902                 if (!a.email().empty())
1903                         os << " (" << a.email() << ")";
1904                 // FIXME ctime is english, we should translate that
1905                 os << _(" at ") << ctime(&change.changetime);
1906                 os << " : ";
1907         }
1908
1909         // I think we should only show changes from the default
1910         // font. (Asger)
1911         // No, from the document font (MV)
1912         Font font = cur.real_current_font;
1913         font.fontInfo().reduce(buf.params().getFont().fontInfo());
1914
1915         os << bformat(_("Font: %1$s"), font.stateText(&buf.params()));
1916
1917         // The paragraph depth
1918         int depth = cur.paragraph().getDepth();
1919         if (depth > 0)
1920                 os << bformat(_(", Depth: %1$d"), depth);
1921
1922         // The paragraph spacing, but only if different from
1923         // buffer spacing.
1924         Spacing const & spacing = par.params().spacing();
1925         if (!spacing.isDefault()) {
1926                 os << _(", Spacing: ");
1927                 switch (spacing.getSpace()) {
1928                 case Spacing::Single:
1929                         os << _("Single");
1930                         break;
1931                 case Spacing::Onehalf:
1932                         os << _("OneHalf");
1933                         break;
1934                 case Spacing::Double:
1935                         os << _("Double");
1936                         break;
1937                 case Spacing::Other:
1938                         os << _("Other (") << from_ascii(spacing.getValueAsString()) << ')';
1939                         break;
1940                 case Spacing::Default:
1941                         // should never happen, do nothing
1942                         break;
1943                 }
1944         }
1945
1946 #ifdef DEVEL_VERSION
1947         os << _(", Inset: ") << &cur.inset();
1948         os << _(", Paragraph: ") << cur.pit();
1949         os << _(", Id: ") << par.id();
1950         os << _(", Position: ") << cur.pos();
1951         // FIXME: Why is the check for par.size() needed?
1952         // We are called with cur.pos() == par.size() quite often.
1953         if (!par.empty() && cur.pos() < par.size()) {
1954                 // Force output of code point, not character
1955                 size_t const c = par.getChar(cur.pos());
1956                 os << _(", Char: 0x") << hex << c;
1957         }
1958         os << _(", Boundary: ") << cur.boundary();
1959 //      Row & row = cur.textRow();
1960 //      os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
1961 #endif
1962         return os.str();
1963 }
1964
1965
1966 docstring Text::getPossibleLabel(Cursor const & cur) const
1967 {
1968         pit_type pit = cur.pit();
1969
1970         Layout const * layout = &(pars_[pit].layout());
1971
1972         docstring text;
1973         docstring par_text = pars_[pit].asString();
1974
1975         // The return string of math matrices might contain linebreaks
1976         par_text = subst(par_text, '\n', '-');
1977         int const numwords = 3;
1978         for (int i = 0; i < numwords; ++i) {
1979                 if (par_text.empty())
1980                         break;
1981                 docstring head;
1982                 par_text = split(par_text, head, ' ');
1983                 // Is it legal to use spaces in labels ?
1984                 if (i > 0)
1985                         text += '-';
1986                 text += head;
1987         }
1988
1989         // Make sure it isn't too long
1990         unsigned int const max_label_length = 32;
1991         if (text.size() > max_label_length)
1992                 text.resize(max_label_length);
1993
1994         // Will contain the label prefix.
1995         docstring name;
1996
1997         // For section, subsection, etc...
1998         if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
1999                 Layout const * layout2 = &(pars_[pit - 1].layout());
2000                 if (layout2->latextype != LATEX_PARAGRAPH) {
2001                         --pit;
2002                         layout = layout2;
2003                 }
2004         }
2005         if (layout->latextype != LATEX_PARAGRAPH)
2006                 name = layout->refprefix;
2007
2008         // For captions, we just take the caption type
2009         Inset * caption_inset = cur.innerInsetOfType(CAPTION_CODE);
2010         if (caption_inset) {
2011                 string const & ftype = static_cast<InsetCaption *>(caption_inset)->floattype();
2012                 FloatList const & fl = cur.buffer()->params().documentClass().floats();
2013                 if (fl.typeExist(ftype)) {
2014                         Floating const & flt = fl.getType(ftype);
2015                         name = from_utf8(flt.refPrefix());
2016                 }
2017                 if (name.empty())
2018                         name = from_utf8(ftype.substr(0,3));
2019         }
2020
2021         // If none of the above worked, see if the inset knows.
2022         if (name.empty()) {
2023                 InsetLayout const & il = cur.inset().getLayout();
2024                 name = il.refprefix();
2025         }
2026
2027         if (!name.empty())
2028                 text = name + ':' + text;
2029
2030         // We need a unique label
2031         docstring label = text;
2032         int i = 1;
2033         while (cur.buffer()->insetLabel(label)) {
2034                         label = text + '-' + convert<docstring>(i);
2035                         ++i;
2036                 }
2037
2038         return label;
2039 }
2040
2041
2042 docstring Text::asString(int options) const
2043 {
2044         return asString(0, pars_.size(), options);
2045 }
2046
2047
2048 docstring Text::asString(pit_type beg, pit_type end, int options) const
2049 {
2050         size_t i = size_t(beg);
2051         docstring str = pars_[i].asString(options);
2052         for (++i; i != size_t(end); ++i) {
2053                 str += '\n';
2054                 str += pars_[i].asString(options);
2055         }
2056         return str;
2057 }
2058
2059
2060 void Text::forOutliner(docstring & os, size_t maxlen, bool shorten) const
2061 {
2062         if (maxlen == 0)
2063                 maxlen = std::numeric_limits<std::size_t>::max();
2064         else
2065                 LASSERT(maxlen >= 8, maxlen = TOC_ENTRY_LENGTH);
2066         for (size_t i = 0; i != pars_.size() && os.length() < maxlen; ++i)
2067                 pars_[i].forOutliner(os, maxlen);
2068         if (shorten && os.length() >= maxlen)
2069                 os = os.substr(0, maxlen - 3) + from_ascii("...");
2070 }
2071
2072
2073 void Text::charsTranspose(Cursor & cur)
2074 {
2075         LBUFERR(this == cur.text());
2076
2077         pos_type pos = cur.pos();
2078
2079         // If cursor is at beginning or end of paragraph, do nothing.
2080         if (pos == cur.lastpos() || pos == 0)
2081                 return;
2082
2083         Paragraph & par = cur.paragraph();
2084
2085         // Get the positions of the characters to be transposed.
2086         pos_type pos1 = pos - 1;
2087         pos_type pos2 = pos;
2088
2089         // In change tracking mode, ignore deleted characters.
2090         while (pos2 < cur.lastpos() && par.isDeleted(pos2))
2091                 ++pos2;
2092         if (pos2 == cur.lastpos())
2093                 return;
2094
2095         while (pos1 >= 0 && par.isDeleted(pos1))
2096                 --pos1;
2097         if (pos1 < 0)
2098                 return;
2099
2100         // Don't do anything if one of the "characters" is not regular text.
2101         if (par.isInset(pos1) || par.isInset(pos2))
2102                 return;
2103
2104         // Store the characters to be transposed (including font information).
2105         char_type const char1 = par.getChar(pos1);
2106         Font const font1 =
2107                 par.getFontSettings(cur.buffer()->params(), pos1);
2108
2109         char_type const char2 = par.getChar(pos2);
2110         Font const font2 =
2111                 par.getFontSettings(cur.buffer()->params(), pos2);
2112
2113         // And finally, we are ready to perform the transposition.
2114         // Track the changes if Change Tracking is enabled.
2115         bool const trackChanges = cur.buffer()->params().track_changes;
2116
2117         cur.recordUndo();
2118
2119         par.eraseChar(pos2, trackChanges);
2120         par.eraseChar(pos1, trackChanges);
2121         par.insertChar(pos1, char2, font2, trackChanges);
2122         par.insertChar(pos2, char1, font1, trackChanges);
2123
2124         cur.checkBufferStructure();
2125
2126         // After the transposition, move cursor to after the transposition.
2127         setCursor(cur, cur.pit(), pos2);
2128         cur.forwardPos();
2129 }
2130
2131
2132 DocIterator Text::macrocontextPosition() const
2133 {
2134         return macrocontext_position_;
2135 }
2136
2137
2138 void Text::setMacrocontextPosition(DocIterator const & pos)
2139 {
2140         macrocontext_position_ = pos;
2141 }
2142
2143
2144 docstring Text::previousWord(CursorSlice const & sl) const
2145 {
2146         CursorSlice from = sl;
2147         CursorSlice to = sl;
2148         getWord(from, to, PREVIOUS_WORD);
2149         if (sl == from || to == from)
2150                 return docstring();
2151
2152         Paragraph const & par = sl.paragraph();
2153         return par.asString(from.pos(), to.pos());
2154 }
2155
2156
2157 bool Text::completionSupported(Cursor const & cur) const
2158 {
2159         Paragraph const & par = cur.paragraph();
2160         return cur.pos() > 0
2161                 && (cur.pos() >= par.size() || par.isWordSeparator(cur.pos()))
2162                 && !par.isWordSeparator(cur.pos() - 1);
2163 }
2164
2165
2166 CompletionList const * Text::createCompletionList(Cursor const & cur) const
2167 {
2168         WordList const * list = theWordList(cur.getFont().language()->lang());
2169         return new TextCompletionList(cur, list);
2170 }
2171
2172
2173 bool Text::insertCompletion(Cursor & cur, docstring const & s, bool /*finished*/)
2174 {
2175         LBUFERR(cur.bv().cursor() == cur);
2176         cur.insert(s);
2177         cur.bv().cursor() = cur;
2178         if (!(cur.result().screenUpdate() & Update::Force))
2179                 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
2180         return true;
2181 }
2182
2183
2184 docstring Text::completionPrefix(Cursor const & cur) const
2185 {
2186         return previousWord(cur.top());
2187 }
2188
2189 } // namespace lyx