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