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