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