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