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