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