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