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