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