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