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