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