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