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