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