]> git.lyx.org Git - lyx.git/blob - src/Text.cpp
Tweaks.
[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 "Cursor.h"
30 #include "ParIterator.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 "FontIterator.h"
38 #include "Language.h"
39 #include "Length.h"
40 #include "Lexer.h"
41 #include "LyXRC.h"
42 #include "Paragraph.h"
43 #include "paragraph_funcs.h"
44 #include "ParagraphParameters.h"
45 #include "TextClass.h"
46 #include "TextMetrics.h"
47 #include "VSpace.h"
48 #include "WordLangTuple.h"
49
50 #include "frontends/FontMetrics.h"
51 #include "frontends/Painter.h"
52
53 #include "insets/InsetText.h"
54 #include "insets/InsetBibitem.h"
55 #include "insets/InsetCaption.h"
56 #include "insets/InsetHFill.h"
57 #include "insets/InsetLine.h"
58 #include "insets/InsetNewline.h"
59 #include "insets/InsetNewpage.h"
60 #include "insets/InsetOptArg.h"
61 #include "insets/InsetSpace.h"
62 #include "insets/InsetSpecialChar.h"
63 #include "insets/InsetTabular.h"
64
65 #include "support/convert.h"
66 #include "support/debug.h"
67 #include "support/docstream.h"
68 #include "support/gettext.h"
69 #include "support/lstrings.h"
70 #include "support/textutils.h"
71
72 #include <boost/next_prior.hpp>
73
74 #include <sstream>
75
76 using namespace std;
77 using namespace lyx::support;
78
79 namespace lyx {
80
81 using cap::cutSelection;
82 using cap::pasteParagraphList;
83
84 using frontend::FontMetrics;
85
86 namespace {
87
88 void readParToken(Buffer const & buf, Paragraph & par, Lexer & lex,
89         string const & token, Font & font, Change & change, ErrorList & errorList)
90 {
91         BufferParams const & bp = buf.params();
92
93         if (token[0] != '\\') {
94                 docstring dstr = lex.getDocString();
95                 par.appendString(dstr, font, change);
96
97         } else if (token == "\\begin_layout") {
98                 lex.eatLine();
99                 docstring layoutname = lex.getDocString();
100
101                 font = Font(inherit_font, bp.language);
102                 change = Change(Change::UNCHANGED);
103
104                 TextClass const & tclass = bp.getTextClass();
105
106                 if (layoutname.empty()) {
107                         layoutname = tclass.defaultLayoutName();
108                 }
109
110                 bool hasLayout = tclass.hasLayout(layoutname);
111
112                 if (!hasLayout) {
113                         errorList.push_back(ErrorItem(_("Unknown layout"),
114                         bformat(_("Layout '%1$s' does not exist in textclass '%2$s'\nTrying to use the default instead.\n"),
115                         layoutname, from_utf8(tclass.name())), par.id(), 0, par.size()));
116                         layoutname = tclass.defaultLayoutName();
117                 }
118
119                 par.layout(bp.getTextClass()[layoutname]);
120
121                 // Test whether the layout is obsolete.
122                 LayoutPtr const & layout = par.layout();
123                 if (!layout->obsoleted_by().empty())
124                         par.layout(bp.getTextClass()[layout->obsoleted_by()]);
125
126                 par.params().read(lex);
127
128         } else if (token == "\\end_layout") {
129                 LYXERR0("Solitary \\end_layout in line " << lex.getLineNo() << "\n"
130                        << "Missing \\begin_layout ?");
131         } else if (token == "\\end_inset") {
132                 LYXERR0("Solitary \\end_inset in line " << lex.getLineNo() << "\n"
133                        << "Missing \\begin_inset ?");
134         } else if (token == "\\begin_inset") {
135                 Inset * inset = readInset(lex, buf);
136                 if (inset)
137                         par.insertInset(par.size(), inset, font, change);
138                 else {
139                         lex.eatLine();
140                         docstring line = lex.getDocString();
141                         errorList.push_back(ErrorItem(_("Unknown Inset"), line,
142                                             par.id(), 0, par.size()));
143                 }
144         } else if (token == "\\family") {
145                 lex.next();
146                 setLyXFamily(lex.getString(), font.fontInfo());
147         } else if (token == "\\series") {
148                 lex.next();
149                 setLyXSeries(lex.getString(), font.fontInfo());
150         } else if (token == "\\shape") {
151                 lex.next();
152                 setLyXShape(lex.getString(), font.fontInfo());
153         } else if (token == "\\size") {
154                 lex.next();
155                 setLyXSize(lex.getString(), font.fontInfo());
156         } else if (token == "\\lang") {
157                 lex.next();
158                 string const tok = lex.getString();
159                 Language const * lang = languages.getLanguage(tok);
160                 if (lang) {
161                         font.setLanguage(lang);
162                 } else {
163                         font.setLanguage(bp.language);
164                         lex.printError("Unknown language `$$Token'");
165                 }
166         } else if (token == "\\numeric") {
167                 lex.next();
168                 font.fontInfo().setNumber(font.setLyXMisc(lex.getString()));
169         } else if (token == "\\emph") {
170                 lex.next();
171                 font.fontInfo().setEmph(font.setLyXMisc(lex.getString()));
172         } else if (token == "\\bar") {
173                 lex.next();
174                 string const tok = lex.getString();
175
176                 if (tok == "under")
177                         font.fontInfo().setUnderbar(FONT_ON);
178                 else if (tok == "no")
179                         font.fontInfo().setUnderbar(FONT_OFF);
180                 else if (tok == "default")
181                         font.fontInfo().setUnderbar(FONT_INHERIT);
182                 else
183                         lex.printError("Unknown bar font flag "
184                                        "`$$Token'");
185         } else if (token == "\\noun") {
186                 lex.next();
187                 font.fontInfo().setNoun(font.setLyXMisc(lex.getString()));
188         } else if (token == "\\color") {
189                 lex.next();
190                 setLyXColor(lex.getString(), font.fontInfo());
191         } else if (token == "\\InsetSpace" || token == "\\SpecialChar") {
192
193                 // Insets don't make sense in a free-spacing context! ---Kayvan
194                 if (par.isFreeSpacing()) {
195                         if (token == "\\InsetSpace")
196                                 par.appendChar(' ', font, change);
197                         else if (lex.isOK()) {
198                                 lex.next();
199                                 string const next_token = lex.getString();
200                                 if (next_token == "\\-")
201                                         par.appendChar('-', font, change);
202                                 else {
203                                         lex.printError("Token `$$Token' "
204                                                        "is in free space "
205                                                        "paragraph layout!");
206                                 }
207                         }
208                 } else {
209                         auto_ptr<Inset> inset;
210                         if (token == "\\SpecialChar" )
211                                 inset.reset(new InsetSpecialChar);
212                         else
213                                 inset.reset(new InsetSpace);
214                         inset->read(buf, lex);
215                         par.insertInset(par.size(), inset.release(),
216                                         font, change);
217                 }
218         } else if (token == "\\backslash") {
219                 par.appendChar('\\', font, change);
220         } else if (token == "\\linebreak") {
221                 auto_ptr<Inset> inset(new InsetLinebreak);
222                 inset->read(buf, lex);
223                 par.insertInset(par.size(), inset.release(), font, change);
224         } else if (token == "\\newline") {
225                 auto_ptr<Inset> inset(new InsetNewline);
226                 inset->read(buf, lex);
227                 par.insertInset(par.size(), inset.release(), font, change);
228         } else if (token == "\\LyXTable") {
229                 auto_ptr<Inset> inset(new InsetTabular(buf));
230                 inset->read(buf, lex);
231                 par.insertInset(par.size(), inset.release(), font, change);
232         } else if (token == "\\hfill") {
233                 par.insertInset(par.size(), new InsetHFill, font, change);
234         } else if (token == "\\lyxline") {
235                 par.insertInset(par.size(), new InsetLine, font, change);
236         } else if (token == "\\newpage") {
237                 par.insertInset(par.size(), new InsetNewpage, font, change);
238         } else if (token == "\\pagebreak") {
239                 par.insertInset(par.size(), new InsetPagebreak, font, change);
240         } else if (token == "\\clearpage") {
241                 par.insertInset(par.size(), new InsetClearPage, font, change);
242         } else if (token == "\\cleardoublepage") {
243                 par.insertInset(par.size(), new InsetClearDoublePage, font, change);
244         } else if (token == "\\change_unchanged") {
245                 change = Change(Change::UNCHANGED);
246         } else if (token == "\\change_inserted") {
247                 lex.eatLine();
248                 istringstream is(lex.getString());
249                 unsigned int aid;
250                 time_t ct;
251                 is >> aid >> ct;
252                 if (aid >= bp.author_map.size()) {
253                         errorList.push_back(ErrorItem(_("Change tracking error"),
254                                             bformat(_("Unknown author index for insertion: %1$d\n"), aid),
255                                             par.id(), 0, par.size()));
256                         change = Change(Change::UNCHANGED);
257                 } else
258                         change = Change(Change::INSERTED, bp.author_map[aid], ct);
259         } else if (token == "\\change_deleted") {
260                 lex.eatLine();
261                 istringstream is(lex.getString());
262                 unsigned int aid;
263                 time_t ct;
264                 is >> aid >> ct;
265                 if (aid >= bp.author_map.size()) {
266                         errorList.push_back(ErrorItem(_("Change tracking error"),
267                                             bformat(_("Unknown author index for deletion: %1$d\n"), aid),
268                                             par.id(), 0, par.size()));
269                         change = Change(Change::UNCHANGED);
270                 } else
271                         change = Change(Change::DELETED, bp.author_map[aid], ct);
272         } else {
273                 lex.eatLine();
274                 errorList.push_back(ErrorItem(_("Unknown token"),
275                         bformat(_("Unknown token: %1$s %2$s\n"), from_utf8(token),
276                         lex.getDocString()),
277                         par.id(), 0, par.size()));
278         }
279 }
280
281
282 void readParagraph(Buffer const & buf, Paragraph & par, Lexer & lex,
283         ErrorList & errorList)
284 {
285         lex.nextToken();
286         string token = lex.getString();
287         Font font;
288         Change change(Change::UNCHANGED);
289
290         while (lex.isOK()) {
291                 readParToken(buf, par, lex, token, font, change, errorList);
292
293                 lex.nextToken();
294                 token = lex.getString();
295
296                 if (token.empty())
297                         continue;
298
299                 if (token == "\\end_layout") {
300                         //Ok, paragraph finished
301                         break;
302                 }
303
304                 LYXERR(Debug::PARSER, "Handling paragraph token: `" << token << '\'');
305                 if (token == "\\begin_layout" || token == "\\end_document"
306                     || token == "\\end_inset" || token == "\\begin_deeper"
307                     || token == "\\end_deeper") {
308                         lex.pushToken(token);
309                         lyxerr << "Paragraph ended in line "
310                                << lex.getLineNo() << "\n"
311                                << "Missing \\end_layout.\n";
312                         break;
313                 }
314         }
315         // Final change goes to paragraph break:
316         par.setChange(par.size(), change);
317
318         // Initialize begin_of_body_ on load; redoParagraph maintains
319         par.setBeginOfBody();
320 }
321
322
323 } // namespace anon
324
325
326 bool Text::empty() const
327 {
328         return pars_.empty() || (pars_.size() == 1 && pars_[0].empty()
329                 // FIXME: Should we consider the labeled type as empty too? 
330                 && pars_[0].layout()->labeltype == LABEL_NO_LABEL);
331 }
332
333
334 double Text::spacing(Buffer const & buffer,
335                 Paragraph const & par) const
336 {
337         if (par.params().spacing().isDefault())
338                 return buffer.params().spacing().getValue();
339         return par.params().spacing().getValue();
340 }
341
342
343 void Text::breakParagraph(Cursor & cur, bool inverse_logic)
344 {
345         BOOST_ASSERT(this == cur.text());
346
347         Paragraph & cpar = cur.paragraph();
348         pit_type cpit = cur.pit();
349
350         TextClass const & tclass = cur.buffer().params().getTextClass();
351         LayoutPtr const & layout = cpar.layout();
352
353         // this is only allowed, if the current paragraph is not empty
354         // or caption and if it has not the keepempty flag active
355         if (cur.lastpos() == 0 && !cpar.allowEmpty() &&
356             layout->labeltype != LABEL_SENSITIVE)
357                 return;
358
359         // a layout change may affect also the following paragraph
360         recUndo(cur, cur.pit(), undoSpan(cur.pit()) - 1);
361
362         // Always break behind a space
363         // It is better to erase the space (Dekel)
364         if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
365                 cpar.eraseChar(cur.pos(), cur.buffer().params().trackChanges);
366
367         // What should the layout for the new paragraph be?
368         bool keep_layout = inverse_logic ? 
369                 !layout->isEnvironment() 
370                 : layout->isEnvironment();
371
372         // We need to remember this before we break the paragraph, because
373         // that invalidates the layout variable
374         bool sensitive = layout->labeltype == LABEL_SENSITIVE;
375
376         // we need to set this before we insert the paragraph.
377         bool const isempty = cpar.allowEmpty() && cpar.empty();
378
379         lyx::breakParagraph(cur.buffer().params(), paragraphs(), cpit,
380                          cur.pos(), keep_layout);
381
382         // After this, neither paragraph contains any rows!
383
384         cpit = cur.pit();
385         pit_type next_par = cpit + 1;
386
387         // well this is the caption hack since one caption is really enough
388         if (sensitive) {
389                 if (cur.pos() == 0)
390                         // set to standard-layout
391                         pars_[cpit].applyLayout(tclass.defaultLayout());
392                 else
393                         // set to standard-layout
394                         pars_[next_par].applyLayout(tclass.defaultLayout());
395         }
396
397         while (!pars_[next_par].empty() && pars_[next_par].isNewline(0)) {
398                 if (!pars_[next_par].eraseChar(0, cur.buffer().params().trackChanges))
399                         break; // the character couldn't be deleted physically due to change tracking
400         }
401
402         updateLabels(cur.buffer());
403
404         // A singlePar update is not enough in this case.
405         cur.updateFlags(Update::Force);
406
407         // This check is necessary. Otherwise the new empty paragraph will
408         // be deleted automatically. And it is more friendly for the user!
409         if (cur.pos() != 0 || isempty)
410                 setCursor(cur, cur.pit() + 1, 0);
411         else
412                 setCursor(cur, cur.pit(), 0);
413 }
414
415
416 // insert a character, moves all the following breaks in the
417 // same Paragraph one to the right and make a rebreak
418 void Text::insertChar(Cursor & cur, char_type c)
419 {
420         BOOST_ASSERT(this == cur.text());
421
422         cur.recordUndo(INSERT_UNDO);
423
424         TextMetrics const & tm = cur.bv().textMetrics(this);
425         Buffer const & buffer = cur.buffer();
426         Paragraph & par = cur.paragraph();
427         // try to remove this
428         pit_type const pit = cur.pit();
429
430         bool const freeSpacing = par.layout()->free_spacing ||
431                 par.isFreeSpacing();
432
433         if (lyxrc.auto_number) {
434                 static docstring const number_operators = from_ascii("+-/*");
435                 static docstring const number_unary_operators = from_ascii("+-");
436                 static docstring const number_seperators = from_ascii(".,:");
437
438                 if (cur.current_font.fontInfo().number() == FONT_ON) {
439                         if (!isDigit(c) && !contains(number_operators, c) &&
440                             !(contains(number_seperators, c) &&
441                               cur.pos() != 0 &&
442                               cur.pos() != cur.lastpos() &&
443                               tm.getDisplayFont(pit, cur.pos()).fontInfo().number() == FONT_ON &&
444                               tm.getDisplayFont(pit, cur.pos() - 1).fontInfo().number() == FONT_ON)
445                            )
446                                 number(cur); // Set current_font.number to OFF
447                 } else if (isDigit(c) &&
448                            cur.real_current_font.isVisibleRightToLeft()) {
449                         number(cur); // Set current_font.number to ON
450
451                         if (cur.pos() != 0) {
452                                 char_type const c = par.getChar(cur.pos() - 1);
453                                 if (contains(number_unary_operators, c) &&
454                                     (cur.pos() == 1
455                                      || par.isSeparator(cur.pos() - 2)
456                                      || par.isNewline(cur.pos() - 2))
457                                   ) {
458                                         setCharFont(buffer, pit, cur.pos() - 1, cur.current_font,
459                                                 tm.font_);
460                                 } else if (contains(number_seperators, c)
461                                      && cur.pos() >= 2
462                                      && tm.getDisplayFont(pit, cur.pos() - 2).fontInfo().number() == FONT_ON) {
463                                         setCharFont(buffer, pit, cur.pos() - 1, cur.current_font,
464                                                 tm.font_);
465                                 }
466                         }
467                 }
468         }
469
470         // In Bidi text, we want spaces to be treated in a special way: spaces
471         // which are between words in different languages should get the 
472         // paragraph's language; otherwise, spaces should keep the language 
473         // they were originally typed in. This is only in effect while typing;
474         // after the text is already typed in, the user can always go back and
475         // explicitly set the language of a space as desired. But 99.9% of the
476         // time, what we're doing here is what the user actually meant.
477         // 
478         // The following cases are the ones in which the language of the space
479         // should be changed to match that of the containing paragraph. In the
480         // depictions, lowercase is LTR, uppercase is RTL, underscore (_) 
481         // represents a space, pipe (|) represents the cursor position (so the
482         // character before it is the one just typed in). The different cases
483         // are depicted logically (not visually), from left to right:
484         // 
485         // 1. A_a|
486         // 2. a_A|
487         //
488         // Theoretically, there are other situations that we should, perhaps, deal
489         // with (e.g.: a|_A, A|_a). In practice, though, there really isn't any 
490         // point (to understand why, just try to create this situation...).
491
492         if ((cur.pos() >= 2) && (par.isLineSeparator(cur.pos() - 1))) {
493                 // get font in front and behind the space in question. But do NOT 
494                 // use getFont(cur.pos()) because the character c is not inserted yet
495                 Font const pre_space_font  = tm.getDisplayFont(cur.pit(), cur.pos() - 2);
496                 Font const & post_space_font = cur.real_current_font;
497                 bool pre_space_rtl  = pre_space_font.isVisibleRightToLeft();
498                 bool post_space_rtl = post_space_font.isVisibleRightToLeft();
499                 
500                 if (pre_space_rtl != post_space_rtl) {
501                         // Set the space's language to match the language of the 
502                         // adjacent character whose direction is the paragraph's
503                         // direction; don't touch other properties of the font
504                         Language const * lang = 
505                                 (pre_space_rtl == par.isRTL(buffer.params())) ?
506                                 pre_space_font.language() : post_space_font.language();
507
508                         Font space_font = tm.getDisplayFont(cur.pit(), cur.pos() - 1);
509                         space_font.setLanguage(lang);
510                         par.setFont(cur.pos() - 1, space_font);
511                 }
512         }
513         
514         // Next check, if there will be two blanks together or a blank at
515         // the beginning of a paragraph.
516         // I decided to handle blanks like normal characters, the main
517         // difference are the special checks when calculating the row.fill
518         // (blank does not count at the end of a row) and the check here
519
520         // When the free-spacing option is set for the current layout,
521         // disable the double-space checking
522         if (!freeSpacing && isLineSeparatorChar(c)) {
523                 if (cur.pos() == 0) {
524                         static bool sent_space_message = false;
525                         if (!sent_space_message) {
526                                 cur.message(_("You cannot insert a space at the "
527                                                            "beginning of a paragraph. Please read the Tutorial."));
528                                 sent_space_message = true;
529                         }
530                         return;
531                 }
532                 BOOST_ASSERT(cur.pos() > 0);
533                 if ((par.isLineSeparator(cur.pos() - 1) || par.isNewline(cur.pos() - 1))
534                     && !par.isDeleted(cur.pos() - 1)) {
535                         static bool sent_space_message = false;
536                         if (!sent_space_message) {
537                                 cur.message(_("You cannot type two spaces this way. "
538                                                            "Please read the Tutorial."));
539                                 sent_space_message = true;
540                         }
541                         return;
542                 }
543         }
544
545         par.insertChar(cur.pos(), c, cur.current_font, cur.buffer().params().trackChanges);
546         cur.checkBufferStructure();
547
548 //              cur.updateFlags(Update::Force);
549         setCursor(cur.top(), cur.pit(), cur.pos() + 1);
550         charInserted(cur);
551 }
552
553
554 void Text::charInserted(Cursor & cur)
555 {
556         // Here we call finishUndo for every 20 characters inserted.
557         // This is from my experience how emacs does it. (Lgb)
558         static unsigned int counter;
559         if (counter < 20) {
560                 ++counter;
561         } else {
562                 cur.finishUndo();
563                 counter = 0;
564         }
565 }
566
567
568 // the cursor set functions have a special mechanism. When they
569 // realize, that you left an empty paragraph, they will delete it.
570
571 bool Text::cursorForwardOneWord(Cursor & cur)
572 {
573         BOOST_ASSERT(this == cur.text());
574
575         Cursor old = cur;
576
577         if (old.pos() == old.lastpos() && old.pit() != old.lastpit()) {
578                 ++old.pit();
579                 old.pos() = 0;
580         } else {
581                 // Advance through word.
582                 while (old.pos() != old.lastpos() && old.paragraph().isLetter(old.pos()))
583                         ++old.pos();
584                 // Skip through trailing nonword stuff.
585                 while (old.pos() != old.lastpos() && !old.paragraph().isLetter(old.pos()))
586                         ++old.pos();
587         }
588         return setCursor(cur, old.pit(), old.pos());
589 }
590
591
592 bool Text::cursorBackwardOneWord(Cursor & cur)
593 {
594         BOOST_ASSERT(this == cur.text());
595
596         Cursor old = cur;
597
598         if (old.pos() == 0 && old.pit() != 0) {
599                 --old.pit();
600                 old.pos() = old.lastpos();
601         } else {
602                 // Skip through initial nonword stuff.
603                 while (old.pos() != 0 && !old.paragraph().isLetter(old.pos() - 1))
604                         --old.pos();
605                 // Advance through word.
606                 while (old.pos() != 0 && old.paragraph().isLetter(old.pos() - 1))
607                         --old.pos();
608         }
609         return setCursor(cur, old.pit(), old.pos());
610 }
611
612
613 void Text::selectWord(Cursor & cur, word_location loc)
614 {
615         BOOST_ASSERT(this == cur.text());
616         CursorSlice from = cur.top();
617         CursorSlice to = cur.top();
618         getWord(from, to, loc);
619         if (cur.top() != from)
620                 setCursor(cur, from.pit(), from.pos());
621         if (to == from)
622                 return;
623         cur.resetAnchor();
624         setCursor(cur, to.pit(), to.pos());
625         cur.setSelection();
626 }
627
628
629 // Select the word currently under the cursor when no
630 // selection is currently set
631 bool Text::selectWordWhenUnderCursor(Cursor & cur, word_location loc)
632 {
633         BOOST_ASSERT(this == cur.text());
634         if (cur.selection())
635                 return false;
636         selectWord(cur, loc);
637         return cur.selection();
638 }
639
640
641 void Text::acceptOrRejectChanges(Cursor & cur, ChangeOp op)
642 {
643         BOOST_ASSERT(this == cur.text());
644
645         if (!cur.selection())
646                 return;
647
648         cur.recordUndoSelection();
649
650         pit_type begPit = cur.selectionBegin().pit();
651         pit_type endPit = cur.selectionEnd().pit();
652
653         pos_type begPos = cur.selectionBegin().pos();
654         pos_type endPos = cur.selectionEnd().pos();
655
656         // keep selection info, because endPos becomes invalid after the first loop
657         bool endsBeforeEndOfPar = (endPos < pars_[endPit].size());
658
659         // first, accept/reject changes within each individual paragraph (do not consider end-of-par)
660
661         for (pit_type pit = begPit; pit <= endPit; ++pit) {
662                 pos_type parSize = pars_[pit].size();
663
664                 // ignore empty paragraphs; otherwise, an assertion will fail for
665                 // acceptChanges(bparams, 0, 0) or rejectChanges(bparams, 0, 0)
666                 if (parSize == 0)
667                         continue;
668
669                 // do not consider first paragraph if the cursor starts at pos size()
670                 if (pit == begPit && begPos == parSize)
671                         continue;
672
673                 // do not consider last paragraph if the cursor ends at pos 0
674                 if (pit == endPit && endPos == 0)
675                         break; // last iteration anyway
676
677                 pos_type left  = (pit == begPit ? begPos : 0);
678                 pos_type right = (pit == endPit ? endPos : parSize);
679
680                 if (op == ACCEPT) {
681                         pars_[pit].acceptChanges(cur.buffer().params(), left, right);
682                 } else {
683                         pars_[pit].rejectChanges(cur.buffer().params(), left, right);
684                 }
685         }
686
687         // next, accept/reject imaginary end-of-par characters
688
689         for (pit_type pit = begPit; pit <= endPit; ++pit) {
690                 pos_type pos = pars_[pit].size();
691
692                 // skip if the selection ends before the end-of-par
693                 if (pit == endPit && endsBeforeEndOfPar)
694                         break; // last iteration anyway
695
696                 // skip if this is not the last paragraph of the document
697                 // note: the user should be able to accept/reject the par break of the last par!
698                 if (pit == endPit && pit + 1 != int(pars_.size()))
699                         break; // last iteration anway
700
701                 if (op == ACCEPT) {
702                         if (pars_[pit].isInserted(pos)) {
703                                 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
704                         } else if (pars_[pit].isDeleted(pos)) {
705                                 if (pit + 1 == int(pars_.size())) {
706                                         // we cannot remove a par break at the end of the last paragraph;
707                                         // instead, we mark it unchanged
708                                         pars_[pit].setChange(pos, Change(Change::UNCHANGED));
709                                 } else {
710                                         mergeParagraph(cur.buffer().params(), pars_, pit);
711                                         --endPit;
712                                         --pit;
713                                 }
714                         }
715                 } else {
716                         if (pars_[pit].isDeleted(pos)) {
717                                 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
718                         } else if (pars_[pit].isInserted(pos)) {
719                                 if (pit + 1 == int(pars_.size())) {
720                                         // we mark the par break at the end of the last paragraph unchanged
721                                         pars_[pit].setChange(pos, Change(Change::UNCHANGED));
722                                 } else {
723                                         mergeParagraph(cur.buffer().params(), pars_, pit);
724                                         --endPit;
725                                         --pit;
726                                 }
727                         }
728                 }
729         }
730
731         // finally, invoke the DEPM
732
733         deleteEmptyParagraphMechanism(begPit, endPit, cur.buffer().params().trackChanges);
734
735         //
736
737         cur.finishUndo();
738         cur.clearSelection();
739         setCursorIntern(cur, begPit, begPos);
740         cur.updateFlags(Update::Force);
741         updateLabels(cur.buffer());
742 }
743
744
745 void Text::acceptChanges(BufferParams const & bparams)
746 {
747         lyx::acceptChanges(pars_, bparams);
748         deleteEmptyParagraphMechanism(0, pars_.size() - 1, bparams.trackChanges);
749 }
750
751
752 void Text::rejectChanges(BufferParams const & bparams)
753 {
754         pit_type pars_size = static_cast<pit_type>(pars_.size());
755
756         // first, reject changes within each individual paragraph
757         // (do not consider end-of-par)
758         for (pit_type pit = 0; pit < pars_size; ++pit) {
759                 if (!pars_[pit].empty())   // prevent assertion failure
760                         pars_[pit].rejectChanges(bparams, 0, pars_[pit].size());
761         }
762
763         // next, reject imaginary end-of-par characters
764         for (pit_type pit = 0; pit < pars_size; ++pit) {
765                 pos_type pos = pars_[pit].size();
766
767                 if (pars_[pit].isDeleted(pos)) {
768                         pars_[pit].setChange(pos, Change(Change::UNCHANGED));
769                 } else if (pars_[pit].isInserted(pos)) {
770                         if (pit == pars_size - 1) {
771                                 // we mark the par break at the end of the last
772                                 // paragraph unchanged
773                                 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
774                         } else {
775                                 mergeParagraph(bparams, pars_, pit);
776                                 --pit;
777                                 --pars_size;
778                         }
779                 }
780         }
781
782         // finally, invoke the DEPM
783         deleteEmptyParagraphMechanism(0, pars_size - 1, bparams.trackChanges);
784 }
785
786
787 void Text::deleteWordForward(Cursor & cur)
788 {
789         BOOST_ASSERT(this == cur.text());
790         if (cur.lastpos() == 0)
791                 cursorForward(cur);
792         else {
793                 cur.resetAnchor();
794                 cur.selection() = true;
795                 cursorForwardOneWord(cur);
796                 cur.setSelection();
797                 cutSelection(cur, true, false);
798                 cur.checkBufferStructure();
799         }
800 }
801
802
803 void Text::deleteWordBackward(Cursor & cur)
804 {
805         BOOST_ASSERT(this == cur.text());
806         if (cur.lastpos() == 0)
807                 cursorBackward(cur);
808         else {
809                 cur.resetAnchor();
810                 cur.selection() = true;
811                 cursorBackwardOneWord(cur);
812                 cur.setSelection();
813                 cutSelection(cur, true, false);
814                 cur.checkBufferStructure();
815         }
816 }
817
818
819 // Kill to end of line.
820 void Text::changeCase(Cursor & cur, TextCase action)
821 {
822         BOOST_ASSERT(this == cur.text());
823         CursorSlice from;
824         CursorSlice to;
825
826         bool gotsel = false;
827         if (cur.selection()) {
828                 from = cur.selBegin();
829                 to = cur.selEnd();
830                 gotsel = true;
831         } else {
832                 from = cur.top();
833                 getWord(from, to, PARTIAL_WORD);
834                 cursorForwardOneWord(cur);
835         }
836
837         cur.recordUndoSelection();
838
839         pit_type begPit = from.pit();
840         pit_type endPit = to.pit();
841
842         pos_type begPos = from.pos();
843         pos_type endPos = to.pos();
844
845         pos_type right = 0; // needed after the for loop
846
847         for (pit_type pit = begPit; pit <= endPit; ++pit) {
848                 Paragraph & par = pars_[pit];
849                 pos_type const pos = (pit == begPit ? begPos : 0);
850                 right = (pit == endPit ? endPos : par.size());
851                 par.changeCase(cur.buffer().params(), pos, right, action);
852         }
853
854         // the selection may have changed due to logically-only deleted chars
855         if (gotsel) {
856                 setCursor(cur, begPit, begPos);
857                 cur.resetAnchor();
858                 setCursor(cur, endPit, right);
859                 cur.setSelection();
860         } else
861                 setCursor(cur, endPit, right);
862
863         cur.checkBufferStructure();
864 }
865
866
867 bool Text::handleBibitems(Cursor & cur)
868 {
869         if (cur.paragraph().layout()->labeltype != LABEL_BIBLIO)
870                 return false;
871         // if a bibitem is deleted, merge with previous paragraph
872         // if this is a bibliography item as well
873         if (cur.pos() == 0) {
874                 BufferParams const & bufparams = cur.buffer().params();
875                 Paragraph const & par = cur.paragraph();
876                 Cursor prevcur = cur;
877                 if (cur.pit() > 0) {
878                         --prevcur.pit();
879                         prevcur.pos() = prevcur.lastpos();
880                 }
881                 Paragraph const & prevpar = prevcur.paragraph();
882                 if (cur.pit() > 0 && par.layout() == prevpar.layout()) {
883                         cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
884                         mergeParagraph(bufparams, cur.text()->paragraphs(),
885                                        prevcur.pit());
886                         updateLabels(cur.buffer());
887                         setCursorIntern(cur, prevcur.pit(), prevcur.pos());
888                         cur.updateFlags(Update::Force);
889                 // if not, reset the paragraph to default
890                 } else
891                         cur.paragraph().layout(
892                                 bufparams.getTextClass().defaultLayout());
893                 return true;
894         }
895         return false;
896 }
897
898
899 bool Text::erase(Cursor & cur)
900 {
901         BOOST_ASSERT(this == cur.text());
902         bool needsUpdate = false;
903         Paragraph & par = cur.paragraph();
904
905         if (cur.pos() != cur.lastpos()) {
906                 // this is the code for a normal delete, not pasting
907                 // any paragraphs
908                 cur.recordUndo(DELETE_UNDO);
909                 if(!par.eraseChar(cur.pos(), cur.buffer().params().trackChanges)) {
910                         // the character has been logically deleted only => skip it
911                         cur.top().forwardPos();
912                 }
913                 cur.checkBufferStructure();
914                 needsUpdate = true;
915         } else {
916                 if (cur.pit() == cur.lastpit())
917                         return dissolveInset(cur);
918
919                 if (!par.isMergedOnEndOfParDeletion(cur.buffer().params().trackChanges)) {
920                         par.setChange(cur.pos(), Change(Change::DELETED));
921                         cur.forwardPos();
922                         needsUpdate = true;
923                 } else {
924                         setCursorIntern(cur, cur.pit() + 1, 0);
925                         needsUpdate = backspacePos0(cur);
926                 }
927         }
928
929         needsUpdate |= handleBibitems(cur);
930
931         if (needsUpdate) {
932                 // Make sure the cursor is correct. Is this really needed?
933                 // No, not really... at least not here!
934                 cur.text()->setCursor(cur.top(), cur.pit(), cur.pos());
935                 cur.checkBufferStructure();
936         }
937
938         return needsUpdate;
939 }
940
941
942 bool Text::backspacePos0(Cursor & cur)
943 {
944         BOOST_ASSERT(this == cur.text());
945         if (cur.pit() == 0)
946                 return false;
947
948         bool needsUpdate = false;
949
950         BufferParams const & bufparams = cur.buffer().params();
951         TextClass const & tclass = bufparams.getTextClass();
952         ParagraphList & plist = cur.text()->paragraphs();
953         Paragraph const & par = cur.paragraph();
954         Cursor prevcur = cur;
955         --prevcur.pit();
956         prevcur.pos() = prevcur.lastpos();
957         Paragraph const & prevpar = prevcur.paragraph();
958
959         // is it an empty paragraph?
960         if (cur.lastpos() == 0
961             || (cur.lastpos() == 1 && par.isSeparator(0))) {
962                 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
963                 plist.erase(boost::next(plist.begin(), cur.pit()));
964                 needsUpdate = true;
965         }
966         // is previous par empty?
967         else if (prevcur.lastpos() == 0
968                  || (prevcur.lastpos() == 1 && prevpar.isSeparator(0))) {
969                 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
970                 plist.erase(boost::next(plist.begin(), prevcur.pit()));
971                 needsUpdate = true;
972         }
973         // Pasting is not allowed, if the paragraphs have different
974         // layouts. I think it is a real bug of all other
975         // word processors to allow it. It confuses the user.
976         // Correction: Pasting is always allowed with standard-layout
977         else if (par.layout() == prevpar.layout()
978                  || par.layout() == tclass.defaultLayout()) {
979                 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
980                 mergeParagraph(bufparams, plist, prevcur.pit());
981                 needsUpdate = true;
982         }
983
984         if (needsUpdate) {
985                 updateLabels(cur.buffer());
986                 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
987         }
988
989         return needsUpdate;
990 }
991
992
993 bool Text::backspace(Cursor & cur)
994 {
995         BOOST_ASSERT(this == cur.text());
996         bool needsUpdate = false;
997         if (cur.pos() == 0) {
998                 if (cur.pit() == 0)
999                         return dissolveInset(cur);
1000
1001                 Paragraph & prev_par = pars_[cur.pit() - 1];
1002
1003                 if (!prev_par.isMergedOnEndOfParDeletion(cur.buffer().params().trackChanges)) {
1004                         prev_par.setChange(prev_par.size(), Change(Change::DELETED));
1005                         setCursorIntern(cur, cur.pit() - 1, prev_par.size());
1006                         return true;
1007                 }
1008                 // The cursor is at the beginning of a paragraph, so
1009                 // the backspace will collapse two paragraphs into one.
1010                 needsUpdate = backspacePos0(cur);
1011
1012         } else {
1013                 // this is the code for a normal backspace, not pasting
1014                 // any paragraphs
1015                 cur.recordUndo(DELETE_UNDO);
1016                 // We used to do cursorBackwardIntern() here, but it is
1017                 // not a good idea since it triggers the auto-delete
1018                 // mechanism. So we do a cursorBackwardIntern()-lite,
1019                 // without the dreaded mechanism. (JMarc)
1020                 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1021                                 false, cur.boundary());
1022                 cur.paragraph().eraseChar(cur.pos(), cur.buffer().params().trackChanges);
1023                 cur.checkBufferStructure();
1024         }
1025
1026         if (cur.pos() == cur.lastpos())
1027                 cur.setCurrentFont();
1028
1029         needsUpdate |= handleBibitems(cur);
1030
1031         // A singlePar update is not enough in this case.
1032 //              cur.updateFlags(Update::Force);
1033         setCursor(cur.top(), cur.pit(), cur.pos());
1034
1035         return needsUpdate;
1036 }
1037
1038
1039 bool Text::dissolveInset(Cursor & cur) {
1040         BOOST_ASSERT(this == cur.text());
1041
1042         if (isMainText(cur.bv().buffer()) || cur.inset().nargs() != 1)
1043                 return false;
1044
1045         cur.recordUndoInset();
1046         cur.mark() = false;
1047         cur.selHandle(false);
1048         // save position
1049         pos_type spos = cur.pos();
1050         pit_type spit = cur.pit();
1051         ParagraphList plist;
1052         if (cur.lastpit() != 0 || cur.lastpos() != 0)
1053                 plist = paragraphs();
1054         cur.popBackward();
1055         // store cursor offset
1056         if (spit == 0)
1057                 spos += cur.pos();
1058         spit += cur.pit();
1059         Buffer & b = cur.buffer();
1060         cur.paragraph().eraseChar(cur.pos(), b.params().trackChanges);
1061         if (!plist.empty()) {
1062                 // ERT paragraphs have the Language latex_language.
1063                 // This is invalid outside of ERT, so we need to
1064                 // change it to the buffer language.
1065                 ParagraphList::iterator it = plist.begin();
1066                 ParagraphList::iterator it_end = plist.end();
1067                 for (; it != it_end; it++)
1068                         it->changeLanguage(b.params(), latex_language, b.language());
1069
1070                 pasteParagraphList(cur, plist, b.params().getTextClassPtr(),
1071                                    b.errorList("Paste"));
1072                 // restore position
1073                 cur.pit() = min(cur.lastpit(), spit);
1074                 cur.pos() = min(cur.lastpos(), spos);
1075         }
1076         cur.clearSelection();
1077         cur.resetAnchor();
1078         return true;
1079 }
1080
1081
1082 void Text::getWord(CursorSlice & from, CursorSlice & to,
1083         word_location const loc)
1084 {
1085         Paragraph const & from_par = pars_[from.pit()];
1086         switch (loc) {
1087         case WHOLE_WORD_STRICT:
1088                 if (from.pos() == 0 || from.pos() == from_par.size()
1089                     || !from_par.isLetter(from.pos())
1090                     || !from_par.isLetter(from.pos() - 1)) {
1091                         to = from;
1092                         return;
1093                 }
1094                 // no break here, we go to the next
1095
1096         case WHOLE_WORD:
1097                 // If we are already at the beginning of a word, do nothing
1098                 if (!from.pos() || !from_par.isLetter(from.pos() - 1))
1099                         break;
1100                 // no break here, we go to the next
1101
1102         case PREVIOUS_WORD:
1103                 // always move the cursor to the beginning of previous word
1104                 while (from.pos() && from_par.isLetter(from.pos() - 1))
1105                         --from.pos();
1106                 break;
1107         case NEXT_WORD:
1108                 LYXERR0("Text::getWord: NEXT_WORD not implemented yet");
1109                 break;
1110         case PARTIAL_WORD:
1111                 // no need to move the 'from' cursor
1112                 break;
1113         }
1114         to = from;
1115         Paragraph & to_par = pars_[to.pit()];
1116         while (to.pos() < to_par.size() && to_par.isLetter(to.pos()))
1117                 ++to.pos();
1118 }
1119
1120
1121 void Text::write(Buffer const & buf, ostream & os) const
1122 {
1123         ParagraphList::const_iterator pit = paragraphs().begin();
1124         ParagraphList::const_iterator end = paragraphs().end();
1125         depth_type dth = 0;
1126         for (; pit != end; ++pit)
1127                 pit->write(buf, os, buf.params(), dth);
1128
1129         // Close begin_deeper
1130         for(; dth > 0; --dth)
1131                 os << "\n\\end_deeper";
1132 }
1133
1134
1135 bool Text::read(Buffer const & buf, Lexer & lex, ErrorList & errorList)
1136 {
1137         depth_type depth = 0;
1138
1139         while (lex.isOK()) {
1140                 lex.nextToken();
1141                 string const token = lex.getString();
1142
1143                 if (token.empty())
1144                         continue;
1145
1146                 if (token == "\\end_inset")
1147                         break;
1148
1149                 if (token == "\\end_body")
1150                         continue;
1151
1152                 if (token == "\\begin_body")
1153                         continue;
1154
1155                 if (token == "\\end_document")
1156                         return false;
1157
1158                 if (token == "\\begin_layout") {
1159                         lex.pushToken(token);
1160
1161                         Paragraph par;
1162                         par.params().depth(depth);
1163                         par.setFont(0, Font(inherit_font, buf.params().language));
1164                         pars_.push_back(par);
1165
1166                         // FIXME: goddamn InsetTabular makes us pass a Buffer
1167                         // not BufferParams
1168                         lyx::readParagraph(buf, pars_.back(), lex, errorList);
1169
1170                 } else if (token == "\\begin_deeper") {
1171                         ++depth;
1172                 } else if (token == "\\end_deeper") {
1173                         if (!depth)
1174                                 lex.printError("\\end_deeper: " "depth is already null");
1175                         else
1176                                 --depth;
1177                 } else {
1178                         LYXERR0("Handling unknown body token: `" << token << '\'');
1179                 }
1180         }
1181         return true;
1182 }
1183
1184 // Returns the current font and depth as a message.
1185 docstring Text::currentState(Cursor & cur)
1186 {
1187         BOOST_ASSERT(this == cur.text());
1188         Buffer & buf = cur.buffer();
1189         Paragraph const & par = cur.paragraph();
1190         odocstringstream os;
1191
1192         if (buf.params().trackChanges)
1193                 os << _("[Change Tracking] ");
1194
1195         Change change = par.lookupChange(cur.pos());
1196
1197         if (change.type != Change::UNCHANGED) {
1198                 Author const & a = buf.params().authors().get(change.author);
1199                 os << _("Change: ") << a.name();
1200                 if (!a.email().empty())
1201                         os << " (" << a.email() << ")";
1202                 // FIXME ctime is english, we should translate that
1203                 os << _(" at ") << ctime(&change.changetime);
1204                 os << " : ";
1205         }
1206
1207         // I think we should only show changes from the default
1208         // font. (Asger)
1209         // No, from the document font (MV)
1210         Font font = cur.real_current_font;
1211         font.fontInfo().reduce(buf.params().getFont().fontInfo());
1212
1213         os << bformat(_("Font: %1$s"), font.stateText(&buf.params()));
1214
1215         // The paragraph depth
1216         int depth = cur.paragraph().getDepth();
1217         if (depth > 0)
1218                 os << bformat(_(", Depth: %1$d"), depth);
1219
1220         // The paragraph spacing, but only if different from
1221         // buffer spacing.
1222         Spacing const & spacing = par.params().spacing();
1223         if (!spacing.isDefault()) {
1224                 os << _(", Spacing: ");
1225                 switch (spacing.getSpace()) {
1226                 case Spacing::Single:
1227                         os << _("Single");
1228                         break;
1229                 case Spacing::Onehalf:
1230                         os << _("OneHalf");
1231                         break;
1232                 case Spacing::Double:
1233                         os << _("Double");
1234                         break;
1235                 case Spacing::Other:
1236                         os << _("Other (") << from_ascii(spacing.getValueAsString()) << ')';
1237                         break;
1238                 case Spacing::Default:
1239                         // should never happen, do nothing
1240                         break;
1241                 }
1242         }
1243
1244 #ifdef DEVEL_VERSION
1245         os << _(", Inset: ") << &cur.inset();
1246         os << _(", Paragraph: ") << cur.pit();
1247         os << _(", Id: ") << par.id();
1248         os << _(", Position: ") << cur.pos();
1249         // FIXME: Why is the check for par.size() needed?
1250         // We are called with cur.pos() == par.size() quite often.
1251         if (!par.empty() && cur.pos() < par.size()) {
1252                 // Force output of code point, not character
1253                 size_t const c = par.getChar(cur.pos());
1254                 os << _(", Char: 0x") << hex << c;
1255         }
1256         os << _(", Boundary: ") << cur.boundary();
1257 //      Row & row = cur.textRow();
1258 //      os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
1259 #endif
1260         return os.str();
1261 }
1262
1263
1264 docstring Text::getPossibleLabel(Cursor & cur) const
1265 {
1266         pit_type pit = cur.pit();
1267
1268         LayoutPtr layout = pars_[pit].layout();
1269
1270         docstring text;
1271         docstring par_text = pars_[pit].asString(cur.buffer(), false);
1272         string piece;
1273         // the return string of math matrices might contain linebreaks
1274         par_text = subst(par_text, '\n', '-');
1275         for (int i = 0; i < lyxrc.label_init_length; ++i) {
1276                 if (par_text.empty())
1277                         break;
1278                 docstring head;
1279                 par_text = split(par_text, head, ' ');
1280                 // Is it legal to use spaces in labels ?
1281                 if (i > 0)
1282                         text += '-';
1283                 text += head;
1284         }
1285
1286         // No need for a prefix if the user said so.
1287         if (lyxrc.label_init_length <= 0)
1288                 return text;
1289
1290         // Will contain the label type.
1291         docstring name;
1292
1293         // For section, subsection, etc...
1294         if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
1295                 LayoutPtr const & layout2 = pars_[pit - 1].layout();
1296                 if (layout2->latextype != LATEX_PARAGRAPH) {
1297                         --pit;
1298                         layout = layout2;
1299                 }
1300         }
1301         if (layout->latextype != LATEX_PARAGRAPH)
1302                 name = from_ascii(layout->latexname());
1303
1304         // for captions, we just take the caption type
1305         Inset * caption_inset = cur.innerInsetOfType(CAPTION_CODE);
1306         if (caption_inset)
1307                 name = from_ascii(static_cast<InsetCaption *>(caption_inset)->type());
1308
1309         // If none of the above worked, we'll see if we're inside various
1310         // types of insets and take our abbreviation from them.
1311         if (name.empty()) {
1312                 InsetCode const codes[] = {
1313                         FLOAT_CODE,
1314                         WRAP_CODE,
1315                         FOOT_CODE
1316                 };
1317                 for (unsigned int i = 0; i < (sizeof codes / sizeof codes[0]); ++i) {
1318                         Inset * float_inset = cur.innerInsetOfType(codes[i]);
1319                         if (float_inset) {
1320                                 name = float_inset->name();
1321                                 break;
1322                         }
1323                 }
1324         }
1325
1326         // Create a correct prefix for prettyref
1327         if (name == "theorem")
1328                 name = from_ascii("thm");
1329         else if (name == "Foot")
1330                 name = from_ascii("fn");
1331         else if (name == "listing")
1332                 name = from_ascii("lst");
1333
1334         if (!name.empty())
1335                 text = name.substr(0, 3) + ':' + text;
1336
1337         return text;
1338 }
1339
1340
1341 void Text::charsTranspose(Cursor & cur)
1342 {
1343         BOOST_ASSERT(this == cur.text());
1344
1345         pos_type pos = cur.pos();
1346
1347         // If cursor is at beginning or end of paragraph, do nothing.
1348         if (pos == cur.lastpos() || pos == 0)
1349                 return;
1350
1351         Paragraph & par = cur.paragraph();
1352
1353         // Get the positions of the characters to be transposed.
1354         pos_type pos1 = pos - 1;
1355         pos_type pos2 = pos;
1356
1357         // In change tracking mode, ignore deleted characters.
1358         while (pos2 < cur.lastpos() && par.isDeleted(pos2))
1359                 ++pos2;
1360         if (pos2 == cur.lastpos())
1361                 return;
1362
1363         while (pos1 >= 0 && par.isDeleted(pos1))
1364                 --pos1;
1365         if (pos1 < 0)
1366                 return;
1367
1368         // Don't do anything if one of the "characters" is not regular text.
1369         if (par.isInset(pos1) || par.isInset(pos2))
1370                 return;
1371
1372         // Store the characters to be transposed (including font information).
1373         char_type char1 = par.getChar(pos1);
1374         Font const font1 =
1375                 par.getFontSettings(cur.buffer().params(), pos1);
1376
1377         char_type char2 = par.getChar(pos2);
1378         Font const font2 =
1379                 par.getFontSettings(cur.buffer().params(), pos2);
1380
1381         // And finally, we are ready to perform the transposition.
1382         // Track the changes if Change Tracking is enabled.
1383         bool const trackChanges = cur.buffer().params().trackChanges;
1384
1385         cur.recordUndo();
1386
1387         par.eraseChar(pos2, trackChanges);
1388         par.eraseChar(pos1, trackChanges);
1389         par.insertChar(pos1, char2, font2, trackChanges);
1390         par.insertChar(pos2, char1, font1, trackChanges);
1391
1392         cur.checkBufferStructure();
1393
1394         // After the transposition, move cursor to after the transposition.
1395         setCursor(cur, cur.pit(), pos2);
1396         cur.forwardPos();
1397 }
1398
1399
1400 DocIterator Text::macrocontextPosition() const
1401 {
1402         return macrocontext_position_;
1403 }
1404
1405
1406 void Text::setMacrocontextPosition(DocIterator const & pos)
1407 {
1408         macrocontext_position_ = pos;
1409 }
1410
1411
1412 } // namespace lyx