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