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