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