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