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