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