]> git.lyx.org Git - lyx.git/blob - src/Text.cpp
99e87889e1d983d2e7462c2e4a206afab1e6e19c
[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 "bufferview_funcs.h"
29 #include "Cursor.h"
30 #include "ParIterator.h"
31 #include "CoordCache.h"
32 #include "CutAndPaste.h"
33 #include "debug.h"
34 #include "DispatchResult.h"
35 #include "Encoding.h"
36 #include "ErrorList.h"
37 #include "FuncRequest.h"
38 #include "factory.h"
39 #include "FontIterator.h"
40 #include "gettext.h"
41 #include "Language.h"
42 #include "Color.h"
43 #include "Length.h"
44 #include "Lexer.h"
45 #include "LyXRC.h"
46 #include "Row.h"
47 #include "MetricsInfo.h"
48 #include "Paragraph.h"
49 #include "paragraph_funcs.h"
50 #include "ParagraphParameters.h"
51 #include "Undo.h"
52 #include "VSpace.h"
53 #include "WordLangTuple.h"
54
55 #include "frontends/FontMetrics.h"
56 #include "frontends/Painter.h"
57
58 #include "insets/InsetText.h"
59 #include "insets/InsetBibitem.h"
60 #include "insets/InsetCaption.h"
61 #include "insets/InsetHFill.h"
62 #include "insets/InsetLine.h"
63 #include "insets/InsetNewline.h"
64 #include "insets/InsetPagebreak.h"
65 #include "insets/InsetOptArg.h"
66 #include "insets/InsetSpace.h"
67 #include "insets/InsetSpecialChar.h"
68 #include "insets/InsetTabular.h"
69
70 #include "support/lstrings.h"
71 #include "support/textutils.h"
72 #include "support/convert.h"
73
74 #include <boost/current_function.hpp>
75
76 #include <sstream>
77
78 using std::auto_ptr;
79 using std::advance;
80 using std::distance;
81 using std::max;
82 using std::min;
83 using std::endl;
84 using std::string;
85
86 namespace lyx {
87
88 using support::bformat;
89 using support::contains;
90 using support::lowercase;
91 using support::split;
92 using support::uppercase;
93
94 using cap::cutSelection;
95 using cap::pasteParagraphList;
96
97 using frontend::FontMetrics;
98
99 namespace {
100
101 void readParToken(Buffer const & buf, Paragraph & par, Lexer & lex,
102         string const & token, Font & font, Change & change, ErrorList & errorList)
103 {
104         BufferParams const & bp = buf.params();
105
106         if (token[0] != '\\') {
107 #if 0
108                 string::const_iterator cit = token.begin();
109                 for (; cit != token.end(); ++cit)
110                         par.insertChar(par.size(), (*cit), font, change);
111 #else
112                 docstring dstr = lex.getDocString();
113                 docstring::const_iterator cit = dstr.begin();
114                 docstring::const_iterator cend = dstr.end();
115                 for (; cit != cend; ++cit)
116                         par.insertChar(par.size(), *cit, font, change);
117 #endif
118         } else if (token == "\\begin_layout") {
119                 lex.eatLine();
120                 docstring layoutname = lex.getDocString();
121
122                 font = Font(Font::ALL_INHERIT, bp.language);
123                 change = Change(Change::UNCHANGED);
124
125                 TextClass const & tclass = bp.getTextClass();
126
127                 if (layoutname.empty()) {
128                         layoutname = tclass.defaultLayoutName();
129                 }
130
131                 bool hasLayout = tclass.hasLayout(layoutname);
132
133                 if (!hasLayout) {
134                         errorList.push_back(ErrorItem(_("Unknown layout"),
135                         bformat(_("Layout '%1$s' does not exist in textclass '%2$s'\nTrying to use the default instead.\n"),
136                         layoutname, from_utf8(tclass.name())), par.id(), 0, par.size()));
137                         layoutname = tclass.defaultLayoutName();
138                 }
139
140                 par.layout(bp.getTextClass()[layoutname]);
141
142                 // Test whether the layout is obsolete.
143                 LayoutPtr const & layout = par.layout();
144                 if (!layout->obsoleted_by().empty())
145                         par.layout(bp.getTextClass()[layout->obsoleted_by()]);
146
147                 par.params().read(lex);
148
149         } else if (token == "\\end_layout") {
150                 lyxerr << BOOST_CURRENT_FUNCTION
151                        << ": Solitary \\end_layout in line "
152                        << lex.getLineNo() << "\n"
153                        << "Missing \\begin_layout?.\n";
154         } else if (token == "\\end_inset") {
155                 lyxerr << BOOST_CURRENT_FUNCTION
156                        << ": Solitary \\end_inset in line "
157                        << lex.getLineNo() << "\n"
158                        << "Missing \\begin_inset?.\n";
159         } else if (token == "\\begin_inset") {
160                 Inset * inset = readInset(lex, buf);
161                 if (inset)
162                         par.insertInset(par.size(), inset, font, change);
163                 else {
164                         lex.eatLine();
165                         docstring line = lex.getDocString();
166                         errorList.push_back(ErrorItem(_("Unknown Inset"), line,
167                                             par.id(), 0, par.size()));
168                 }
169         } else if (token == "\\family") {
170                 lex.next();
171                 font.setLyXFamily(lex.getString());
172         } else if (token == "\\series") {
173                 lex.next();
174                 font.setLyXSeries(lex.getString());
175         } else if (token == "\\shape") {
176                 lex.next();
177                 font.setLyXShape(lex.getString());
178         } else if (token == "\\size") {
179                 lex.next();
180                 font.setLyXSize(lex.getString());
181         } else if (token == "\\lang") {
182                 lex.next();
183                 string const tok = lex.getString();
184                 Language const * lang = languages.getLanguage(tok);
185                 if (lang) {
186                         font.setLanguage(lang);
187                 } else {
188                         font.setLanguage(bp.language);
189                         lex.printError("Unknown language `$$Token'");
190                 }
191         } else if (token == "\\numeric") {
192                 lex.next();
193                 font.setNumber(font.setLyXMisc(lex.getString()));
194         } else if (token == "\\emph") {
195                 lex.next();
196                 font.setEmph(font.setLyXMisc(lex.getString()));
197         } else if (token == "\\bar") {
198                 lex.next();
199                 string const tok = lex.getString();
200
201                 if (tok == "under")
202                         font.setUnderbar(Font::ON);
203                 else if (tok == "no")
204                         font.setUnderbar(Font::OFF);
205                 else if (tok == "default")
206                         font.setUnderbar(Font::INHERIT);
207                 else
208                         lex.printError("Unknown bar font flag "
209                                        "`$$Token'");
210         } else if (token == "\\noun") {
211                 lex.next();
212                 font.setNoun(font.setLyXMisc(lex.getString()));
213         } else if (token == "\\color") {
214                 lex.next();
215                 font.setLyXColor(lex.getString());
216         } else if (token == "\\InsetSpace" || token == "\\SpecialChar") {
217
218                 // Insets don't make sense in a free-spacing context! ---Kayvan
219                 if (par.isFreeSpacing()) {
220                         if (token == "\\InsetSpace")
221                                 par.insertChar(par.size(), ' ', font, change);
222                         else if (lex.isOK()) {
223                                 lex.next();
224                                 string const next_token = lex.getString();
225                                 if (next_token == "\\-")
226                                         par.insertChar(par.size(), '-', font, change);
227                                 else {
228                                         lex.printError("Token `$$Token' "
229                                                        "is in free space "
230                                                        "paragraph layout!");
231                                 }
232                         }
233                 } else {
234                         auto_ptr<Inset> inset;
235                         if (token == "\\SpecialChar" )
236                                 inset.reset(new InsetSpecialChar);
237                         else
238                                 inset.reset(new InsetSpace);
239                         inset->read(buf, lex);
240                         par.insertInset(par.size(), inset.release(),
241                                         font, change);
242                 }
243         } else if (token == "\\backslash") {
244                 par.insertChar(par.size(), '\\', font, change);
245         } else if (token == "\\newline") {
246                 auto_ptr<Inset> inset(new InsetNewline);
247                 inset->read(buf, lex);
248                 par.insertInset(par.size(), inset.release(), font, change);
249         } else if (token == "\\LyXTable") {
250                 auto_ptr<Inset> inset(new InsetTabular(buf));
251                 inset->read(buf, lex);
252                 par.insertInset(par.size(), inset.release(), font, change);
253         } else if (token == "\\hfill") {
254                 par.insertInset(par.size(), new InsetHFill, font, change);
255         } else if (token == "\\lyxline") {
256                 par.insertInset(par.size(), new InsetLine, font, change);
257         } else if (token == "\\newpage") {
258                 par.insertInset(par.size(), new InsetPagebreak, font, change);
259         } else if (token == "\\clearpage") {
260                 par.insertInset(par.size(), new InsetClearPage, font, change);
261         } else if (token == "\\cleardoublepage") {
262                 par.insertInset(par.size(), new InsetClearDoublePage, font, change);
263         } else if (token == "\\change_unchanged") {
264                 change = Change(Change::UNCHANGED);
265         } else if (token == "\\change_inserted") {
266                 lex.eatLine();
267                 std::istringstream is(lex.getString());
268                 unsigned int aid;
269                 time_type ct;
270                 is >> aid >> ct;
271                 if (aid >= bp.author_map.size()) {
272                         errorList.push_back(ErrorItem(_("Change tracking error"),
273                                             bformat(_("Unknown author index for insertion: %1$d\n"), aid),
274                                             par.id(), 0, par.size()));
275                         change = Change(Change::UNCHANGED);
276                 } else
277                         change = Change(Change::INSERTED, bp.author_map[aid], ct);
278         } else if (token == "\\change_deleted") {
279                 lex.eatLine();
280                 std::istringstream is(lex.getString());
281                 unsigned int aid;
282                 time_type ct;
283                 is >> aid >> ct;
284                 if (aid >= bp.author_map.size()) {
285                         errorList.push_back(ErrorItem(_("Change tracking error"),
286                                             bformat(_("Unknown author index for deletion: %1$d\n"), aid),
287                                             par.id(), 0, par.size()));
288                         change = Change(Change::UNCHANGED);
289                 } else
290                         change = Change(Change::DELETED, bp.author_map[aid], ct);
291         } else {
292                 lex.eatLine();
293                 errorList.push_back(ErrorItem(_("Unknown token"),
294                         bformat(_("Unknown token: %1$s %2$s\n"), from_utf8(token),
295                         lex.getDocString()),
296                         par.id(), 0, par.size()));
297         }
298 }
299
300
301 void readParagraph(Buffer const & buf, Paragraph & par, Lexer & lex,
302         ErrorList & errorList)
303 {
304         lex.nextToken();
305         string token = lex.getString();
306         Font font;
307         Change change(Change::UNCHANGED);
308
309         while (lex.isOK()) {
310                 readParToken(buf, par, lex, token, font, change, errorList);
311
312                 lex.nextToken();
313                 token = lex.getString();
314
315                 if (token.empty())
316                         continue;
317
318                 if (token == "\\end_layout") {
319                         //Ok, paragraph finished
320                         break;
321                 }
322
323                 LYXERR(Debug::PARSER) << "Handling paragraph token: `"
324                                       << token << '\'' << endl;
325                 if (token == "\\begin_layout" || token == "\\end_document"
326                     || token == "\\end_inset" || token == "\\begin_deeper"
327                     || token == "\\end_deeper") {
328                         lex.pushToken(token);
329                         lyxerr << "Paragraph ended in line "
330                                << lex.getLineNo() << "\n"
331                                << "Missing \\end_layout.\n";
332                         break;
333                 }
334         }
335         // Final change goes to paragraph break:
336         par.setChange(par.size(), change);
337
338         // Initialize begin_of_body_ on load; redoParagraph maintains
339         par.setBeginOfBody();
340 }
341
342
343 } // namespace anon
344
345
346 bool Text::empty() const
347 {
348         return pars_.empty() || (pars_.size() == 1 && pars_[0].empty()
349                 // FIXME: Should we consider the labeled type as empty too? 
350                 && pars_[0].layout()->labeltype == LABEL_NO_LABEL);
351 }
352
353
354 double Text::spacing(Buffer const & buffer,
355                 Paragraph const & par) const
356 {
357         if (par.params().spacing().isDefault())
358                 return buffer.params().spacing().getValue();
359         return par.params().spacing().getValue();
360 }
361
362
363 int Text::leftMargin(Buffer const & buffer, int max_width, pit_type pit) const
364 {
365         BOOST_ASSERT(pit >= 0);
366         BOOST_ASSERT(pit < int(pars_.size()));
367         return leftMargin(buffer, max_width, pit, pars_[pit].size());
368 }
369
370
371 int Text::leftMargin(Buffer const & buffer, int max_width,
372                 pit_type const pit, pos_type const pos) const
373 {
374         BOOST_ASSERT(pit >= 0);
375         BOOST_ASSERT(pit < int(pars_.size()));
376         Paragraph const & par = pars_[pit];
377         BOOST_ASSERT(pos >= 0);
378         BOOST_ASSERT(pos <= par.size());
379         //lyxerr << "Text::leftMargin: pit: " << pit << " pos: " << pos << endl;
380         TextClass const & tclass = buffer.params().getTextClass();
381         LayoutPtr const & layout = par.layout();
382
383         docstring parindent = layout->parindent;
384
385         int l_margin = 0;
386
387         if (isMainText(buffer))
388                 l_margin += changebarMargin();
389
390         l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
391                 tclass.leftmargin());
392
393         if (par.getDepth() != 0) {
394                 // find the next level paragraph
395                 pit_type newpar = outerHook(pit, pars_);
396                 if (newpar != pit_type(pars_.size())) {
397                         if (pars_[newpar].layout()->isEnvironment()) {
398                                 l_margin = leftMargin(buffer, max_width, newpar);
399                         }
400                         if (par.layout() == tclass.defaultLayout()) {
401                                 if (pars_[newpar].params().noindent())
402                                         parindent.erase();
403                                 else
404                                         parindent = pars_[newpar].layout()->parindent;
405                         }
406                 }
407         }
408
409         // This happens after sections in standard classes. The 1.3.x
410         // code compared depths too, but it does not seem necessary
411         // (JMarc)
412         if (par.layout() == tclass.defaultLayout()
413             && pit > 0 && pars_[pit - 1].layout()->nextnoindent)
414                 parindent.erase();
415
416         Font const labelfont = getLabelFont(buffer, par);
417         FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
418
419         switch (layout->margintype) {
420         case MARGIN_DYNAMIC:
421                 if (!layout->leftmargin.empty()) {
422                         l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
423                                 layout->leftmargin);
424                 }
425                 if (!par.getLabelstring().empty()) {
426                         l_margin += labelfont_metrics.signedWidth(layout->labelindent);
427                         l_margin += labelfont_metrics.width(par.getLabelstring());
428                         l_margin += labelfont_metrics.width(layout->labelsep);
429                 }
430                 break;
431
432         case MARGIN_MANUAL: {
433                 l_margin += labelfont_metrics.signedWidth(layout->labelindent);
434                 // The width of an empty par, even with manual label, should be 0
435                 if (!par.empty() && pos >= par.beginOfBody()) {
436                         if (!par.getLabelWidthString().empty()) {
437                                 docstring labstr = par.getLabelWidthString();
438                                 l_margin += labelfont_metrics.width(labstr);
439                                 l_margin += labelfont_metrics.width(layout->labelsep);
440                         }
441                 }
442                 break;
443         }
444
445         case MARGIN_STATIC: {
446                 l_margin += theFontMetrics(buffer.params().getFont()).
447                         signedWidth(layout->leftmargin) * 4     / (par.getDepth() + 4);
448                 break;
449         }
450
451         case MARGIN_FIRST_DYNAMIC:
452                 if (layout->labeltype == LABEL_MANUAL) {
453                         if (pos >= par.beginOfBody()) {
454                                 l_margin += labelfont_metrics.signedWidth(layout->leftmargin);
455                         } else {
456                                 l_margin += labelfont_metrics.signedWidth(layout->labelindent);
457                         }
458                 } else if (pos != 0
459                            // Special case to fix problems with
460                            // theorems (JMarc)
461                            || (layout->labeltype == LABEL_STATIC
462                                && layout->latextype == LATEX_ENVIRONMENT
463                                && !isFirstInSequence(pit, pars_))) {
464                         l_margin += labelfont_metrics.signedWidth(layout->leftmargin);
465                 } else if (layout->labeltype != LABEL_TOP_ENVIRONMENT
466                            && layout->labeltype != LABEL_BIBLIO
467                            && layout->labeltype !=
468                            LABEL_CENTERED_TOP_ENVIRONMENT) {
469                         l_margin += labelfont_metrics.signedWidth(layout->labelindent);
470                         l_margin += labelfont_metrics.width(layout->labelsep);
471                         l_margin += labelfont_metrics.width(par.getLabelstring());
472                 }
473                 break;
474
475         case MARGIN_RIGHT_ADDRESS_BOX: {
476 #if 0
477                 // ok, a terrible hack. The left margin depends on the widest
478                 // row in this paragraph.
479                 RowList::iterator rit = par.rows().begin();
480                 RowList::iterator end = par.rows().end();
481                 // FIXME: This is wrong.
482                 int minfill = max_width;
483                 for ( ; rit != end; ++rit)
484                         if (rit->fill() < minfill)
485                                 minfill = rit->fill();
486                 l_margin += theFontMetrics(params.getFont()).signedWidth(layout->leftmargin);
487                 l_margin += minfill;
488 #endif
489                 // also wrong, but much shorter.
490                 l_margin += max_width / 2;
491                 break;
492         }
493         }
494
495         if (!par.params().leftIndent().zero())
496                 l_margin += par.params().leftIndent().inPixels(max_width);
497
498         LyXAlignment align;
499
500         if (par.params().align() == LYX_ALIGN_LAYOUT)
501                 align = layout->align;
502         else
503                 align = par.params().align();
504
505         // set the correct parindent
506         if (pos == 0
507             && (layout->labeltype == LABEL_NO_LABEL
508                || layout->labeltype == LABEL_TOP_ENVIRONMENT
509                || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
510                || (layout->labeltype == LABEL_STATIC
511                    && layout->latextype == LATEX_ENVIRONMENT
512                    && !isFirstInSequence(pit, pars_)))
513             && align == LYX_ALIGN_BLOCK
514             && !par.params().noindent()
515             // in some insets, paragraphs are never indented
516             && !(par.inInset() && par.inInset()->neverIndent(buffer))
517             // display style insets are always centered, omit indentation
518             && !(!par.empty()
519                     && par.isInset(pos)
520                     && par.getInset(pos)->display())
521             && (par.layout() != tclass.defaultLayout()
522                 || buffer.params().paragraph_separation ==
523                    BufferParams::PARSEP_INDENT))
524         {
525                 l_margin += theFontMetrics(buffer.params().getFont()).signedWidth(
526                         parindent);
527         }
528
529         return l_margin;
530 }
531
532
533 Color_color Text::backgroundColor() const
534 {
535         return Color_color(Color::color(background_color_));
536 }
537
538
539 void Text::breakParagraph(Cursor & cur, bool keep_layout)
540 {
541         BOOST_ASSERT(this == cur.text());
542
543         Paragraph & cpar = cur.paragraph();
544         pit_type cpit = cur.pit();
545
546         TextClass const & tclass = cur.buffer().params().getTextClass();
547         LayoutPtr const & layout = cpar.layout();
548
549         // this is only allowed, if the current paragraph is not empty
550         // or caption and if it has not the keepempty flag active
551         if (cur.lastpos() == 0 && !cpar.allowEmpty() &&
552             layout->labeltype != LABEL_SENSITIVE)
553                 return;
554
555         // a layout change may affect also the following paragraph
556         recUndo(cur, cur.pit(), undoSpan(cur.pit()) - 1);
557
558         // Always break behind a space
559         // It is better to erase the space (Dekel)
560         if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
561                 cpar.eraseChar(cur.pos(), cur.buffer().params().trackChanges);
562
563         // What should the layout for the new paragraph be?
564         int preserve_layout = 0;
565         if (keep_layout)
566                 preserve_layout = 2;
567         else
568                 preserve_layout = layout->isEnvironment();
569
570         // We need to remember this before we break the paragraph, because
571         // that invalidates the layout variable
572         bool sensitive = layout->labeltype == LABEL_SENSITIVE;
573
574         // we need to set this before we insert the paragraph.
575         bool const isempty = cpar.allowEmpty() && cpar.empty();
576
577         lyx::breakParagraph(cur.buffer().params(), paragraphs(), cpit,
578                          cur.pos(), preserve_layout);
579
580         // After this, neither paragraph contains any rows!
581
582         cpit = cur.pit();
583         pit_type next_par = cpit + 1;
584
585         // well this is the caption hack since one caption is really enough
586         if (sensitive) {
587                 if (cur.pos() == 0)
588                         // set to standard-layout
589                         pars_[cpit].applyLayout(tclass.defaultLayout());
590                 else
591                         // set to standard-layout
592                         pars_[next_par].applyLayout(tclass.defaultLayout());
593         }
594
595         while (!pars_[next_par].empty() && pars_[next_par].isNewline(0)) {
596                 if (!pars_[next_par].eraseChar(0, cur.buffer().params().trackChanges))
597                         break; // the character couldn't be deleted physically due to change tracking
598         }
599
600         updateLabels(cur.buffer());
601
602         // A singlePar update is not enough in this case.
603         cur.updateFlags(Update::Force);
604
605         // This check is necessary. Otherwise the new empty paragraph will
606         // be deleted automatically. And it is more friendly for the user!
607         if (cur.pos() != 0 || isempty)
608                 setCursor(cur, cur.pit() + 1, 0);
609         else
610                 setCursor(cur, cur.pit(), 0);
611 }
612
613
614 // insert a character, moves all the following breaks in the
615 // same Paragraph one to the right and make a rebreak
616 void Text::insertChar(Cursor & cur, char_type c)
617 {
618         BOOST_ASSERT(this == cur.text());
619         BOOST_ASSERT(c != Paragraph::META_INSET);
620
621         recordUndo(cur, Undo::INSERT);
622
623         Buffer const & buffer = cur.buffer();
624         Paragraph & par = cur.paragraph();
625         // try to remove this
626         pit_type const pit = cur.pit();
627
628         bool const freeSpacing = par.layout()->free_spacing ||
629                 par.isFreeSpacing();
630
631         if (lyxrc.auto_number) {
632                 static docstring const number_operators = from_ascii("+-/*");
633                 static docstring const number_unary_operators = from_ascii("+-");
634                 static docstring const number_seperators = from_ascii(".,:");
635
636                 if (current_font.number() == Font::ON) {
637                         if (!isDigit(c) && !contains(number_operators, c) &&
638                             !(contains(number_seperators, c) &&
639                               cur.pos() != 0 &&
640                               cur.pos() != cur.lastpos() &&
641                               getFont(buffer, par, cur.pos()).number() == Font::ON &&
642                               getFont(buffer, par, cur.pos() - 1).number() == Font::ON)
643                            )
644                                 number(cur); // Set current_font.number to OFF
645                 } else if (isDigit(c) &&
646                            real_current_font.isVisibleRightToLeft()) {
647                         number(cur); // Set current_font.number to ON
648
649                         if (cur.pos() != 0) {
650                                 char_type const c = par.getChar(cur.pos() - 1);
651                                 if (contains(number_unary_operators, c) &&
652                                     (cur.pos() == 1
653                                      || par.isSeparator(cur.pos() - 2)
654                                      || par.isNewline(cur.pos() - 2))
655                                   ) {
656                                         setCharFont(buffer, pit, cur.pos() - 1, current_font);
657                                 } else if (contains(number_seperators, c)
658                                      && cur.pos() >= 2
659                                      && getFont(buffer, par, cur.pos() - 2).number() == Font::ON) {
660                                         setCharFont(buffer, pit, cur.pos() - 1, current_font);
661                                 }
662                         }
663                 }
664         }
665
666         // In Bidi text, we want spaces to be treated in a special way: spaces
667         // which are between words in different languages should get the 
668         // paragraph's language; otherwise, spaces should keep the language 
669         // they were originally typed in. This is only in effect while typing;
670         // after the text is already typed in, the user can always go back and
671         // explicitly set the language of a space as desired. But 99.9% of the
672         // time, what we're doing here is what the user actually meant.
673         // 
674         // The following cases are the ones in which the language of the space
675         // should be changed to match that of the containing paragraph. In the
676         // depictions, lowercase is LTR, uppercase is RTL, underscore (_) 
677         // represents a space, pipe (|) represents the cursor position (so the
678         // character before it is the one just typed in). The different cases
679         // are depicted logically (not visually), from left to right:
680         // 
681         // 1. A_a|
682         // 2. a_A|
683         //
684         // Theoretically, there are other situations that we should, perhaps, deal
685         // with (e.g.: a|_A, A|_a). In practice, though, there really isn't any 
686         // point (to understand why, just try to create this situation...).
687
688         if ((cur.pos() >= 2) && (par.isLineSeparator(cur.pos() - 1))) {
689                 // get font in front and behind the space in question. But do NOT 
690                 // use getFont(cur.pos()) because the character c is not inserted yet
691                 Font const & pre_space_font  = getFont(buffer, par, cur.pos() - 2);
692                 Font const & post_space_font = real_current_font;
693                 bool pre_space_rtl  = pre_space_font.isVisibleRightToLeft();
694                 bool post_space_rtl = post_space_font.isVisibleRightToLeft();
695                 
696                 if (pre_space_rtl != post_space_rtl) {
697                         // Set the space's language to match the language of the 
698                         // adjacent character whose direction is the paragraph's
699                         // direction; don't touch other properties of the font
700                         Language const * lang = 
701                                 (pre_space_rtl == par.isRightToLeftPar(buffer.params())) ?
702                                 pre_space_font.language() : post_space_font.language();
703
704                         Font space_font = getFont(buffer, par, cur.pos() - 1);
705                         space_font.setLanguage(lang);
706                         par.setFont(cur.pos() - 1, space_font);
707                 }
708         }
709         
710         // Next check, if there will be two blanks together or a blank at
711         // the beginning of a paragraph.
712         // I decided to handle blanks like normal characters, the main
713         // difference are the special checks when calculating the row.fill
714         // (blank does not count at the end of a row) and the check here
715
716         // When the free-spacing option is set for the current layout,
717         // disable the double-space checking
718         if (!freeSpacing && isLineSeparatorChar(c)) {
719                 if (cur.pos() == 0) {
720                         static bool sent_space_message = false;
721                         if (!sent_space_message) {
722                                 cur.message(_("You cannot insert a space at the "
723                                                            "beginning of a paragraph. Please read the Tutorial."));
724                                 sent_space_message = true;
725                         }
726                         return;
727                 }
728                 BOOST_ASSERT(cur.pos() > 0);
729                 if ((par.isLineSeparator(cur.pos() - 1) || par.isNewline(cur.pos() - 1))
730                     && !par.isDeleted(cur.pos() - 1)) {
731                         static bool sent_space_message = false;
732                         if (!sent_space_message) {
733                                 cur.message(_("You cannot type two spaces this way. "
734                                                            "Please read the Tutorial."));
735                                 sent_space_message = true;
736                         }
737                         return;
738                 }
739         }
740
741         par.insertChar(cur.pos(), c, current_font, cur.buffer().params().trackChanges);
742         checkBufferStructure(cur.buffer(), cur);
743
744 //              cur.updateFlags(Update::Force);
745         setCursor(cur.top(), cur.pit(), cur.pos() + 1);
746         charInserted();
747 }
748
749
750 void Text::charInserted()
751 {
752         // Here we call finishUndo for every 20 characters inserted.
753         // This is from my experience how emacs does it. (Lgb)
754         static unsigned int counter;
755         if (counter < 20) {
756                 ++counter;
757         } else {
758                 finishUndo();
759                 counter = 0;
760         }
761 }
762
763
764 // the cursor set functions have a special mechanism. When they
765 // realize, that you left an empty paragraph, they will delete it.
766
767 bool Text::cursorRightOneWord(Cursor & cur)
768 {
769         BOOST_ASSERT(this == cur.text());
770
771         Cursor old = cur;
772
773         if (old.pos() == old.lastpos() && old.pit() != old.lastpit()) {
774                 ++old.pit();
775                 old.pos() = 0;
776         } else {
777                 // Advance through word.
778                 while (old.pos() != old.lastpos() && old.paragraph().isLetter(old.pos()))
779                         ++old.pos();
780                 // Skip through trailing nonword stuff.
781                 while (old.pos() != old.lastpos() && !old.paragraph().isLetter(old.pos()))
782                         ++old.pos();
783         }
784         return setCursor(cur, old.pit(), old.pos());
785 }
786
787
788 bool Text::cursorLeftOneWord(Cursor & cur)
789 {
790         BOOST_ASSERT(this == cur.text());
791
792         Cursor old = cur;
793
794         if (old.pos() == 0 && old.pit() != 0) {
795                 --old.pit();
796                 old.pos() = old.lastpos();
797         } else {
798                 // Skip through initial nonword stuff.
799                 while (old.pos() != 0 && !old.paragraph().isLetter(old.pos() - 1))
800                         --old.pos();
801                 // Advance through word.
802                 while (old.pos() != 0 && old.paragraph().isLetter(old.pos() - 1))
803                         --old.pos();
804         }
805         return setCursor(cur, old.pit(), old.pos());
806 }
807
808
809 void Text::selectWord(Cursor & cur, word_location loc)
810 {
811         BOOST_ASSERT(this == cur.text());
812         CursorSlice from = cur.top();
813         CursorSlice to = cur.top();
814         getWord(from, to, loc);
815         if (cur.top() != from)
816                 setCursor(cur, from.pit(), from.pos());
817         if (to == from)
818                 return;
819         cur.resetAnchor();
820         setCursor(cur, to.pit(), to.pos());
821         cur.setSelection();
822 }
823
824
825 // Select the word currently under the cursor when no
826 // selection is currently set
827 bool Text::selectWordWhenUnderCursor(Cursor & cur, word_location loc)
828 {
829         BOOST_ASSERT(this == cur.text());
830         if (cur.selection())
831                 return false;
832         selectWord(cur, loc);
833         return cur.selection();
834 }
835
836
837 void Text::acceptOrRejectChanges(Cursor & cur, ChangeOp op)
838 {
839         BOOST_ASSERT(this == cur.text());
840
841         if (!cur.selection())
842                 return;
843
844         recordUndoSelection(cur, Undo::ATOMIC);
845
846         pit_type begPit = cur.selectionBegin().pit();
847         pit_type endPit = cur.selectionEnd().pit();
848
849         pos_type begPos = cur.selectionBegin().pos();
850         pos_type endPos = cur.selectionEnd().pos();
851
852         // keep selection info, because endPos becomes invalid after the first loop
853         bool endsBeforeEndOfPar = (endPos < pars_[endPit].size());
854
855         // first, accept/reject changes within each individual paragraph (do not consider end-of-par)
856
857         for (pit_type pit = begPit; pit <= endPit; ++pit) {
858                 pos_type parSize = pars_[pit].size();
859
860                 // ignore empty paragraphs; otherwise, an assertion will fail for
861                 // acceptChanges(bparams, 0, 0) or rejectChanges(bparams, 0, 0)
862                 if (parSize == 0)
863                         continue;
864
865                 // do not consider first paragraph if the cursor starts at pos size()
866                 if (pit == begPit && begPos == parSize)
867                         continue;
868
869                 // do not consider last paragraph if the cursor ends at pos 0
870                 if (pit == endPit && endPos == 0)
871                         break; // last iteration anyway
872
873                 pos_type left  = (pit == begPit ? begPos : 0);
874                 pos_type right = (pit == endPit ? endPos : parSize);
875
876                 if (op == ACCEPT) {
877                         pars_[pit].acceptChanges(cur.buffer().params(), left, right);
878                 } else {
879                         pars_[pit].rejectChanges(cur.buffer().params(), left, right);
880                 }
881         }
882
883         // next, accept/reject imaginary end-of-par characters
884
885         for (pit_type pit = begPit; pit <= endPit; ++pit) {
886                 pos_type pos = pars_[pit].size();
887
888                 // skip if the selection ends before the end-of-par
889                 if (pit == endPit && endsBeforeEndOfPar)
890                         break; // last iteration anyway
891
892                 // skip if this is not the last paragraph of the document
893                 // note: the user should be able to accept/reject the par break of the last par!
894                 if (pit == endPit && pit + 1 != int(pars_.size()))
895                         break; // last iteration anway
896
897                 if (op == ACCEPT) {
898                         if (pars_[pit].isInserted(pos)) {
899                                 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
900                         } else if (pars_[pit].isDeleted(pos)) {
901                                 if (pit + 1 == int(pars_.size())) {
902                                         // we cannot remove a par break at the end of the last paragraph;
903                                         // instead, we mark it unchanged
904                                         pars_[pit].setChange(pos, Change(Change::UNCHANGED));
905                                 } else {
906                                         mergeParagraph(cur.buffer().params(), pars_, pit);
907                                         --endPit;
908                                         --pit;
909                                 }
910                         }
911                 } else {
912                         if (pars_[pit].isDeleted(pos)) {
913                                 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
914                         } else if (pars_[pit].isInserted(pos)) {
915                                 if (pit + 1 == int(pars_.size())) {
916                                         // we mark the par break at the end of the last paragraph unchanged
917                                         pars_[pit].setChange(pos, Change(Change::UNCHANGED));
918                                 } else {
919                                         mergeParagraph(cur.buffer().params(), pars_, pit);
920                                         --endPit;
921                                         --pit;
922                                 }
923                         }
924                 }
925         }
926
927         // finally, invoke the DEPM
928
929         deleteEmptyParagraphMechanism(begPit, endPit, cur.buffer().params().trackChanges);
930
931         //
932
933         finishUndo();
934         cur.clearSelection();
935         setCursorIntern(cur, begPit, begPos);
936         cur.updateFlags(Update::Force);
937         updateLabels(cur.buffer());
938 }
939
940
941 void Text::acceptChanges(BufferParams const & bparams)
942 {
943         lyx::acceptChanges(pars_, bparams);
944         deleteEmptyParagraphMechanism(0, pars_.size() - 1, bparams.trackChanges);
945 }
946
947
948 void Text::rejectChanges(BufferParams const & bparams)
949 {
950         pit_type pars_size = static_cast<pit_type>(pars_.size());
951
952         // first, reject changes within each individual paragraph
953         // (do not consider end-of-par)
954         for (pit_type pit = 0; pit < pars_size; ++pit) {
955                 if (!pars_[pit].empty())   // prevent assertion failure
956                         pars_[pit].rejectChanges(bparams, 0, pars_[pit].size());
957         }
958
959         // next, reject imaginary end-of-par characters
960         for (pit_type pit = 0; pit < pars_size; ++pit) {
961                 pos_type pos = pars_[pit].size();
962
963                 if (pars_[pit].isDeleted(pos)) {
964                         pars_[pit].setChange(pos, Change(Change::UNCHANGED));
965                 } else if (pars_[pit].isInserted(pos)) {
966                         if (pit == pars_size - 1) {
967                                 // we mark the par break at the end of the last
968                                 // paragraph unchanged
969                                 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
970                         } else {
971                                 mergeParagraph(bparams, pars_, pit);
972                                 --pit;
973                                 --pars_size;
974                         }
975                 }
976         }
977
978         // finally, invoke the DEPM
979         deleteEmptyParagraphMechanism(0, pars_size - 1, bparams.trackChanges);
980 }
981
982
983 // Delete from cursor up to the end of the current or next word.
984 void Text::deleteWordForward(Cursor & cur)
985 {
986         BOOST_ASSERT(this == cur.text());
987         if (cur.lastpos() == 0)
988                 cursorRight(cur);
989         else {
990                 cur.resetAnchor();
991                 cur.selection() = true;
992                 cursorRightOneWord(cur);
993                 cur.setSelection();
994                 cutSelection(cur, true, false);
995                 checkBufferStructure(cur.buffer(), cur);
996         }
997 }
998
999
1000 // Delete from cursor to start of current or prior word.
1001 void Text::deleteWordBackward(Cursor & cur)
1002 {
1003         BOOST_ASSERT(this == cur.text());
1004         if (cur.lastpos() == 0)
1005                 cursorLeft(cur);
1006         else {
1007                 cur.resetAnchor();
1008                 cur.selection() = true;
1009                 cursorLeftOneWord(cur);
1010                 cur.setSelection();
1011                 cutSelection(cur, true, false);
1012                 checkBufferStructure(cur.buffer(), cur);
1013         }
1014 }
1015
1016
1017 // Kill to end of line.
1018 void Text::deleteLineForward(Cursor & cur)
1019 {
1020         BOOST_ASSERT(this == cur.text());
1021         if (cur.lastpos() == 0) {
1022                 // Paragraph is empty, so we just go to the right
1023                 cursorRight(cur);
1024         } else {
1025                 cur.resetAnchor();
1026                 cur.selection() = true; // to avoid deletion
1027                 cursorEnd(cur);
1028                 cur.setSelection();
1029                 // What is this test for ??? (JMarc)
1030                 if (!cur.selection())
1031                         deleteWordForward(cur);
1032                 else
1033                         cutSelection(cur, true, false);
1034                 checkBufferStructure(cur.buffer(), cur);
1035         }
1036 }
1037
1038
1039 void Text::changeCase(Cursor & cur, Text::TextCase action)
1040 {
1041         BOOST_ASSERT(this == cur.text());
1042         CursorSlice from;
1043         CursorSlice to;
1044
1045         if (cur.selection()) {
1046                 from = cur.selBegin();
1047                 to = cur.selEnd();
1048         } else {
1049                 from = cur.top();
1050                 getWord(from, to, PARTIAL_WORD);
1051                 cursorRightOneWord(cur);
1052         }
1053
1054         recordUndoSelection(cur, Undo::ATOMIC);
1055
1056         pit_type begPit = from.pit();
1057         pit_type endPit = to.pit();
1058
1059         pos_type begPos = from.pos();
1060         pos_type endPos = to.pos();
1061
1062         bool const trackChanges = cur.buffer().params().trackChanges;
1063
1064         pos_type right = 0; // needed after the for loop
1065
1066         for (pit_type pit = begPit; pit <= endPit; ++pit) {
1067                 pos_type parSize = pars_[pit].size();
1068
1069                 pos_type pos = (pit == begPit ? begPos : 0);
1070                 right = (pit == endPit ? endPos : parSize);
1071
1072                 // process sequences of modified characters; in change
1073                 // tracking mode, this approach results in much better
1074                 // usability than changing case on a char-by-char basis
1075                 docstring changes;
1076
1077                 bool capitalize = true;
1078
1079                 for (; pos < right; ++pos) {
1080                         char_type oldChar = pars_[pit].getChar(pos);
1081                         char_type newChar = oldChar;
1082
1083                         // ignore insets and don't play with deleted text!
1084                         if (oldChar != Paragraph::META_INSET && !pars_[pit].isDeleted(pos)) {
1085                                 switch (action) {
1086                                 case text_lowercase:
1087                                         newChar = lowercase(oldChar);
1088                                         break;
1089                                 case text_capitalization:
1090                                         if (capitalize) {
1091                                                 newChar = uppercase(oldChar);
1092                                                 capitalize = false;
1093                                         }
1094                                         break;
1095                                 case text_uppercase:
1096                                         newChar = uppercase(oldChar);
1097                                         break;
1098                                 }
1099                         }
1100
1101                         if (!pars_[pit].isLetter(pos) || pars_[pit].isDeleted(pos)) {
1102                                 capitalize = true; // permit capitalization again
1103                         }
1104
1105                         if (oldChar != newChar) {
1106                                 changes += newChar;
1107                         }
1108
1109                         if (oldChar == newChar || pos == right - 1) {
1110                                 if (oldChar != newChar) {
1111                                         pos++; // step behind the changing area
1112                                 }
1113                                 int erasePos = pos - changes.size();
1114                                 for (size_t i = 0; i < changes.size(); i++) {
1115                                         pars_[pit].insertChar(pos, changes[i],
1116                                                 pars_[pit].getFontSettings(cur.buffer().params(),
1117                                                                 erasePos),
1118                                                 trackChanges);
1119                                         if (!pars_[pit].eraseChar(erasePos, trackChanges)) {
1120                                                 ++erasePos;
1121                                                 ++pos; // advance
1122                                                 ++right; // expand selection
1123                                         }
1124                                 }
1125                                 changes.clear();
1126                         }
1127                 }
1128         }
1129
1130         // the selection may have changed due to logically-only deleted chars
1131         setCursor(cur, begPit, begPos);
1132         cur.resetAnchor();
1133         setCursor(cur, endPit, right);
1134         cur.setSelection();
1135
1136         checkBufferStructure(cur.buffer(), cur);
1137 }
1138
1139
1140 bool Text::handleBibitems(Cursor & cur)
1141 {
1142         if (cur.paragraph().layout()->labeltype != LABEL_BIBLIO)
1143                 return false;
1144         // if a bibitem is deleted, merge with previous paragraph
1145         // if this is a bibliography item as well
1146         if (cur.pos() == 0) {
1147                 BufferParams const & bufparams = cur.buffer().params();
1148                 Paragraph const & par = cur.paragraph();
1149                 Cursor prevcur = cur;
1150                 if (cur.pit() > 0) {
1151                         --prevcur.pit();
1152                         prevcur.pos() = prevcur.lastpos();
1153                 }
1154                 Paragraph const & prevpar = prevcur.paragraph();
1155                 if (cur.pit() > 0 && par.layout() == prevpar.layout()) {
1156                         recordUndo(cur, Undo::ATOMIC, prevcur.pit());
1157                         mergeParagraph(bufparams, cur.text()->paragraphs(),
1158                                        prevcur.pit());
1159                         updateLabels(cur.buffer());
1160                         setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1161                         cur.updateFlags(Update::Force);
1162                 // if not, reset the paragraph to default
1163                 } else
1164                         cur.paragraph().layout(
1165                                 bufparams.getTextClass().defaultLayout());
1166                 return true;
1167         }
1168         return false;
1169 }
1170
1171
1172 bool Text::erase(Cursor & cur)
1173 {
1174         BOOST_ASSERT(this == cur.text());
1175         bool needsUpdate = false;
1176         Paragraph & par = cur.paragraph();
1177
1178         if (cur.pos() != cur.lastpos()) {
1179                 // this is the code for a normal delete, not pasting
1180                 // any paragraphs
1181                 recordUndo(cur, Undo::DELETE);
1182                 if(!par.eraseChar(cur.pos(), cur.buffer().params().trackChanges)) {
1183                         // the character has been logically deleted only => skip it
1184                         cur.top().forwardPos();
1185                 }
1186                 checkBufferStructure(cur.buffer(), cur);
1187                 needsUpdate = true;
1188         } else {
1189                 if (cur.pit() == cur.lastpit())
1190                         return dissolveInset(cur);
1191
1192                 if (!par.isMergedOnEndOfParDeletion(cur.buffer().params().trackChanges)) {
1193                         par.setChange(cur.pos(), Change(Change::DELETED));
1194                         cur.forwardPos();
1195                         needsUpdate = true;
1196                 } else {
1197                         setCursorIntern(cur, cur.pit() + 1, 0);
1198                         needsUpdate = backspacePos0(cur);
1199                 }
1200         }
1201
1202         needsUpdate |= handleBibitems(cur);
1203
1204         if (needsUpdate) {
1205                 // Make sure the cursor is correct. Is this really needed?
1206                 // No, not really... at least not here!
1207                 cur.text()->setCursor(cur.top(), cur.pit(), cur.pos());
1208                 checkBufferStructure(cur.buffer(), cur);
1209         }
1210
1211         return needsUpdate;
1212 }
1213
1214
1215 bool Text::backspacePos0(Cursor & cur)
1216 {
1217         BOOST_ASSERT(this == cur.text());
1218         if (cur.pit() == 0)
1219                 return false;
1220
1221         bool needsUpdate = false;
1222
1223         BufferParams const & bufparams = cur.buffer().params();
1224         TextClass const & tclass = bufparams.getTextClass();
1225         ParagraphList & plist = cur.text()->paragraphs();
1226         Paragraph const & par = cur.paragraph();
1227         Cursor prevcur = cur;
1228         --prevcur.pit();
1229         prevcur.pos() = prevcur.lastpos();
1230         Paragraph const & prevpar = prevcur.paragraph();
1231
1232         // is it an empty paragraph?
1233         if (cur.lastpos() == 0
1234             || (cur.lastpos() == 1 && par.isSeparator(0))) {
1235                 recordUndo(cur, Undo::ATOMIC, prevcur.pit(), cur.pit());
1236                 plist.erase(boost::next(plist.begin(), cur.pit()));
1237                 needsUpdate = true;
1238         }
1239         // is previous par empty?
1240         else if (prevcur.lastpos() == 0
1241                  || (prevcur.lastpos() == 1 && prevpar.isSeparator(0))) {
1242                 recordUndo(cur, Undo::ATOMIC, prevcur.pit(), cur.pit());
1243                 plist.erase(boost::next(plist.begin(), prevcur.pit()));
1244                 needsUpdate = true;
1245         }
1246         // Pasting is not allowed, if the paragraphs have different
1247         // layouts. I think it is a real bug of all other
1248         // word processors to allow it. It confuses the user.
1249         // Correction: Pasting is always allowed with standard-layout
1250         else if (par.layout() == prevpar.layout()
1251                  || par.layout() == tclass.defaultLayout()) {
1252                 recordUndo(cur, Undo::ATOMIC, prevcur.pit());
1253                 mergeParagraph(bufparams, plist, prevcur.pit());
1254                 needsUpdate = true;
1255         }
1256
1257         if (needsUpdate) {
1258                 updateLabels(cur.buffer());
1259                 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1260         }
1261
1262         return needsUpdate;
1263 }
1264
1265
1266 bool Text::backspace(Cursor & cur)
1267 {
1268         BOOST_ASSERT(this == cur.text());
1269         bool needsUpdate = false;
1270         if (cur.pos() == 0) {
1271                 if (cur.pit() == 0)
1272                         return dissolveInset(cur);
1273
1274                 Paragraph & prev_par = pars_[cur.pit() - 1];
1275
1276                 if (!prev_par.isMergedOnEndOfParDeletion(cur.buffer().params().trackChanges)) {
1277                         prev_par.setChange(prev_par.size(), Change(Change::DELETED));
1278                         setCursorIntern(cur, cur.pit() - 1, prev_par.size());
1279                         return true;
1280                 }
1281                 // The cursor is at the beginning of a paragraph, so
1282                 // the backspace will collapse two paragraphs into one.
1283                 needsUpdate = backspacePos0(cur);
1284
1285         } else {
1286                 // this is the code for a normal backspace, not pasting
1287                 // any paragraphs
1288                 recordUndo(cur, Undo::DELETE);
1289                 // We used to do cursorLeftIntern() here, but it is
1290                 // not a good idea since it triggers the auto-delete
1291                 // mechanism. So we do a cursorLeftIntern()-lite,
1292                 // without the dreaded mechanism. (JMarc)
1293                 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1294                                 false, cur.boundary());
1295                 cur.paragraph().eraseChar(cur.pos(), cur.buffer().params().trackChanges);
1296                 checkBufferStructure(cur.buffer(), cur);
1297         }
1298
1299         if (cur.pos() == cur.lastpos())
1300                 setCurrentFont(cur);
1301
1302         needsUpdate |= handleBibitems(cur);
1303
1304         // A singlePar update is not enough in this case.
1305 //              cur.updateFlags(Update::Force);
1306         setCursor(cur.top(), cur.pit(), cur.pos());
1307
1308         return needsUpdate;
1309 }
1310
1311
1312 bool Text::dissolveInset(Cursor & cur) {
1313         BOOST_ASSERT(this == cur.text());
1314
1315         if (isMainText(cur.bv().buffer()) || cur.inset().nargs() != 1)
1316                 return false;
1317
1318         recordUndoInset(cur);
1319         cur.selHandle(false);
1320         // save position
1321         pos_type spos = cur.pos();
1322         pit_type spit = cur.pit();
1323         ParagraphList plist;
1324         if (cur.lastpit() != 0 || cur.lastpos() != 0)
1325                 plist = paragraphs();
1326         cur.popLeft();
1327         // store cursor offset
1328         if (spit == 0)
1329                 spos += cur.pos();
1330         spit += cur.pit();
1331         Buffer & b = cur.buffer();
1332         cur.paragraph().eraseChar(cur.pos(), b.params().trackChanges);
1333         if (!plist.empty()) {
1334                 // ERT paragraphs have the Language latex_language.
1335                 // This is invalid outside of ERT, so we need to
1336                 // change it to the buffer language.
1337                 ParagraphList::iterator it = plist.begin();
1338                 ParagraphList::iterator it_end = plist.end();
1339                 for (; it != it_end; it++) {
1340                         it->changeLanguage(b.params(), latex_language,
1341                                         b.getLanguage());
1342                 }
1343
1344                 pasteParagraphList(cur, plist, b.params().getTextClass_ptr(),
1345                                    b.errorList("Paste"));
1346                 // restore position
1347                 cur.pit() = std::min(cur.lastpit(), spit);
1348                 cur.pos() = std::min(cur.lastpos(), spos);
1349         }
1350         cur.clearSelection();
1351         cur.resetAnchor();
1352         return true;
1353 }
1354
1355
1356 // only used for inset right now. should also be used for main text
1357 void Text::drawSelection(PainterInfo & pi, int x, int) const
1358 {
1359         Cursor & cur = pi.base.bv->cursor();
1360         if (!cur.selection())
1361                 return;
1362         if (!ptr_cmp(cur.text(), this))
1363                 return;
1364
1365         LYXERR(Debug::DEBUG)
1366                 << BOOST_CURRENT_FUNCTION
1367                 << "draw selection at " << x
1368                 << endl;
1369
1370         DocIterator beg = cur.selectionBegin();
1371         DocIterator end = cur.selectionEnd();
1372
1373         BufferView & bv = *pi.base.bv;
1374
1375         // the selection doesn't touch the visible screen?
1376         if (bv_funcs::status(&bv, beg) == bv_funcs::CUR_BELOW
1377             || bv_funcs::status(&bv, end) == bv_funcs::CUR_ABOVE)
1378                 return;
1379
1380         TextMetrics const & tm = bv.textMetrics(this);
1381         ParagraphMetrics const & pm1 = tm.parMetrics(beg.pit());
1382         ParagraphMetrics const & pm2 = tm.parMetrics(end.pit());
1383         Row const & row1 = pm1.getRow(beg.pos(), beg.boundary());
1384         Row const & row2 = pm2.getRow(end.pos(), end.boundary());
1385
1386         // clip above
1387         int middleTop;
1388         bool const clipAbove = 
1389                 (bv_funcs::status(&bv, beg) == bv_funcs::CUR_ABOVE);
1390         if (clipAbove)
1391                 middleTop = 0;
1392         else
1393                 middleTop = bv_funcs::getPos(bv, beg, beg.boundary()).y_ + row1.descent();
1394         
1395         // clip below
1396         int middleBottom;
1397         bool const clipBelow = 
1398                 (bv_funcs::status(&bv, end) == bv_funcs::CUR_BELOW);
1399         if (clipBelow)
1400                 middleBottom = bv.workHeight();
1401         else
1402                 middleBottom = bv_funcs::getPos(bv, end, end.boundary()).y_ - row2.ascent();
1403
1404         // start and end in the same line?
1405         if (!(clipAbove || clipBelow) && &row1 == &row2)
1406                 // then only draw this row's selection
1407                 drawRowSelection(pi, x, row1, beg, end, false, false);
1408         else {
1409                 if (!clipAbove) {
1410                         // get row end
1411                         DocIterator begRowEnd = beg;
1412                         begRowEnd.pos() = row1.endpos();
1413                         begRowEnd.boundary(true);
1414                         
1415                         // draw upper rectangle
1416                         drawRowSelection(pi, x, row1, beg, begRowEnd, false, true);
1417                 }
1418                         
1419                 if (middleTop < middleBottom) {
1420                         // draw middle rectangle
1421                         pi.pain.fillRectangle(x, middleTop, 
1422                                                                                                                 tm.width(), middleBottom - middleTop, 
1423                                                                                                                 Color::selection);
1424                 }
1425
1426                 if (!clipBelow) {
1427                         // get row begin
1428                         DocIterator endRowBeg = end;
1429                         endRowBeg.pos() = row2.pos();
1430                         endRowBeg.boundary(false);
1431                         
1432                         // draw low rectangle
1433                         drawRowSelection(pi, x, row2, endRowBeg, end, true, false);
1434                 }
1435         }
1436 }
1437
1438
1439 void Text::drawRowSelection(PainterInfo & pi, int x, Row const & row,
1440                                                                                                                 DocIterator const & beg, DocIterator const & end, 
1441                                                                                                                 bool drawOnBegMargin, bool drawOnEndMargin) const
1442 {
1443         BufferView & bv = *pi.base.bv;
1444         Buffer & buffer = bv.buffer();
1445         TextMetrics const & tm = bv.textMetrics(this);
1446         DocIterator cur = beg;
1447         int x1 = cursorX(bv, beg.top(), beg.boundary());
1448         int x2 = cursorX(bv, end.top(), end.boundary());
1449         int y1 = bv_funcs::getPos(bv, cur, cur.boundary()).y_ - row.ascent();
1450         int y2 = y1 + row.height();
1451         
1452         // draw the margins
1453         if (drawOnBegMargin) {
1454                 if (isRTL(buffer, beg.paragraph()))
1455                         pi.pain.fillRectangle(x + x1, y1, tm.width() - x1, y2 - y1, Color::selection);
1456                 else
1457                         pi.pain.fillRectangle(x, y1, x1, y2 - y1, Color::selection);
1458         }
1459         
1460         if (drawOnEndMargin) {
1461                 if (isRTL(buffer, beg.paragraph()))
1462                         pi.pain.fillRectangle(x, y1, x2, y2 - y1, Color::selection);
1463                 else
1464                         pi.pain.fillRectangle(x + x2, y1, tm.width() - x2, y2 - y1, Color::selection);
1465         }
1466         
1467         // if we are on a boundary from the beginning, it's probably
1468         // a RTL boundary and we jump to the other side directly as this
1469         // segement is 0-size and confuses the logic below
1470         if (cur.boundary())
1471                 cur.boundary(false);
1472         
1473         // go through row and draw from RTL boundary to RTL boundary
1474         while (cur < end) {
1475                 bool drawNow = false;
1476                 
1477                 // simplified cursorRight code below which does not
1478                 // descend into insets and which does not go into the
1479                 // next line. Compare the logic with the original cursorRight
1480                 
1481                 // if left of boundary -> just jump to right side
1482                 // but for RTL boundaries don't, because: abc|DDEEFFghi -> abcDDEEF|Fghi
1483                 if (cur.boundary()) {
1484                         cur.boundary(false);
1485                 }       else if (isRTLBoundary(buffer, cur.paragraph(), cur.pos() + 1)) {
1486                         // in front of RTL boundary -> Stay on this side of the boundary because:
1487                         //   ab|cDDEEFFghi -> abc|DDEEFFghi
1488                         ++cur.pos();
1489                         cur.boundary(true);
1490                         drawNow = true;
1491                 } else {
1492                         // move right
1493                         ++cur.pos();
1494                         
1495                         // line end?
1496                         if (cur.pos() == row.endpos())
1497                                 cur.boundary(true);
1498                 }
1499                         
1500                 if (x1 == -1) {
1501                         // the previous segment was just drawn, now the next starts
1502                         x1 = cursorX(bv, cur.top(), cur.boundary());
1503                 }
1504                 
1505                 if (!(cur < end) || drawNow) {
1506                         x2 = cursorX(bv, cur.top(), cur.boundary());
1507                         pi.pain.fillRectangle(x + min(x1,x2), y1, abs(x2 - x1), y2 - y1,
1508                                                                                                                 Color::selection);
1509                         
1510                         // reset x1, so it is set again next round (which will be on the 
1511                         // right side of a boundary or at the selection end)
1512                         x1 = -1;
1513                 }
1514         }
1515 }
1516
1517
1518
1519 bool Text::isLastRow(pit_type pit, Row const & row) const
1520 {
1521         return row.endpos() >= pars_[pit].size()
1522                 && pit + 1 == pit_type(paragraphs().size());
1523 }
1524
1525
1526 bool Text::isFirstRow(pit_type pit, Row const & row) const
1527 {
1528         return row.pos() == 0 && pit == 0;
1529 }
1530
1531
1532 void Text::getWord(CursorSlice & from, CursorSlice & to,
1533         word_location const loc)
1534 {
1535         Paragraph const & from_par = pars_[from.pit()];
1536         switch (loc) {
1537         case WHOLE_WORD_STRICT:
1538                 if (from.pos() == 0 || from.pos() == from_par.size()
1539                     || !from_par.isLetter(from.pos())
1540                     || !from_par.isLetter(from.pos() - 1)) {
1541                         to = from;
1542                         return;
1543                 }
1544                 // no break here, we go to the next
1545
1546         case WHOLE_WORD:
1547                 // If we are already at the beginning of a word, do nothing
1548                 if (!from.pos() || !from_par.isLetter(from.pos() - 1))
1549                         break;
1550                 // no break here, we go to the next
1551
1552         case PREVIOUS_WORD:
1553                 // always move the cursor to the beginning of previous word
1554                 while (from.pos() && from_par.isLetter(from.pos() - 1))
1555                         --from.pos();
1556                 break;
1557         case NEXT_WORD:
1558                 lyxerr << "Text::getWord: NEXT_WORD not implemented yet"
1559                        << endl;
1560                 break;
1561         case PARTIAL_WORD:
1562                 // no need to move the 'from' cursor
1563                 break;
1564         }
1565         to = from;
1566         Paragraph & to_par = pars_[to.pit()];
1567         while (to.pos() < to_par.size() && to_par.isLetter(to.pos()))
1568                 ++to.pos();
1569 }
1570
1571
1572 void Text::write(Buffer const & buf, std::ostream & os) const
1573 {
1574         ParagraphList::const_iterator pit = paragraphs().begin();
1575         ParagraphList::const_iterator end = paragraphs().end();
1576         depth_type dth = 0;
1577         for (; pit != end; ++pit)
1578                 pit->write(buf, os, buf.params(), dth);
1579
1580         // Close begin_deeper
1581         for(; dth > 0; --dth)
1582                 os << "\n\\end_deeper";
1583 }
1584
1585
1586 bool Text::read(Buffer const & buf, Lexer & lex, ErrorList & errorList)
1587 {
1588         depth_type depth = 0;
1589
1590         while (lex.isOK()) {
1591                 lex.nextToken();
1592                 string const token = lex.getString();
1593
1594                 if (token.empty())
1595                         continue;
1596
1597                 if (token == "\\end_inset")
1598                         break;
1599
1600                 if (token == "\\end_body")
1601                         continue;
1602
1603                 if (token == "\\begin_body")
1604                         continue;
1605
1606                 if (token == "\\end_document")
1607                         return false;
1608
1609                 if (token == "\\begin_layout") {
1610                         lex.pushToken(token);
1611
1612                         Paragraph par;
1613                         par.params().depth(depth);
1614                         par.setFont(0, Font(Font::ALL_INHERIT, buf.params().language));
1615                         pars_.push_back(par);
1616
1617                         // FIXME: goddamn InsetTabular makes us pass a Buffer
1618                         // not BufferParams
1619                         lyx::readParagraph(buf, pars_.back(), lex, errorList);
1620
1621                 } else if (token == "\\begin_deeper") {
1622                         ++depth;
1623                 } else if (token == "\\end_deeper") {
1624                         if (!depth) {
1625                                 lex.printError("\\end_deeper: " "depth is already null");
1626                         } else {
1627                                 --depth;
1628                         }
1629                 } else {
1630                         lyxerr << "Handling unknown body token: `"
1631                                << token << '\'' << endl;
1632                 }
1633         }
1634         return true;
1635 }
1636
1637 int Text::cursorX(BufferView const & bv, CursorSlice const & sl,
1638                 bool boundary) const
1639 {
1640         TextMetrics const & tm = bv.textMetrics(sl.text());
1641         pit_type const pit = sl.pit();
1642         Paragraph const & par = pars_[pit];
1643         ParagraphMetrics const & pm = tm.parMetrics(pit);
1644         if (pm.rows().empty())
1645                 return 0;
1646
1647         pos_type ppos = sl.pos();
1648         // Correct position in front of big insets
1649         bool const boundary_correction = ppos != 0 && boundary;
1650         if (boundary_correction)
1651                 --ppos;
1652
1653         Row const & row = pm.getRow(sl.pos(), boundary);
1654
1655         pos_type cursor_vpos = 0;
1656
1657         Buffer const & buffer = bv.buffer();
1658         double x = row.x;
1659         Bidi bidi;
1660         bidi.computeTables(par, buffer, row);
1661
1662         pos_type const row_pos  = row.pos();
1663         pos_type const end      = row.endpos();
1664         // Spaces at logical line breaks in bidi text must be skipped during 
1665         // cursor positioning. However, they may appear visually in the middle
1666         // of a row; they must be skipped, wherever they are...
1667         // * logically "abc_[HEBREW_\nHEBREW]"
1668         // * visually "abc_[_WERBEH\nWERBEH]"
1669         pos_type skipped_sep_vpos = -1;
1670
1671         if (end <= row_pos)
1672                 cursor_vpos = row_pos;
1673         else if (ppos >= end)
1674                 cursor_vpos = isRTL(buffer, par) ? row_pos : end;
1675         else if (ppos > row_pos && ppos >= end)
1676                 // Place cursor after char at (logical) position pos - 1
1677                 cursor_vpos = (bidi.level(ppos - 1) % 2 == 0)
1678                         ? bidi.log2vis(ppos - 1) + 1 : bidi.log2vis(ppos - 1);
1679         else
1680                 // Place cursor before char at (logical) position ppos
1681                 cursor_vpos = (bidi.level(ppos) % 2 == 0)
1682                         ? bidi.log2vis(ppos) : bidi.log2vis(ppos) + 1;
1683
1684         pos_type body_pos = par.beginOfBody();
1685         if (body_pos > 0 &&
1686             (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1687                 body_pos = 0;
1688
1689         // Use font span to speed things up, see below
1690         FontSpan font_span;
1691         Font font;
1692
1693         // If the last logical character is a separator, skip it, unless
1694         // it's in the last row of a paragraph; see skipped_sep_vpos declaration
1695         if (end > 0 && end < par.size() && par.isSeparator(end - 1))
1696                 skipped_sep_vpos = bidi.log2vis(end - 1);
1697         
1698         for (pos_type vpos = row_pos; vpos < cursor_vpos; ++vpos) {
1699                 // Skip the separator which is at the logical end of the row
1700                 if (vpos == skipped_sep_vpos)
1701                         continue;
1702                 pos_type pos = bidi.vis2log(vpos);
1703                 if (body_pos > 0 && pos == body_pos - 1) {
1704                         FontMetrics const & labelfm = theFontMetrics(
1705                                 getLabelFont(buffer, par));
1706                         x += row.label_hfill + labelfm.width(par.layout()->labelsep);
1707                         if (par.isLineSeparator(body_pos - 1))
1708                                 x -= tm.singleWidth(pit, body_pos - 1);
1709                 }
1710
1711                 // Use font span to speed things up, see above
1712                 if (pos < font_span.first || pos > font_span.last) {
1713                         font_span = par.fontSpan(pos);
1714                         font = getFont(buffer, par, pos);
1715                 }
1716
1717                 x += pm.singleWidth(pos, font);
1718
1719                 if (par.hfillExpansion(row, pos))
1720                         x += (pos >= body_pos) ? row.hfill : row.label_hfill;
1721                 else if (par.isSeparator(pos) && pos >= body_pos)
1722                         x += row.separator;
1723         }
1724
1725         // see correction above
1726         if (boundary_correction) {
1727                 if (isRTL(buffer, sl, boundary))
1728                         x -= tm.singleWidth(pit, ppos);
1729                 else
1730                         x += tm.singleWidth(pit, ppos);
1731         }
1732
1733         return int(x);
1734 }
1735
1736
1737 int Text::cursorY(BufferView const & bv, CursorSlice const & sl, bool boundary) const
1738 {
1739         //lyxerr << "Text::cursorY: boundary: " << boundary << std::endl;
1740         ParagraphMetrics const & pm = bv.parMetrics(this, sl.pit());
1741         if (pm.rows().empty())
1742                 return 0;
1743
1744         int h = 0;
1745         h -= bv.parMetrics(this, 0).rows()[0].ascent();
1746         for (pit_type pit = 0; pit < sl.pit(); ++pit) {
1747                 h += bv.parMetrics(this, pit).height();
1748         }
1749         int pos = sl.pos();
1750         if (pos && boundary)
1751                 --pos;
1752         size_t const rend = pm.pos2row(pos);
1753         for (size_t rit = 0; rit != rend; ++rit)
1754                 h += pm.rows()[rit].height();
1755         h += pm.rows()[rend].ascent();
1756         return h;
1757 }
1758
1759
1760 // Returns the current font and depth as a message.
1761 docstring Text::currentState(Cursor & cur)
1762 {
1763         BOOST_ASSERT(this == cur.text());
1764         Buffer & buf = cur.buffer();
1765         Paragraph const & par = cur.paragraph();
1766         odocstringstream os;
1767
1768         if (buf.params().trackChanges)
1769                 os << _("[Change Tracking] ");
1770
1771         Change change = par.lookupChange(cur.pos());
1772
1773         if (change.type != Change::UNCHANGED) {
1774                 Author const & a = buf.params().authors().get(change.author);
1775                 os << _("Change: ") << a.name();
1776                 if (!a.email().empty())
1777                         os << " (" << a.email() << ")";
1778                 // FIXME ctime is english, we should translate that
1779                 os << _(" at ") << ctime(&change.changetime);
1780                 os << " : ";
1781         }
1782
1783         // I think we should only show changes from the default
1784         // font. (Asger)
1785         // No, from the document font (MV)
1786         Font font = real_current_font;
1787         font.reduce(buf.params().getFont());
1788
1789         os << bformat(_("Font: %1$s"), font.stateText(&buf.params()));
1790
1791         // The paragraph depth
1792         int depth = cur.paragraph().getDepth();
1793         if (depth > 0)
1794                 os << bformat(_(", Depth: %1$d"), depth);
1795
1796         // The paragraph spacing, but only if different from
1797         // buffer spacing.
1798         Spacing const & spacing = par.params().spacing();
1799         if (!spacing.isDefault()) {
1800                 os << _(", Spacing: ");
1801                 switch (spacing.getSpace()) {
1802                 case Spacing::Single:
1803                         os << _("Single");
1804                         break;
1805                 case Spacing::Onehalf:
1806                         os << _("OneHalf");
1807                         break;
1808                 case Spacing::Double:
1809                         os << _("Double");
1810                         break;
1811                 case Spacing::Other:
1812                         os << _("Other (") << from_ascii(spacing.getValueAsString()) << ')';
1813                         break;
1814                 case Spacing::Default:
1815                         // should never happen, do nothing
1816                         break;
1817                 }
1818         }
1819
1820 #ifdef DEVEL_VERSION
1821         os << _(", Inset: ") << &cur.inset();
1822         os << _(", Paragraph: ") << cur.pit();
1823         os << _(", Id: ") << par.id();
1824         os << _(", Position: ") << cur.pos();
1825         // FIXME: Why is the check for par.size() needed?
1826         // We are called with cur.pos() == par.size() quite often.
1827         if (!par.empty() && cur.pos() < par.size()) {
1828                 // Force output of code point, not character
1829                 size_t const c = par.getChar(cur.pos());
1830                 os << _(", Char: 0x") << std::hex << c;
1831         }
1832         os << _(", Boundary: ") << cur.boundary();
1833 //      Row & row = cur.textRow();
1834 //      os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
1835 #endif
1836         return os.str();
1837 }
1838
1839
1840 docstring Text::getPossibleLabel(Cursor & cur) const
1841 {
1842         pit_type pit = cur.pit();
1843
1844         LayoutPtr layout = pars_[pit].layout();
1845
1846         docstring text;
1847         docstring par_text = pars_[pit].asString(cur.buffer(), false);
1848         for (int i = 0; i < lyxrc.label_init_length; ++i) {
1849                 if (par_text.empty())
1850                         break;
1851                 docstring head;
1852                 par_text = split(par_text, head, ' ');
1853                 // Is it legal to use spaces in labels ?
1854                 if (i > 0)
1855                         text += '-';
1856                 text += head;
1857         }
1858
1859         // No need for a prefix if the user said so.
1860         if (lyxrc.label_init_length <= 0)
1861                 return text;
1862
1863         // Will contain the label type.
1864         docstring name;
1865
1866         // For section, subsection, etc...
1867         if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
1868                 LayoutPtr const & layout2 = pars_[pit - 1].layout();
1869                 if (layout2->latextype != LATEX_PARAGRAPH) {
1870                         --pit;
1871                         layout = layout2;
1872                 }
1873         }
1874         if (layout->latextype != LATEX_PARAGRAPH)
1875                 name = from_ascii(layout->latexname());
1876
1877         // for captions, we just take the caption type
1878         Inset * caption_inset = cur.innerInsetOfType(Inset::CAPTION_CODE);
1879         if (caption_inset)
1880                 name = from_ascii(static_cast<InsetCaption *>(caption_inset)->type());
1881
1882         // If none of the above worked, we'll see if we're inside various
1883         // types of insets and take our abbreviation from them.
1884         if (name.empty()) {
1885                 Inset::Code const codes[] = {
1886                         Inset::FLOAT_CODE,
1887                         Inset::WRAP_CODE,
1888                         Inset::FOOT_CODE
1889                 };
1890                 for (unsigned int i = 0; i < (sizeof codes / sizeof codes[0]); ++i) {
1891                         Inset * float_inset = cur.innerInsetOfType(codes[i]);
1892                         if (float_inset) {
1893                                 name = float_inset->name();
1894                                 break;
1895                         }
1896                 }
1897         }
1898
1899         // Create a correct prefix for prettyref
1900         if (name == "theorem")
1901                 name = from_ascii("thm");
1902         else if (name == "Foot")
1903                 name = from_ascii("fn");
1904         else if (name == "listing")
1905                 name = from_ascii("lst");
1906
1907         if (!name.empty())
1908                 text = name.substr(0, 3) + ':' + text;
1909
1910         return text;
1911 }
1912
1913
1914 void Text::setCursorFromCoordinates(Cursor & cur, int const x, int const y)
1915 {
1916         BOOST_ASSERT(this == cur.text());
1917         pit_type pit = getPitNearY(cur.bv(), y);
1918
1919         TextMetrics const & tm = cur.bv().textMetrics(this);
1920         ParagraphMetrics const & pm = tm.parMetrics(pit);
1921
1922         int yy = cur.bv().coordCache().get(this, pit).y_ - pm.ascent();
1923         LYXERR(Debug::DEBUG)
1924                 << BOOST_CURRENT_FUNCTION
1925                 << ": x: " << x
1926                 << " y: " << y
1927                 << " pit: " << pit
1928                 << " yy: " << yy << endl;
1929
1930         int r = 0;
1931         BOOST_ASSERT(pm.rows().size());
1932         for (; r < int(pm.rows().size()) - 1; ++r) {
1933                 Row const & row = pm.rows()[r];
1934                 if (int(yy + row.height()) > y)
1935                         break;
1936                 yy += row.height();
1937         }
1938
1939         Row const & row = pm.rows()[r];
1940
1941         LYXERR(Debug::DEBUG)
1942                 << BOOST_CURRENT_FUNCTION
1943                 << ": row " << r
1944                 << " from pos: " << row.pos()
1945                 << endl;
1946
1947         bool bound = false;
1948         int xx = x;
1949         pos_type const pos = row.pos()
1950                 + tm.getColumnNearX(pit, row, xx, bound);
1951
1952         LYXERR(Debug::DEBUG)
1953                 << BOOST_CURRENT_FUNCTION
1954                 << ": setting cursor pit: " << pit
1955                 << " pos: " << pos
1956                 << endl;
1957
1958         setCursor(cur, pit, pos, true, bound);
1959         // remember new position.
1960         cur.setTargetX();
1961 }
1962
1963
1964 void Text::charsTranspose(Cursor & cur)
1965 {
1966         BOOST_ASSERT(this == cur.text());
1967
1968         pos_type pos = cur.pos();
1969
1970         // If cursor is at beginning or end of paragraph, do nothing.
1971         if (pos == cur.lastpos() || pos == 0)
1972                 return;
1973
1974         Paragraph & par = cur.paragraph();
1975
1976         // Get the positions of the characters to be transposed.
1977         pos_type pos1 = pos - 1;
1978         pos_type pos2 = pos;
1979
1980         // In change tracking mode, ignore deleted characters.
1981         while (pos2 < cur.lastpos() && par.isDeleted(pos2))
1982                 ++pos2;
1983         if (pos2 == cur.lastpos())
1984                 return;
1985
1986         while (pos1 >= 0 && par.isDeleted(pos1))
1987                 --pos1;
1988         if (pos1 < 0)
1989                 return;
1990
1991         // Don't do anything if one of the "characters" is not regular text.
1992         if (par.isInset(pos1) || par.isInset(pos2))
1993                 return;
1994
1995         // Store the characters to be transposed (including font information).
1996         char_type char1 = par.getChar(pos1);
1997         Font const font1 =
1998                 par.getFontSettings(cur.buffer().params(), pos1);
1999
2000         char_type char2 = par.getChar(pos2);
2001         Font const font2 =
2002                 par.getFontSettings(cur.buffer().params(), pos2);
2003
2004         // And finally, we are ready to perform the transposition.
2005         // Track the changes if Change Tracking is enabled.
2006         bool const trackChanges = cur.buffer().params().trackChanges;
2007
2008         recordUndo(cur);
2009
2010         par.eraseChar(pos2, trackChanges);
2011         par.eraseChar(pos1, trackChanges);
2012         par.insertChar(pos1, char2, font2, trackChanges);
2013         par.insertChar(pos2, char1, font1, trackChanges);
2014
2015         checkBufferStructure(cur.buffer(), cur);
2016
2017         // After the transposition, move cursor to after the transposition.
2018         setCursor(cur, cur.pit(), pos2);
2019         cur.forwardPos();
2020 }
2021
2022
2023 } // namespace lyx