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