]> git.lyx.org Git - lyx.git/blob - src/text.C
Two fixes involving RtL text drawing
[lyx.git] / src / text.C
1 /**
2  * \file src/text.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Asger Alstrup
7  * \author Lars Gullik Bjønnes
8  * \author Jean-Marc Lasgouttes
9  * \author John Levon
10  * \author André Pönitz
11  * \author Dekel Tsur
12  * \author Jürgen Vigna
13  *
14  * Full author contact details are available in file CREDITS.
15  */
16
17 #include <config.h>
18
19 #include "lyxtext.h"
20
21 #include "author.h"
22 #include "buffer.h"
23 #include "buffer_funcs.h"
24 #include "bufferparams.h"
25 #include "BufferView.h"
26 #include "cursor.h"
27 #include "coordcache.h"
28 #include "CutAndPaste.h"
29 #include "debug.h"
30 #include "dispatchresult.h"
31 #include "encoding.h"
32 #include "errorlist.h"
33 #include "funcrequest.h"
34 #include "factory.h"
35 #include "FontIterator.h"
36 #include "gettext.h"
37 #include "language.h"
38 #include "LColor.h"
39 #include "lyxlength.h"
40 #include "lyxlex.h"
41 #include "lyxrc.h"
42 #include "lyxrow.h"
43 #include "lyxrow_funcs.h"
44 #include "metricsinfo.h"
45 #include "paragraph.h"
46 #include "paragraph_funcs.h"
47 #include "ParagraphParameters.h"
48 #include "rowpainter.h"
49 #include "undo.h"
50 #include "vspace.h"
51 #include "WordLangTuple.h"
52
53 #include "frontends/font_metrics.h"
54 #include "frontends/LyXView.h"
55 #include "frontends/Painter.h"
56
57 #include "insets/insettext.h"
58 #include "insets/insetbibitem.h"
59 #include "insets/insethfill.h"
60 #include "insets/insetlatexaccent.h"
61 #include "insets/insetline.h"
62 #include "insets/insetnewline.h"
63 #include "insets/insetpagebreak.h"
64 #include "insets/insetoptarg.h"
65 #include "insets/insetspace.h"
66 #include "insets/insetspecialchar.h"
67 #include "insets/insettabular.h"
68
69 #include "support/lstrings.h"
70 #include "support/textutils.h"
71 #include "support/convert.h"
72
73 #include <boost/current_function.hpp>
74
75 #include <sstream>
76
77 using lyx::pit_type;
78 using lyx::pos_type;
79 using lyx::word_location;
80
81 using lyx::support::bformat;
82 using lyx::support::contains;
83 using lyx::support::lowercase;
84 using lyx::support::split;
85 using lyx::support::uppercase;
86
87 using lyx::cap::cutSelection;
88
89 using std::auto_ptr;
90 using std::advance;
91 using std::distance;
92 using std::max;
93 using std::min;
94 using std::endl;
95 using std::string;
96
97
98 namespace {
99
100 int numberOfSeparators(Paragraph const & par, Row const & row)
101 {
102         pos_type const first = max(row.pos(), par.beginOfBody());
103         pos_type const last = row.endpos() - 1;
104         int n = 0;
105         for (pos_type p = first; p < last; ++p) {
106                 if (par.isSeparator(p))
107                         ++n;
108         }
109         return n;
110 }
111
112
113 int numberOfLabelHfills(Paragraph const & par, Row const & row)
114 {
115         pos_type last = row.endpos() - 1;
116         pos_type first = row.pos();
117
118         // hfill *DO* count at the beginning of paragraphs!
119         if (first) {
120                 while (first < last && par.isHfill(first))
121                         ++first;
122         }
123
124         last = min(last, par.beginOfBody());
125         int n = 0;
126         for (pos_type p = first; p < last; ++p) {
127                 if (par.isHfill(p))
128                         ++n;
129         }
130         return n;
131 }
132
133
134 int numberOfHfills(Paragraph const & par, Row const & row)
135 {
136         pos_type const last = row.endpos() - 1;
137         pos_type first = row.pos();
138
139         // hfill *DO* count at the beginning of paragraphs!
140         if (first) {
141                 while (first < last && par.isHfill(first))
142                         ++first;
143         }
144
145         first = max(first, par.beginOfBody());
146
147         int n = 0;
148         for (pos_type p = first; p < last; ++p) {
149                 if (par.isHfill(p))
150                         ++n;
151         }
152         return n;
153 }
154
155
156 void readParToken(Buffer const & buf, Paragraph & par, LyXLex & lex,
157         string const & token, LyXFont & font, Change & change)
158 {
159         BufferParams const & bp = buf.params();
160
161         if (token[0] != '\\') {
162                 string::const_iterator cit = token.begin();
163                 for (; cit != token.end(); ++cit)
164                         par.insertChar(par.size(), (*cit), font, change);
165         } else if (token == "\\begin_layout") {
166                 lex.eatLine();
167                 string layoutname = lex.getString();
168
169                 font = LyXFont(LyXFont::ALL_INHERIT, bp.language);
170                 change = Change();
171
172                 LyXTextClass const & tclass = bp.getLyXTextClass();
173
174                 if (layoutname.empty()) {
175                         layoutname = tclass.defaultLayoutName();
176                 }
177
178                 bool hasLayout = tclass.hasLayout(layoutname);
179
180                 if (!hasLayout) {
181                         buf.error(ErrorItem(_("Unknown layout"),
182                         bformat(_("Layout '%1$s' does not exist in textclass '%2$s'\nTrying to use the default instead.\n"),
183                                 layoutname, tclass.name()), par.id(), 0, par.size()));
184                         layoutname = tclass.defaultLayoutName();
185                 }
186
187                 par.layout(bp.getLyXTextClass()[layoutname]);
188
189                 // Test whether the layout is obsolete.
190                 LyXLayout_ptr const & layout = par.layout();
191                 if (!layout->obsoleted_by().empty())
192                         par.layout(bp.getLyXTextClass()[layout->obsoleted_by()]);
193
194                 par.params().read(lex);
195
196         } else if (token == "\\end_layout") {
197                 lyxerr << BOOST_CURRENT_FUNCTION
198                        << ": Solitary \\end_layout in line "
199                        << lex.getLineNo() << "\n"
200                        << "Missing \\begin_layout?.\n";
201         } else if (token == "\\end_inset") {
202                 lyxerr << BOOST_CURRENT_FUNCTION
203                        << ": Solitary \\end_inset in line "
204                        << lex.getLineNo() << "\n"
205                        << "Missing \\begin_inset?.\n";
206         } else if (token == "\\begin_inset") {
207                 InsetBase * inset = readInset(lex, buf);
208                 if (inset)
209                         par.insertInset(par.size(), inset, font, change);
210                 else {
211                         lex.eatLine();
212                         string line = lex.getString();
213                         buf.error(ErrorItem(_("Unknown Inset"), line,
214                                             par.id(), 0, par.size()));
215                 }
216         } else if (token == "\\family") {
217                 lex.next();
218                 font.setLyXFamily(lex.getString());
219         } else if (token == "\\series") {
220                 lex.next();
221                 font.setLyXSeries(lex.getString());
222         } else if (token == "\\shape") {
223                 lex.next();
224                 font.setLyXShape(lex.getString());
225         } else if (token == "\\size") {
226                 lex.next();
227                 font.setLyXSize(lex.getString());
228         } else if (token == "\\lang") {
229                 lex.next();
230                 string const tok = lex.getString();
231                 Language const * lang = languages.getLanguage(tok);
232                 if (lang) {
233                         font.setLanguage(lang);
234                 } else {
235                         font.setLanguage(bp.language);
236                         lex.printError("Unknown language `$$Token'");
237                 }
238         } else if (token == "\\numeric") {
239                 lex.next();
240                 font.setNumber(font.setLyXMisc(lex.getString()));
241         } else if (token == "\\emph") {
242                 lex.next();
243                 font.setEmph(font.setLyXMisc(lex.getString()));
244         } else if (token == "\\bar") {
245                 lex.next();
246                 string const tok = lex.getString();
247
248                 if (tok == "under")
249                         font.setUnderbar(LyXFont::ON);
250                 else if (tok == "no")
251                         font.setUnderbar(LyXFont::OFF);
252                 else if (tok == "default")
253                         font.setUnderbar(LyXFont::INHERIT);
254                 else
255                         lex.printError("Unknown bar font flag "
256                                        "`$$Token'");
257         } else if (token == "\\noun") {
258                 lex.next();
259                 font.setNoun(font.setLyXMisc(lex.getString()));
260         } else if (token == "\\color") {
261                 lex.next();
262                 font.setLyXColor(lex.getString());
263         } else if (token == "\\InsetSpace" || token == "\\SpecialChar") {
264
265                 // Insets don't make sense in a free-spacing context! ---Kayvan
266                 if (par.isFreeSpacing()) {
267                         if (token == "\\InsetSpace")
268                                 par.insertChar(par.size(), ' ', font, change);
269                         else if (lex.isOK()) {
270                                 lex.next();
271                                 string const next_token = lex.getString();
272                                 if (next_token == "\\-")
273                                         par.insertChar(par.size(), '-', font, change);
274                                 else {
275                                         lex.printError("Token `$$Token' "
276                                                        "is in free space "
277                                                        "paragraph layout!");
278                                 }
279                         }
280                 } else {
281                         auto_ptr<InsetBase> inset;
282                         if (token == "\\SpecialChar" )
283                                 inset.reset(new InsetSpecialChar);
284                         else
285                                 inset.reset(new InsetSpace);
286                         inset->read(buf, lex);
287                         par.insertInset(par.size(), inset.release(),
288                                         font, change);
289                 }
290         } else if (token == "\\i") {
291                 auto_ptr<InsetBase> inset(new InsetLatexAccent);
292                 inset->read(buf, lex);
293                 par.insertInset(par.size(), inset.release(), font, change);
294         } else if (token == "\\backslash") {
295                 par.insertChar(par.size(), '\\', font, change);
296         } else if (token == "\\newline") {
297                 auto_ptr<InsetBase> inset(new InsetNewline);
298                 inset->read(buf, lex);
299                 par.insertInset(par.size(), inset.release(), font, change);
300         } else if (token == "\\LyXTable") {
301                 auto_ptr<InsetBase> inset(new InsetTabular(buf));
302                 inset->read(buf, lex);
303                 par.insertInset(par.size(), inset.release(), font, change);
304         } else if (token == "\\bibitem") {
305                 InsetCommandParams p("bibitem", "dummy");
306                 auto_ptr<InsetBibitem> inset(new InsetBibitem(p));
307                 inset->read(buf, lex);
308                 par.insertInset(par.size(), inset.release(), font, change);
309         } else if (token == "\\hfill") {
310                 par.insertInset(par.size(), new InsetHFill, font, change);
311         } else if (token == "\\lyxline") {
312                 par.insertInset(par.size(), new InsetLine, font, change);
313         } else if (token == "\\newpage") {
314                 par.insertInset(par.size(), new InsetPagebreak, font, change);
315         } else if (token == "\\change_unchanged") {
316                 // Hack ! Needed for empty paragraphs :/
317                 // FIXME: is it still ??
318                 if (!par.size())
319                         par.cleanChanges();
320                 change = Change(Change::UNCHANGED);
321         } else if (token == "\\change_inserted") {
322                 lex.eatLine();
323                 std::istringstream is(lex.getString());
324                 int aid;
325                 lyx::time_type ct;
326                 is >> aid >> ct;
327                 change = Change(Change::INSERTED, bp.author_map[aid], ct);
328         } else if (token == "\\change_deleted") {
329                 lex.eatLine();
330                 std::istringstream is(lex.getString());
331                 int aid;
332                 lyx::time_type ct;
333                 is >> aid >> ct;
334                 change = Change(Change::DELETED, bp.author_map[aid], ct);
335         } else {
336                 lex.eatLine();
337                 buf.error(ErrorItem(_("Unknown token"),
338                         bformat(_("Unknown token: %1$s %2$s\n"), token, lex.getString()),
339                         par.id(), 0, par.size()));
340         }
341 }
342
343
344 void readParagraph(Buffer const & buf, Paragraph & par, LyXLex & lex)
345 {
346         lex.nextToken();
347         string token = lex.getString();
348         LyXFont font;
349         Change change;
350
351         while (lex.isOK()) {
352
353                 readParToken(buf, par, lex, token, font, change);
354
355                 lex.nextToken();
356                 token = lex.getString();
357
358                 if (token.empty())
359                         continue;
360
361                 if (token == "\\end_layout") {
362                         //Ok, paragraph finished
363                         break;
364                 }
365
366                 lyxerr[Debug::PARSER] << "Handling paragraph token: `"
367                                       << token << '\'' << endl;
368                 if (token == "\\begin_layout" || token == "\\end_document"
369                     || token == "\\end_inset" || token == "\\begin_deeper"
370                     || token == "\\end_deeper") {
371                         lex.pushToken(token);
372                         lyxerr << "Paragraph ended in line "
373                                << lex.getLineNo() << "\n"
374                                << "Missing \\end_layout.\n";
375                         break;
376                 }
377         }
378         // Initialize begin_of_body_ on load; redoParagraph maintains
379         par.setBeginOfBody();
380 }
381
382
383 } // namespace anon
384
385
386
387 BufferView * LyXText::bv() const
388 {
389         BOOST_ASSERT(bv_owner != 0);
390         return bv_owner;
391 }
392
393
394 double LyXText::spacing(Paragraph const & par) const
395 {
396         if (par.params().spacing().isDefault())
397                 return bv()->buffer()->params().spacing().getValue();
398         return par.params().spacing().getValue();
399 }
400
401
402 int LyXText::width() const
403 {
404         return dim_.wid;
405 }
406
407
408 int LyXText::height() const
409 {
410         return dim_.height();
411 }
412
413
414 int LyXText::singleWidth(Paragraph const & par, pos_type pos) const
415 {
416         return singleWidth(par, pos, par.getChar(pos), getFont(par, pos));
417 }
418
419
420 int LyXText::singleWidth(Paragraph const & par,
421                          pos_type pos, char c, LyXFont const & font) const
422 {
423         // The most common case is handled first (Asger)
424         if (IsPrintable(c)) {
425                 Language const * language = font.language();
426                 if (language->RightToLeft()) {
427                         if ((lyxrc.font_norm_type == LyXRC::ISO_8859_6_8 ||
428                              lyxrc.font_norm_type == LyXRC::ISO_10646_1)
429                             && language->lang() == "arabic") {
430                                 if (Encodings::IsComposeChar_arabic(c))
431                                         return 0;
432                                 c = par.transformChar(c, pos);
433                         } else if (language->lang() == "hebrew" &&
434                                    Encodings::IsComposeChar_hebrew(c))
435                                 return 0;
436                 }
437                 return font_metrics::width(c, font);
438         }
439
440         if (c == Paragraph::META_INSET)
441                 return par.getInset(pos)->width();
442
443         return font_metrics::width(c, font);
444 }
445
446
447 int LyXText::leftMargin(pit_type pit) const
448 {
449         BOOST_ASSERT(pit >= 0);
450         BOOST_ASSERT(pit < int(pars_.size()));
451         return leftMargin(pit, pars_[pit].size());
452 }
453
454
455 int LyXText::leftMargin(pit_type const pit, pos_type const pos) const
456 {
457         BOOST_ASSERT(pit >= 0);
458         BOOST_ASSERT(pit < int(pars_.size()));
459         Paragraph const & par = pars_[pit];
460         BOOST_ASSERT(pos >= 0);
461         BOOST_ASSERT(pos <= par.size());
462         //lyxerr << "LyXText::leftMargin: pit: " << pit << " pos: " << pos << endl;
463         LyXTextClass const & tclass =
464                 bv()->buffer()->params().getLyXTextClass();
465         LyXLayout_ptr const & layout = par.layout();
466
467         string parindent = layout->parindent;
468
469         int l_margin = 0;
470
471         if (isMainText())
472                 l_margin += changebarMargin();
473
474         l_margin += font_metrics::signedWidth(tclass.leftmargin(), tclass.defaultfont());
475
476         if (par.getDepth() != 0) {
477         // find the next level paragraph
478         pit_type newpar = outerHook(pit, pars_);
479                 if (newpar != pit_type(pars_.size())) {
480                         if (pars_[newpar].layout()->isEnvironment()) {
481                                 l_margin = leftMargin(newpar);
482                         }
483                         if (par.layout() == tclass.defaultLayout()) {
484                                 if (pars_[newpar].params().noindent())
485                                         parindent.erase();
486                                 else
487                                         parindent = pars_[newpar].layout()->parindent;
488                         }
489                 }
490         }
491
492         LyXFont const labelfont = getLabelFont(par);
493         switch (layout->margintype) {
494         case MARGIN_DYNAMIC:
495                 if (!layout->leftmargin.empty())
496                         l_margin += font_metrics::signedWidth(layout->leftmargin,
497                                                   tclass.defaultfont());
498                 if (!par.getLabelstring().empty()) {
499                         l_margin += font_metrics::signedWidth(layout->labelindent,
500                                                   labelfont);
501                         l_margin += font_metrics::width(par.getLabelstring(),
502                                             labelfont);
503                         l_margin += font_metrics::width(layout->labelsep, labelfont);
504                 }
505                 break;
506
507         case MARGIN_MANUAL:
508                 l_margin += font_metrics::signedWidth(layout->labelindent, labelfont);
509                 // The width of an empty par, even with manual label, should be 0
510                 if (!par.empty() && pos >= par.beginOfBody()) {
511                         if (!par.getLabelWidthString().empty()) {
512                                 l_margin += font_metrics::width(par.getLabelWidthString(),
513                                                labelfont);
514                                 l_margin += font_metrics::width(layout->labelsep, labelfont);
515                         }
516                 }
517                 break;
518
519         case MARGIN_STATIC:
520                 l_margin += font_metrics::signedWidth(layout->leftmargin, tclass.defaultfont()) * 4
521                         / (par.getDepth() + 4);
522                 break;
523
524         case MARGIN_FIRST_DYNAMIC:
525                 if (layout->labeltype == LABEL_MANUAL) {
526                         if (pos >= par.beginOfBody()) {
527                                 l_margin += font_metrics::signedWidth(layout->leftmargin,
528                                                           labelfont);
529                         } else {
530                                 l_margin += font_metrics::signedWidth(layout->labelindent,
531                                                           labelfont);
532                         }
533                 } else if (pos != 0
534                            // Special case to fix problems with
535                            // theorems (JMarc)
536                            || (layout->labeltype == LABEL_STATIC
537                                && layout->latextype == LATEX_ENVIRONMENT
538                                && !isFirstInSequence(pit, pars_))) {
539                         l_margin += font_metrics::signedWidth(layout->leftmargin,
540                                                   labelfont);
541                 } else if (layout->labeltype != LABEL_TOP_ENVIRONMENT
542                            && layout->labeltype != LABEL_BIBLIO
543                            && layout->labeltype !=
544                            LABEL_CENTERED_TOP_ENVIRONMENT) {
545                         l_margin += font_metrics::signedWidth(layout->labelindent,
546                                                   labelfont);
547                         l_margin += font_metrics::width(layout->labelsep, labelfont);
548                         l_margin += font_metrics::width(par.getLabelstring(),
549                                             labelfont);
550                 }
551                 break;
552
553         case MARGIN_RIGHT_ADDRESS_BOX: {
554 #if 0
555                 // ok, a terrible hack. The left margin depends on the widest
556                 // row in this paragraph.
557                 RowList::iterator rit = par.rows().begin();
558                 RowList::iterator end = par.rows().end();
559 #ifdef WITH_WARNINGS
560 #warning This is wrong.
561 #endif
562                 int minfill = maxwidth_;
563                 for ( ; rit != end; ++rit)
564                         if (rit->fill() < minfill)
565                                 minfill = rit->fill();
566                 l_margin += font_metrics::signedWidth(layout->leftmargin,
567                         tclass.defaultfont());
568                 l_margin += minfill;
569 #endif
570                 // also wrong, but much shorter.
571                 l_margin += maxwidth_ / 2;
572                 break;
573         }
574         }
575
576         if (!par.params().leftIndent().zero())
577                 l_margin += par.params().leftIndent().inPixels(maxwidth_);
578
579         LyXAlignment align;
580
581         if (par.params().align() == LYX_ALIGN_LAYOUT)
582                 align = layout->align;
583         else
584                 align = par.params().align();
585
586         // set the correct parindent
587         if (pos == 0
588             && (layout->labeltype == LABEL_NO_LABEL
589                || layout->labeltype == LABEL_TOP_ENVIRONMENT
590                || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
591                || (layout->labeltype == LABEL_STATIC
592                    && layout->latextype == LATEX_ENVIRONMENT
593                    && !isFirstInSequence(pit, pars_)))
594             && align == LYX_ALIGN_BLOCK
595             && !par.params().noindent()
596             // in some insets, paragraphs are never indented
597             && !(par.inInset() && par.inInset()->neverIndent())
598             // display style insets are always centered, omit indentation
599             && !(!par.empty()
600                     && par.isInset(pos)
601                     && par.getInset(pos)->display())
602             && (par.layout() != tclass.defaultLayout()
603                 || bv()->buffer()->params().paragraph_separation ==
604                    BufferParams::PARSEP_INDENT))
605         {
606                 l_margin += font_metrics::signedWidth(parindent, tclass.defaultfont());
607         }
608
609         return l_margin;
610 }
611
612
613 int LyXText::rightMargin(Paragraph const & par) const
614 {
615         // We do not want rightmargins on inner texts.
616         if (bv()->text() != this)
617                 return 0;
618
619         LyXTextClass const & tclass = bv()->buffer()->params().getLyXTextClass();
620         int const r_margin =
621                 ::rightMargin()
622                 + font_metrics::signedWidth(tclass.rightmargin(),
623                                             tclass.defaultfont())
624                 + font_metrics::signedWidth(par.layout()->rightmargin,
625                                             tclass.defaultfont())
626                 * 4 / (par.getDepth() + 4);
627
628         return r_margin;
629 }
630
631
632 int LyXText::labelEnd(pit_type const pit) const
633 {
634         // labelEnd is only needed if the layout fills a flushleft label.
635         if (pars_[pit].layout()->margintype != MARGIN_MANUAL)
636                 return 0;
637         // return the beginning of the body
638         return leftMargin(pit);
639 }
640
641
642 namespace {
643
644 // this needs special handling - only newlines count as a break point
645 pos_type addressBreakPoint(pos_type i, Paragraph const & par)
646 {
647         pos_type const end = par.size();
648
649         for (; i < end; ++i)
650                 if (par.isNewline(i))
651                         return i + 1;
652
653         return end;
654 }
655
656 };
657
658
659 void LyXText::rowBreakPoint(pit_type const pit, Row & row) const
660 {
661         Paragraph const & par = pars_[pit];
662         pos_type const end = par.size();
663         pos_type const pos = row.pos();
664         if (pos == end) {
665                 row.endpos(end);
666                 return;
667         }
668
669         // maximum pixel width of a row
670         int width = maxwidth_ - rightMargin(par); // - leftMargin(pit, row);
671         if (width < 0) {
672                 row.endpos(end);
673                 return;
674         }
675
676         LyXLayout_ptr const & layout = par.layout();
677
678         if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX) {
679                 row.endpos(addressBreakPoint(pos, par));
680                 return;
681         }
682
683         pos_type const body_pos = par.beginOfBody();
684
685
686         // Now we iterate through until we reach the right margin
687         // or the end of the par, then choose the possible break
688         // nearest that.
689
690         int const left = leftMargin(pit, pos);
691         int x = left;
692
693         // pixel width since last breakpoint
694         int chunkwidth = 0;
695
696         FontIterator fi = FontIterator(*this, par, pos);
697         pos_type point = end;
698         pos_type i = pos;
699         for ( ; i < end; ++i, ++fi) {
700                 char const c = par.getChar(i);
701                 int thiswidth = singleWidth(par, i, c, *fi);
702
703                 // add the auto-hfill from label end to the body
704                 if (body_pos && i == body_pos) {
705                         int add = font_metrics::width(layout->labelsep, getLabelFont(par));
706                         if (par.isLineSeparator(i - 1))
707                                 add -= singleWidth(par, i - 1);
708
709                         add = std::max(add, labelEnd(pit) - x);
710                         thiswidth += add;
711                 }
712
713                 x += thiswidth;
714                 chunkwidth += thiswidth;
715
716                 // break before a character that will fall off
717                 // the right of the row
718                 if (x >= width) {
719                         // if no break before, break here
720                         if (point == end || chunkwidth >= width - left) {
721                                 if (i > pos)
722                                         point = i;
723                                 else
724                                         point = i + 1;
725
726                         }
727                         // exit on last registered breakpoint:
728                         break;
729                 }
730
731                 if (par.isNewline(i)) {
732                         point = i + 1;
733                         break;
734                 }
735                 // Break before...
736                 if (i + 1 < end) {
737                         if (par.isInset(i + 1) && par.getInset(i + 1)->display()) {
738                                 point = i + 1;
739                                 break;
740                         }
741                         // ...and after.
742                         if (par.isInset(i) && par.getInset(i)->display()) {
743                                 point = i + 1;
744                                 break;
745                         }
746                 }
747
748                 if (!par.isInset(i) || par.getInset(i)->isChar()) {
749                         // some insets are line separators too
750                         if (par.isLineSeparator(i)) {
751                                 // register breakpoint:
752                                 point = i + 1;
753                                 chunkwidth = 0;
754                         }
755                 }
756         }
757
758         // maybe found one, but the par is short enough.
759         if (i == end && x < width)
760                 point = end;
761
762         // manual labels cannot be broken in LaTeX. But we
763         // want to make our on-screen rendering of footnotes
764         // etc. still break
765         if (body_pos && point < body_pos)
766                 point = body_pos;
767
768         row.endpos(point);
769 }
770
771
772 void LyXText::setRowWidth(pit_type const pit, Row & row) const
773 {
774         // get the pure distance
775         pos_type const end = row.endpos();
776
777         Paragraph const & par = pars_[pit];
778         string const & labelsep = par.layout()->labelsep;
779         int w = leftMargin(pit, row.pos());
780
781         pos_type const body_pos = par.beginOfBody();
782         pos_type i = row.pos();
783
784         if (i < end) {
785                 FontIterator fi = FontIterator(*this, par, i);
786                 for ( ; i < end; ++i, ++fi) {
787                         if (body_pos > 0 && i == body_pos) {
788                                 w += font_metrics::width(labelsep, getLabelFont(par));
789                                 if (par.isLineSeparator(i - 1))
790                                         w -= singleWidth(par, i - 1);
791                                 w = max(w, labelEnd(pit));
792                         }
793                         char const c = par.getChar(i);
794                         w += singleWidth(par, i, c, *fi);
795                 }
796         }
797
798         if (body_pos > 0 && body_pos >= end) {
799                 w += font_metrics::width(labelsep, getLabelFont(par));
800                 if (end > 0 && par.isLineSeparator(end - 1))
801                         w -= singleWidth(par, end - 1);
802                 w = max(w, labelEnd(pit));
803         }
804
805         row.width(w + rightMargin(par));
806 }
807
808
809 // returns the minimum space a manual label needs on the screen in pixel
810 int LyXText::labelFill(Paragraph const & par, Row const & row) const
811 {
812         pos_type last = par.beginOfBody();
813
814         BOOST_ASSERT(last > 0);
815
816         // -1 because a label ends with a space that is in the label
817         --last;
818
819         // a separator at this end does not count
820         if (par.isLineSeparator(last))
821                 --last;
822
823         int w = 0;
824         for (pos_type i = row.pos(); i <= last; ++i)
825                 w += singleWidth(par, i);
826
827         string const & label = par.params().labelWidthString();
828         if (label.empty())
829                 return 0;
830
831         return max(0, font_metrics::width(label, getLabelFont(par)) - w);
832 }
833
834
835 LColor_color LyXText::backgroundColor() const
836 {
837         return LColor_color(LColor::color(background_color_));
838 }
839
840
841 void LyXText::setHeightOfRow(pit_type const pit, Row & row)
842 {
843         Paragraph const & par = pars_[pit];
844         // get the maximum ascent and the maximum descent
845         double layoutasc = 0;
846         double layoutdesc = 0;
847         double const dh = defaultRowHeight();
848
849         // ok, let us initialize the maxasc and maxdesc value.
850         // Only the fontsize count. The other properties
851         // are taken from the layoutfont. Nicer on the screen :)
852         LyXLayout_ptr const & layout = par.layout();
853
854         // as max get the first character of this row then it can
855         // increase but not decrease the height. Just some point to
856         // start with so we don't have to do the assignment below too
857         // often.
858         LyXFont font = getFont(par, row.pos());
859         LyXFont::FONT_SIZE const tmpsize = font.size();
860         font = getLayoutFont(pit);
861         LyXFont::FONT_SIZE const size = font.size();
862         font.setSize(tmpsize);
863
864         LyXFont labelfont = getLabelFont(par);
865
866         // these are minimum values
867         double const spacing_val = layout->spacing.getValue() * spacing(par);
868         //lyxerr << "spacing_val = " << spacing_val << endl;
869         int maxasc  = int(font_metrics::maxAscent(font)  * spacing_val);
870         int maxdesc = int(font_metrics::maxDescent(font) * spacing_val);
871
872         // insets may be taller
873         InsetList::const_iterator ii = par.insetlist.begin();
874         InsetList::const_iterator iend = par.insetlist.end();
875         for ( ; ii != iend; ++ii) {
876                 if (ii->pos >= row.pos() && ii->pos < row.endpos()) {
877                         maxasc  = max(maxasc,  ii->inset->ascent());
878                         maxdesc = max(maxdesc, ii->inset->descent());
879                 }
880         }
881
882         // Check if any custom fonts are larger (Asger)
883         // This is not completely correct, but we can live with the small,
884         // cosmetic error for now.
885         int labeladdon = 0;
886         pos_type const pos_end = row.endpos();
887
888         LyXFont::FONT_SIZE maxsize =
889                 par.highestFontInRange(row.pos(), pos_end, size);
890         if (maxsize > font.size()) {
891                 font.setSize(maxsize);
892                 maxasc  = max(maxasc,  font_metrics::maxAscent(font));
893                 maxdesc = max(maxdesc, font_metrics::maxDescent(font));
894         }
895
896         // This is nicer with box insets:
897         ++maxasc;
898         ++maxdesc;
899
900         row.ascent(maxasc);
901
902         // is it a top line?
903         if (row.pos() == 0) {
904                 BufferParams const & bufparams = bv()->buffer()->params();
905                 // some parksips VERY EASY IMPLEMENTATION
906                 if (bv()->buffer()->params().paragraph_separation
907                     == BufferParams::PARSEP_SKIP
908                         && pit != 0
909                         && ((layout->isParagraph() && par.getDepth() == 0)
910                             || (pars_[pit - 1].layout()->isParagraph()
911                                 && pars_[pit - 1].getDepth() == 0)))
912                 {
913                                 maxasc += bufparams.getDefSkip().inPixels(*bv());
914                 }
915
916                 if (par.params().startOfAppendix())
917                         maxasc += int(3 * dh);
918
919                 // This is special code for the chapter, since the label of this
920                 // layout is printed in an extra row
921                 if (layout->counter == "chapter"
922                     && !par.params().labelString().empty()) {
923                         labeladdon = int(font_metrics::maxHeight(labelfont)
924                                      * layout->spacing.getValue()
925                                      * spacing(par));
926                 }
927
928                 // special code for the top label
929                 if ((layout->labeltype == LABEL_TOP_ENVIRONMENT
930                      || layout->labeltype == LABEL_BIBLIO
931                      || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
932                     && isFirstInSequence(pit, paragraphs())
933                     && !par.getLabelstring().empty())
934                 {
935                         labeladdon = int(
936                                   font_metrics::maxHeight(labelfont)
937                                         * layout->spacing.getValue()
938                                         * spacing(par)
939                                 + (layout->topsep + layout->labelbottomsep) * dh);
940                 }
941
942                 // Add the layout spaces, for example before and after
943                 // a section, or between the items of a itemize or enumerate
944                 // environment.
945
946                 pit_type prev = depthHook(pit, pars_, par.getDepth());
947                 if (prev != pit
948                     && pars_[prev].layout() == layout
949                     && pars_[prev].getDepth() == par.getDepth()
950                     && pars_[prev].getLabelWidthString() == par.getLabelWidthString())
951                 {
952                         layoutasc = layout->itemsep * dh;
953                 } else if (pit != 0 || row.pos() != 0) {
954                         if (layout->topsep > 0)
955                                 layoutasc = layout->topsep * dh;
956                 }
957
958                 prev = outerHook(pit, pars_);
959                 if (prev != pit_type(pars_.size())) {
960                         maxasc += int(pars_[prev].layout()->parsep * dh);
961                 } else if (pit != 0) {
962                         if (pars_[pit - 1].getDepth() != 0 ||
963                                         pars_[pit - 1].layout() == layout) {
964                                 maxasc += int(layout->parsep * dh);
965                         }
966                 }
967         }
968
969         // is it a bottom line?
970         if (row.endpos() >= par.size()) {
971                 // add the layout spaces, for example before and after
972                 // a section, or between the items of a itemize or enumerate
973                 // environment
974                 pit_type nextpit = pit + 1;
975                 if (nextpit != pit_type(pars_.size())) {
976                         pit_type cpit = pit;
977                         double usual = 0;
978                         double unusual = 0;
979
980                         if (pars_[cpit].getDepth() > pars_[nextpit].getDepth()) {
981                                 usual = pars_[cpit].layout()->bottomsep * dh;
982                                 cpit = depthHook(cpit, paragraphs(), pars_[nextpit].getDepth());
983                                 if (pars_[cpit].layout() != pars_[nextpit].layout()
984                                         || pars_[nextpit].getLabelWidthString() != pars_[cpit].getLabelWidthString())
985                                 {
986                                         unusual = pars_[cpit].layout()->bottomsep * dh;
987                                 }
988                                 layoutdesc = max(unusual, usual);
989                         } else if (pars_[cpit].getDepth() == pars_[nextpit].getDepth()) {
990                                 if (pars_[cpit].layout() != pars_[nextpit].layout()
991                                         || pars_[nextpit].getLabelWidthString() != pars_[cpit].getLabelWidthString())
992                                         layoutdesc = int(pars_[cpit].layout()->bottomsep * dh);
993                         }
994                 }
995         }
996
997         // incalculate the layout spaces
998         maxasc  += int(layoutasc  * 2 / (2 + pars_[pit].getDepth()));
999         maxdesc += int(layoutdesc * 2 / (2 + pars_[pit].getDepth()));
1000
1001         // Top and bottom margin of the document (only at top-level)
1002         if (bv_owner->text() == this) {
1003                 if (pit == 0 && row.pos() == 0)
1004                         maxasc += 20;
1005                 if (pit + 1 == pars_.size() && row.endpos() == par.size())
1006                         maxdesc += 20;
1007         }
1008
1009         row.ascent(maxasc + labeladdon);
1010         row.descent(maxdesc);
1011 }
1012
1013
1014 namespace {
1015
1016 }
1017
1018 void LyXText::breakParagraph(LCursor & cur, bool keep_layout)
1019 {
1020         BOOST_ASSERT(this == cur.text());
1021         // allow only if at start or end, or all previous is new text
1022         Paragraph & cpar = cur.paragraph();
1023         pit_type cpit = cur.pit();
1024
1025         if (cur.pos() != 0 && cur.pos() != cur.lastpos()
1026             && cpar.isChangeEdited(0, cur.pos()))
1027                 return;
1028
1029         LyXTextClass const & tclass = cur.buffer().params().getLyXTextClass();
1030         LyXLayout_ptr const & layout = cpar.layout();
1031
1032         // this is only allowed, if the current paragraph is not empty
1033         // or caption and if it has not the keepempty flag active
1034         if (cur.lastpos() == 0 && !cpar.allowEmpty()
1035            && layout->labeltype != LABEL_SENSITIVE)
1036                 return;
1037
1038         // a layout change may affect also the following paragraph
1039         recUndo(cur.pit(), undoSpan(cur.pit()) - 1);
1040
1041         // Always break behind a space
1042         // It is better to erase the space (Dekel)
1043         if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
1044                 cpar.erase(cur.pos());
1045
1046         // How should the layout for the new paragraph be?
1047         int preserve_layout = 0;
1048         if (keep_layout)
1049                 preserve_layout = 2;
1050         else
1051                 preserve_layout = layout->isEnvironment();
1052
1053         // We need to remember this before we break the paragraph, because
1054         // that invalidates the layout variable
1055         bool sensitive = layout->labeltype == LABEL_SENSITIVE;
1056
1057         // we need to set this before we insert the paragraph.
1058         bool const isempty = cpar.allowEmpty() && cpar.empty();
1059
1060         ::breakParagraph(cur.buffer().params(), paragraphs(), cpit,
1061                          cur.pos(), preserve_layout);
1062
1063         // After this, neither paragraph contains any rows!
1064
1065         cpit = cur.pit();
1066         pit_type next_par = cpit + 1;
1067
1068         // well this is the caption hack since one caption is really enough
1069         if (sensitive) {
1070                 if (cur.pos() == 0)
1071                         // set to standard-layout
1072                         pars_[cpit].applyLayout(tclass.defaultLayout());
1073                 else
1074                         // set to standard-layout
1075                         pars_[next_par].applyLayout(tclass.defaultLayout());
1076         }
1077
1078         while (!pars_[next_par].empty() && pars_[next_par].isNewline(0))
1079                 pars_[next_par].erase(0);
1080
1081         updateCounters(cur.buffer());
1082
1083         // This check is necessary. Otherwise the new empty paragraph will
1084         // be deleted automatically. And it is more friendly for the user!
1085         if (cur.pos() != 0 || isempty)
1086                 setCursor(cur, cur.pit() + 1, 0);
1087         else
1088                 setCursor(cur, cur.pit(), 0);
1089 }
1090
1091
1092 // insert a character, moves all the following breaks in the
1093 // same Paragraph one to the right and make a rebreak
1094 void LyXText::insertChar(LCursor & cur, char c)
1095 {
1096         BOOST_ASSERT(this == cur.text());
1097         BOOST_ASSERT(c != Paragraph::META_INSET);
1098
1099         recordUndo(cur, Undo::INSERT);
1100
1101         Paragraph & par = cur.paragraph();
1102         // try to remove this
1103         pit_type const pit = cur.pit();
1104
1105         bool const freeSpacing = par.layout()->free_spacing ||
1106                 par.isFreeSpacing();
1107
1108         if (lyxrc.auto_number) {
1109                 static string const number_operators = "+-/*";
1110                 static string const number_unary_operators = "+-";
1111                 static string const number_seperators = ".,:";
1112
1113                 if (current_font.number() == LyXFont::ON) {
1114                         if (!IsDigit(c) && !contains(number_operators, c) &&
1115                             !(contains(number_seperators, c) &&
1116                               cur.pos() != 0 &&
1117                               cur.pos() != cur.lastpos() &&
1118                               getFont(par, cur.pos()).number() == LyXFont::ON &&
1119                               getFont(par, cur.pos() - 1).number() == LyXFont::ON)
1120                            )
1121                                 number(cur); // Set current_font.number to OFF
1122                 } else if (IsDigit(c) &&
1123                            real_current_font.isVisibleRightToLeft()) {
1124                         number(cur); // Set current_font.number to ON
1125
1126                         if (cur.pos() != 0) {
1127                                 char const c = par.getChar(cur.pos() - 1);
1128                                 if (contains(number_unary_operators, c) &&
1129                                     (cur.pos() == 1
1130                                      || par.isSeparator(cur.pos() - 2)
1131                                      || par.isNewline(cur.pos() - 2))
1132                                   ) {
1133                                         setCharFont(pit, cur.pos() - 1, current_font);
1134                                 } else if (contains(number_seperators, c)
1135                                      && cur.pos() >= 2
1136                                      && getFont(par, cur.pos() - 2).number() == LyXFont::ON) {
1137                                         setCharFont(pit, cur.pos() - 1, current_font);
1138                                 }
1139                         }
1140                 }
1141         }
1142
1143         // First check, if there will be two blanks together or a blank at
1144         // the beginning of a paragraph.
1145         // I decided to handle blanks like normal characters, the main
1146         // difference are the special checks when calculating the row.fill
1147         // (blank does not count at the end of a row) and the check here
1148
1149         // The bug is triggered when we type in a description environment:
1150         // The current_font is not changed when we go from label to main text
1151         // and it should (along with realtmpfont) when we type the space.
1152         // CHECK There is a bug here! (Asger)
1153
1154         // store the current font.  This is because of the use of cursor
1155         // movements. The moving cursor would refresh the current font
1156         LyXFont realtmpfont = real_current_font;
1157         LyXFont rawtmpfont = current_font;
1158
1159         // When the free-spacing option is set for the current layout,
1160         // disable the double-space checking
1161         if (!freeSpacing && IsLineSeparatorChar(c)) {
1162                 if (cur.pos() == 0) {
1163                         static bool sent_space_message = false;
1164                         if (!sent_space_message) {
1165                                 cur.message(_("You cannot insert a space at the "
1166                                         "beginning of a paragraph. Please read the Tutorial."));
1167                                 sent_space_message = true;
1168                         }
1169                         return;
1170                 }
1171                 BOOST_ASSERT(cur.pos() > 0);
1172                 if ((par.isLineSeparator(cur.pos() - 1)
1173                     || par.isNewline(cur.pos() - 1))
1174                     && par.lookupChange(cur.pos() - 1) != Change::DELETED) {
1175                         static bool sent_space_message = false;
1176                         if (!sent_space_message) {
1177                                 cur.message(_("You cannot type two spaces this way. "
1178                                         "Please read the Tutorial."));
1179                                 sent_space_message = true;
1180                         }
1181                         return;
1182                 }
1183         }
1184
1185         par.insertChar(cur.pos(), c, rawtmpfont);
1186
1187         current_font = rawtmpfont;
1188         real_current_font = realtmpfont;
1189         //setCursor(cur, cur.pit(), cur.pos() + 1, false, cur.boundary());
1190         setCursor(cur, cur.pit(), cur.pos() + 1, false, true);
1191         charInserted();
1192 }
1193
1194
1195 void LyXText::charInserted()
1196 {
1197         // Here we call finishUndo for every 20 characters inserted.
1198         // This is from my experience how emacs does it. (Lgb)
1199         static unsigned int counter;
1200         if (counter < 20) {
1201                 ++counter;
1202         } else {
1203                 finishUndo();
1204                 counter = 0;
1205         }
1206 }
1207
1208
1209 RowMetrics
1210 LyXText::computeRowMetrics(pit_type const pit, Row const & row) const
1211 {
1212         RowMetrics result;
1213         Paragraph const & par = pars_[pit];
1214
1215         double w = dim_.wid - row.width();
1216
1217         bool const is_rtl = isRTL(par);
1218         if (is_rtl)
1219                 result.x = rightMargin(par);
1220         else
1221                 result.x = leftMargin(pit, row.pos());
1222
1223         // is there a manual margin with a manual label
1224         LyXLayout_ptr const & layout = par.layout();
1225
1226         if (layout->margintype == MARGIN_MANUAL
1227             && layout->labeltype == LABEL_MANUAL) {
1228                 /// We might have real hfills in the label part
1229                 int nlh = numberOfLabelHfills(par, row);
1230
1231                 // A manual label par (e.g. List) has an auto-hfill
1232                 // between the label text and the body of the
1233                 // paragraph too.
1234                 // But we don't want to do this auto hfill if the par
1235                 // is empty.
1236                 if (!par.empty())
1237                         ++nlh;
1238
1239                 if (nlh && !par.getLabelWidthString().empty())
1240                         result.label_hfill = labelFill(par, row) / double(nlh);
1241         }
1242
1243         // are there any hfills in the row?
1244         int const nh = numberOfHfills(par, row);
1245
1246         if (nh) {
1247                 if (w > 0)
1248                         result.hfill = w / nh;
1249         // we don't have to look at the alignment if it is ALIGN_LEFT and
1250         // if the row is already larger then the permitted width as then
1251         // we force the LEFT_ALIGN'edness!
1252         } else if (int(row.width()) < maxwidth_) {
1253                 // is it block, flushleft or flushright?
1254                 // set x how you need it
1255                 int align;
1256                 if (par.params().align() == LYX_ALIGN_LAYOUT)
1257                         align = layout->align;
1258                 else
1259                         align = par.params().align();
1260
1261                 // Display-style insets should always be on a centred row
1262                 // The test on par.size() is to catch zero-size pars, which
1263                 // would trigger the assert in Paragraph::getInset().
1264                 //inset = par.size() ? par.getInset(row.pos()) : 0;
1265                 if (!par.empty()
1266                     && par.isInset(row.pos())
1267                     && par.getInset(row.pos())->display())
1268                 {
1269                         align = LYX_ALIGN_CENTER;
1270                 }
1271
1272                 switch (align) {
1273                 case LYX_ALIGN_BLOCK: {
1274                         int const ns = numberOfSeparators(par, row);
1275                         bool disp_inset = false;
1276                         if (row.endpos() < par.size()) {
1277                                 InsetBase const * in = par.getInset(row.endpos());
1278                                 if (in)
1279                                         disp_inset = in->display();
1280                         }
1281                         // If we have separators, this is not the last row of a
1282                         // par, does not end in newline, and is not row above a
1283                         // display inset... then stretch it
1284                         if (ns
1285                             && row.endpos() < par.size()
1286                             && !par.isNewline(row.endpos() - 1)
1287                             && !disp_inset
1288                                 ) {
1289                                 result.separator = w / ns;
1290                         } else if (is_rtl) {
1291                                 result.x += w;
1292                         }
1293                         break;
1294                 }
1295                 case LYX_ALIGN_RIGHT:
1296                         result.x += w;
1297                         break;
1298                 case LYX_ALIGN_CENTER:
1299                         result.x += w / 2;
1300                         break;
1301                 }
1302         }
1303
1304         bidi.computeTables(par, *bv()->buffer(), row);
1305         if (is_rtl) {
1306                 pos_type body_pos = par.beginOfBody();
1307                 pos_type end = row.endpos();
1308
1309                 if (body_pos > 0
1310                     && (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1311                 {
1312                         result.x += font_metrics::width(layout->labelsep, getLabelFont(par));
1313                         if (body_pos <= end)
1314                                 result.x += result.label_hfill;
1315                 }
1316         }
1317
1318         return result;
1319 }
1320
1321
1322 // the cursor set functions have a special mechanism. When they
1323 // realize, that you left an empty paragraph, they will delete it.
1324
1325 bool LyXText::cursorRightOneWord(LCursor & cur)
1326 {
1327         BOOST_ASSERT(this == cur.text());
1328
1329         LCursor old = cur;
1330
1331         if (old.pos() == old.lastpos() && old.pit() != old.lastpit()) {
1332                 ++old.pit();
1333                 old.pos() = 0;
1334         } else {
1335                 // Skip through initial nonword stuff.
1336                 // Treat floats and insets as words.
1337                 while (old.pos() != old.lastpos() && !old.paragraph().isLetter(old.pos()))
1338                         ++old.pos();
1339                 // Advance through word.
1340                 while (old.pos() != old.lastpos() && old.paragraph().isLetter(old.pos()))
1341                         ++old.pos();
1342         }
1343         return setCursor(cur, old.pit(), old.pos());
1344 }
1345
1346
1347 bool LyXText::cursorLeftOneWord(LCursor & cur)
1348 {
1349         BOOST_ASSERT(this == cur.text());
1350
1351         LCursor old = cur;
1352
1353         if (old.pos() == 0 && old.pit() != 0) {
1354                 --old.pit();
1355                 old.pos() = old.lastpos();
1356         } else {
1357                 // Skip through initial nonword stuff.
1358                 // Treat floats and insets as words.
1359                 while (old.pos() != 0 && !old.paragraph().isLetter(old.pos() - 1))
1360                         --old.pos();
1361                 // Advance through word.
1362                 while (old.pos() != 0 && old.paragraph().isLetter(old.pos() - 1))
1363                         --old.pos();
1364         }
1365         return setCursor(cur, old.pit(), old.pos());
1366 }
1367
1368
1369 void LyXText::selectWord(LCursor & cur, word_location loc)
1370 {
1371         BOOST_ASSERT(this == cur.text());
1372         CursorSlice from = cur.top();
1373         CursorSlice to = cur.top();
1374         getWord(from, to, loc);
1375         if (cur.top() != from)
1376                 setCursor(cur, from.pit(), from.pos());
1377         if (to == from)
1378                 return;
1379         cur.resetAnchor();
1380         setCursor(cur, to.pit(), to.pos());
1381         cur.setSelection();
1382 }
1383
1384
1385 // Select the word currently under the cursor when no
1386 // selection is currently set
1387 bool LyXText::selectWordWhenUnderCursor(LCursor & cur, word_location loc)
1388 {
1389         BOOST_ASSERT(this == cur.text());
1390         if (cur.selection())
1391                 return false;
1392         selectWord(cur, loc);
1393         return cur.selection();
1394 }
1395
1396
1397 void LyXText::acceptChange(LCursor & cur)
1398 {
1399         BOOST_ASSERT(this == cur.text());
1400         if (!cur.selection() && cur.lastpos() != 0)
1401                 return;
1402
1403         CursorSlice const & startc = cur.selBegin();
1404         CursorSlice const & endc = cur.selEnd();
1405         if (startc.pit() == endc.pit()) {
1406                 recordUndoSelection(cur, Undo::INSERT);
1407                 pars_[startc.pit()].acceptChange(startc.pos(), endc.pos());
1408                 finishUndo();
1409                 cur.clearSelection();
1410                 setCursorIntern(cur, startc.pit(), 0);
1411         }
1412 #ifdef WITH_WARNINGS
1413 #warning handle multi par selection
1414 #endif
1415 }
1416
1417
1418 void LyXText::rejectChange(LCursor & cur)
1419 {
1420         BOOST_ASSERT(this == cur.text());
1421         if (!cur.selection() && cur.lastpos() != 0)
1422                 return;
1423
1424         CursorSlice const & startc = cur.selBegin();
1425         CursorSlice const & endc = cur.selEnd();
1426         if (startc.pit() == endc.pit()) {
1427                 recordUndoSelection(cur, Undo::INSERT);
1428                 pars_[startc.pit()].rejectChange(startc.pos(), endc.pos());
1429                 finishUndo();
1430                 cur.clearSelection();
1431                 setCursorIntern(cur, startc.pit(), 0);
1432         }
1433 #ifdef WITH_WARNINGS
1434 #warning handle multi par selection
1435 #endif
1436 }
1437
1438
1439 // Delete from cursor up to the end of the current or next word.
1440 void LyXText::deleteWordForward(LCursor & cur)
1441 {
1442         BOOST_ASSERT(this == cur.text());
1443         if (cur.lastpos() == 0)
1444                 cursorRight(cur);
1445         else {
1446                 cur.resetAnchor();
1447                 cur.selection() = true;
1448                 cursorRightOneWord(cur);
1449                 cur.setSelection();
1450                 cutSelection(cur, true, false);
1451         }
1452 }
1453
1454
1455 // Delete from cursor to start of current or prior word.
1456 void LyXText::deleteWordBackward(LCursor & cur)
1457 {
1458         BOOST_ASSERT(this == cur.text());
1459         if (cur.lastpos() == 0)
1460                 cursorLeft(cur);
1461         else {
1462                 cur.resetAnchor();
1463                 cur.selection() = true;
1464                 cursorLeftOneWord(cur);
1465                 cur.setSelection();
1466                 cutSelection(cur, true, false);
1467         }
1468 }
1469
1470
1471 // Kill to end of line.
1472 void LyXText::deleteLineForward(LCursor & cur)
1473 {
1474         BOOST_ASSERT(this == cur.text());
1475         if (cur.lastpos() == 0) {
1476                 // Paragraph is empty, so we just go to the right
1477                 cursorRight(cur);
1478         } else {
1479                 cur.resetAnchor();
1480                 cur.selection() = true; // to avoid deletion
1481                 cursorEnd(cur);
1482                 cur.setSelection();
1483                 // What is this test for ??? (JMarc)
1484                 if (!cur.selection())
1485                         deleteWordForward(cur);
1486                 else
1487                         cutSelection(cur, true, false);
1488         }
1489 }
1490
1491
1492 void LyXText::changeCase(LCursor & cur, LyXText::TextCase action)
1493 {
1494         BOOST_ASSERT(this == cur.text());
1495         CursorSlice from;
1496         CursorSlice to;
1497
1498         if (cur.selection()) {
1499                 from = cur.selBegin();
1500                 to = cur.selEnd();
1501         } else {
1502                 from = cur.top();
1503                 getWord(from, to, lyx::PARTIAL_WORD);
1504                 setCursor(cur, to.pit(), to.pos() + 1);
1505         }
1506
1507         recordUndoSelection(cur);
1508
1509         pos_type pos = from.pos();
1510         int par = from.pit();
1511
1512         while (par != int(pars_.size()) && (pos != to.pos() || par != to.pit())) {
1513                 pit_type pit = par;
1514                 if (pos == pars_[pit].size()) {
1515                         ++par;
1516                         pos = 0;
1517                         continue;
1518                 }
1519                 unsigned char c = pars_[pit].getChar(pos);
1520                 if (c != Paragraph::META_INSET) {
1521                         switch (action) {
1522                         case text_lowercase:
1523                                 c = lowercase(c);
1524                                 break;
1525                         case text_capitalization:
1526                                 c = uppercase(c);
1527                                 action = text_lowercase;
1528                                 break;
1529                         case text_uppercase:
1530                                 c = uppercase(c);
1531                                 break;
1532                         }
1533                 }
1534 #ifdef WITH_WARNINGS
1535 #warning changes
1536 #endif
1537                 pars_[pit].setChar(pos, c);
1538                 ++pos;
1539         }
1540 }
1541
1542
1543 void LyXText::Delete(LCursor & cur)
1544 {
1545         BOOST_ASSERT(this == cur.text());
1546
1547         if (cur.pos() != cur.lastpos()) {
1548                 recordUndo(cur, Undo::DELETE, cur.pit());
1549                 setCursorIntern(cur, cur.pit(), cur.pos() + 1, false, cur.boundary());
1550                 backspace(cur);
1551         } else if (cur.pit() != cur.lastpit()) {
1552                 LCursor scur = cur;
1553
1554                 setCursorIntern(cur, cur.pit()+1, 0, false, false);
1555                 if (pars_[cur.pit()].layout() == pars_[scur.pit()].layout()) {
1556                         recordUndo(scur, Undo::DELETE, scur.pit());
1557                         backspace(cur);
1558                 } else {
1559                         setCursorIntern(scur, scur.pit(), scur.pos(), false, scur.boundary());
1560                 }
1561         }
1562 }
1563
1564
1565 void LyXText::backspace(LCursor & cur)
1566 {
1567         BOOST_ASSERT(this == cur.text());
1568         if (cur.pos() == 0) {
1569                 // The cursor is at the beginning of a paragraph, so
1570                 // the the backspace will collapse two paragraphs into
1571                 // one.
1572
1573                 // but it's not allowed unless it's new
1574                 Paragraph & par = cur.paragraph();
1575                 if (par.isChangeEdited(0, par.size()))
1576                         return;
1577
1578                 // we may paste some paragraphs
1579
1580                 // is it an empty paragraph?
1581                 pos_type lastpos = cur.lastpos();
1582                 if (lastpos == 0 || (lastpos == 1 && par.isSeparator(0))) {
1583                         // This is an empty paragraph and we delete it just
1584                         // by moving the cursor one step
1585                         // left and let the DeleteEmptyParagraphMechanism
1586                         // handle the actual deletion of the paragraph.
1587
1588                         if (cur.pit() != 0) {
1589                                 // For KeepEmpty layouts we need to get
1590                                 // rid of the keepEmpty setting first.
1591                                 // And the only way to do this is to
1592                                 // reset the layout to something
1593                                 // else: f.ex. the default layout.
1594                                 if (par.allowEmpty()) {
1595                                         Buffer & buf = cur.buffer();
1596                                         BufferParams const & bparams = buf.params();
1597                                         par.layout(bparams.getLyXTextClass().defaultLayout());
1598                                 }
1599                                 
1600                                 cursorLeft(cur);
1601                                 return;
1602                         }
1603                 }
1604
1605                 if (cur.pit() != 0)
1606                         recordUndo(cur, Undo::DELETE, cur.pit() - 1);
1607
1608                 pit_type tmppit = cur.pit();
1609                 // We used to do cursorLeftIntern() here, but it is
1610                 // not a good idea since it triggers the auto-delete
1611                 // mechanism. So we do a cursorLeftIntern()-lite,
1612                 // without the dreaded mechanism. (JMarc)
1613                 if (cur.pit() != 0) {
1614                         // steps into the above paragraph.
1615                         setCursorIntern(cur, cur.pit() - 1,
1616                                         pars_[cur.pit() - 1].size(),
1617                                         false);
1618                 }
1619
1620                 // Pasting is not allowed, if the paragraphs have different
1621                 // layout. I think it is a real bug of all other
1622                 // word processors to allow it. It confuses the user.
1623                 // Correction: Pasting is always allowed with standard-layout
1624                 // Correction (Jug 20050717): Remove check about alignment!
1625                 Buffer & buf = cur.buffer();
1626                 BufferParams const & bufparams = buf.params();
1627                 LyXTextClass const & tclass = bufparams.getLyXTextClass();
1628                 pit_type const cpit = cur.pit();
1629
1630                 if (cpit != tmppit
1631                     && (pars_[cpit].layout() == pars_[tmppit].layout()
1632                         || pars_[tmppit].layout() == tclass.defaultLayout()))
1633                 {
1634                         mergeParagraph(bufparams, pars_, cpit);
1635
1636                         if (cur.pos() != 0 && pars_[cpit].isSeparator(cur.pos() - 1))
1637                                 --cur.pos();
1638
1639                         // the counters may have changed
1640                         updateCounters(cur.buffer());
1641                         setCursor(cur, cur.pit(), cur.pos(), false);
1642                 }
1643         } else {
1644                 // this is the code for a normal backspace, not pasting
1645                 // any paragraphs
1646                 recordUndo(cur, Undo::DELETE);
1647                 // We used to do cursorLeftIntern() here, but it is
1648                 // not a good idea since it triggers the auto-delete
1649                 // mechanism. So we do a cursorLeftIntern()-lite,
1650                 // without the dreaded mechanism. (JMarc)
1651                 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1652                                 false, cur.boundary());
1653                 cur.paragraph().erase(cur.pos());
1654         }
1655
1656         if (cur.pos() == cur.lastpos())
1657                 setCurrentFont(cur);
1658
1659         setCursor(cur, cur.pit(), cur.pos(), false, cur.boundary());
1660 }
1661
1662
1663 Row const & LyXText::firstRow() const
1664 {
1665         return *paragraphs().front().rows().begin();
1666 }
1667
1668
1669 bool LyXText::redoParagraph(pit_type const pit)
1670 {
1671         // remove rows of paragraph, keep track of height changes
1672         Paragraph & par = pars_[pit];
1673
1674         // Add bibitem insets if necessary
1675         if (par.layout()->labeltype == LABEL_BIBLIO) {
1676                 bool hasbibitem(false);
1677                 if (!par.insetlist.empty()
1678                         // Insist on it being in pos 0
1679                         && par.getChar(0) == Paragraph::META_INSET) {
1680                         InsetBase * inset = par.insetlist.begin()->inset;
1681                         if (inset->lyxCode() == InsetBase::BIBITEM_CODE)
1682                                 hasbibitem = true;
1683                 }
1684                 if (!hasbibitem) {
1685                         InsetBibitem * inset(new
1686                                 InsetBibitem(InsetCommandParams("bibitem")));
1687                         par.insertInset(0, static_cast<InsetBase *>(inset));
1688                         bv()->cursor().posRight();
1689                 }
1690         }
1691
1692         // redo insets
1693         InsetList::iterator ii = par.insetlist.begin();
1694         InsetList::iterator iend = par.insetlist.end();
1695         for (; ii != iend; ++ii) {
1696                 Dimension dim;
1697                 int const w = maxwidth_ - leftMargin(pit, ii->pos) - rightMargin(par);
1698                 MetricsInfo mi(bv(), getFont(par, ii->pos), w);
1699                 ii->inset->metrics(mi, dim);
1700         }
1701
1702         // rebreak the paragraph
1703         par.rows().clear();
1704         Dimension dim;
1705
1706         par.setBeginOfBody();
1707         pos_type z = 0;
1708         do {
1709                 Row row(z);
1710                 rowBreakPoint(pit, row);
1711                 setRowWidth(pit, row);
1712                 setHeightOfRow(pit, row);
1713                 par.rows().push_back(row);
1714                 dim.wid = std::max(dim.wid, row.width());
1715                 dim.des += row.height();
1716                 z = row.endpos();
1717         } while (z < par.size());
1718
1719         dim.asc += par.rows()[0].ascent();
1720         dim.des -= par.rows()[0].ascent();
1721
1722         bool const same = dim == par.dim();
1723
1724         par.dim() = dim;
1725         //lyxerr << "redoParagraph: " << par.rows().size() << " rows\n";
1726
1727         return !same;
1728 }
1729
1730
1731 void LyXText::metrics(MetricsInfo & mi, Dimension & dim)
1732 {
1733         //BOOST_ASSERT(mi.base.textwidth);
1734         if (mi.base.textwidth)
1735                 maxwidth_ = mi.base.textwidth;
1736         //lyxerr << "LyXText::metrics: width: " << mi.base.textwidth
1737         //      << " maxWidth: " << maxwidth_ << "\nfont: " << mi.base.font << endl;
1738         // save the caller's font locally:
1739         font_ = mi.base.font;
1740
1741         unsigned int h = 0;
1742         unsigned int w = 0;
1743         for (pit_type pit = 0, n = paragraphs().size(); pit != n; ++pit) {
1744                 redoParagraph(pit);
1745                 Paragraph & par = paragraphs()[pit];
1746                 h += par.height();
1747                 if (w < par.width())
1748                         w = par.width();
1749         }
1750
1751         dim.wid = w;
1752         dim.asc = pars_[0].ascent();
1753         dim.des = h - dim.asc;
1754
1755         dim_ = dim;
1756 }
1757
1758
1759 // only used for inset right now. should also be used for main text
1760 void LyXText::draw(PainterInfo & pi, int x, int y) const
1761 {
1762         paintTextInset(*this, pi, x, y);
1763 }
1764
1765
1766 #if 0
1767 // only used for inset right now. should also be used for main text
1768 void LyXText::drawSelection(PainterInfo & pi, int x , int) const
1769 {
1770         LCursor & cur = pi.base.bv->cursor();
1771         if (!cur.selection())
1772                 return;
1773         if (!ptr_cmp(cur.text(), this))
1774                 return;
1775
1776         lyxerr << "draw selection at " << x << endl;
1777
1778         // is there a better way of getting these two iterators?
1779         DocIterator beg = cur;
1780         DocIterator end = cur;
1781
1782         beg.top() = cur.selBegin();
1783         end.top() = cur.selEnd();
1784
1785         // the selection doesn't touch the visible screen
1786         if (bv_funcs::status(pi.base.bv, beg) == bv_funcs::CUR_BELOW
1787             || bv_funcs::status(pi.base.bv, end) == bv_funcs::CUR_ABOVE)
1788                 return;
1789
1790         Paragraph const & par1 = pars_[beg.pit()];
1791         Paragraph const & par2 = pars_[end.pit()];
1792
1793         Row const & row1 = par1.getRow(beg.pos(), beg.boundary());
1794         Row const & row2 = par2.getRow(end.pos(), end.boundary());
1795
1796         int y1,x1,x2;
1797         if (bv_funcs::status(pi.base.bv, beg) == bv_funcs::CUR_ABOVE) {
1798                 y1 = 0;
1799                 x1 = 0;
1800                 x2 = 0;
1801         } else {
1802                 y1 = bv_funcs::getPos(beg).y_ - row1.ascent();
1803                 int const startx = cursorX(beg.top(), begin.boundary());
1804                 x1 = isRTL(par1) ? startx : 0;
1805                 x2 = isRTL(par1) ? 0 + dim_.wid : startx;
1806         }
1807
1808         int y2,X1,X2;
1809         if (bv_funcs::status(pi.base.bv, end) == bv_funcs::CUR_BELOW) {
1810                 y2 = pi.base.bv->workHeight();
1811                 X1 = 0;
1812                 X2 = 0;
1813         } else {
1814                 y2 = bv_funcs::getPos(end).y_ + row2.descent();
1815                 int const endx = cursorX(end.top(), end.boundary());
1816                 X1 = isRTL(par2) ? 0 : endx;
1817                 X2 = isRTL(par2) ? endx : 0 + dim_.wid;
1818         }
1819
1820         lyxerr << " y1: " << y1 << " y2: " << y2
1821                 << " xo: " << xo_ << " wid: " << dim_.wid
1822                 << endl;
1823
1824         // paint big rectangle in one go
1825         pi.pain.fillRectangle(x, y1, dim_.wid, y2 - y1, LColor::selection);
1826
1827         // reset background at begin of first selected line
1828         pi.pain.fillRectangle(x + x1, y1, x2 - x1, row1.height(),
1829                 LColor::background);
1830
1831         // reset background at end of last selected line
1832         pi.pain.fillRectangle(x + X1, y2  - row2.height(),
1833                 X2 - X1, row2.height(), LColor::background);
1834 }
1835
1836 #else
1837
1838 void LyXText::drawSelection(PainterInfo & pi, int x, int) const
1839 {
1840         LCursor & cur = pi.base.bv->cursor();
1841         if (!cur.selection())
1842                 return;
1843         if (!ptr_cmp(cur.text(), this))
1844                 return;
1845
1846         lyxerr[Debug::DEBUG]
1847                 << BOOST_CURRENT_FUNCTION
1848                 << "draw selection at " << x
1849                 << endl;
1850
1851         // is there a better way of getting these two iterators?
1852         DocIterator beg = cur;
1853         DocIterator end = cur;
1854
1855         beg.top() = cur.selBegin();
1856         end.top() = cur.selEnd();
1857
1858         // the selection doesn't touch the visible screen
1859         if (bv_funcs::status(pi.base.bv, beg) == bv_funcs::CUR_BELOW
1860             || bv_funcs::status(pi.base.bv, end) == bv_funcs::CUR_ABOVE)
1861                 return;
1862
1863         Paragraph const & par1 = pars_[beg.pit()];
1864         Paragraph const & par2 = pars_[end.pit()];
1865
1866         bool const above = (bv_funcs::status(pi.base.bv, beg)
1867                             == bv_funcs::CUR_ABOVE);
1868         bool const below = (bv_funcs::status(pi.base.bv, end)
1869                             == bv_funcs::CUR_BELOW);
1870         int y1,y2,x1,x2;
1871         if (above) {
1872                 y1 = 0;
1873                 y2 = 0;
1874                 x1 = 0;
1875                 x2 = dim_.wid;
1876         } else {
1877                 Row const & row1 = par1.getRow(beg.pos(), beg.boundary());
1878                 y1 = bv_funcs::getPos(beg, beg.boundary()).y_ - row1.ascent();
1879                 y2 = y1 + row1.height();
1880                 int const startx = cursorX(beg.top(), beg.boundary());
1881                 x1 = !isRTL(par1) ? startx : 0;
1882                 x2 = !isRTL(par1) ? 0 + dim_.wid : startx;
1883         }
1884
1885         int Y1,Y2,X1,X2;
1886         if (below) {
1887                 Y1 = pi.base.bv->workHeight();
1888                 Y2 = pi.base.bv->workHeight();
1889                 X1 = 0;
1890                 X2 = dim_.wid;
1891         } else {
1892                 Row const & row2 = par2.getRow(end.pos(), end.boundary());
1893                 Y1 = bv_funcs::getPos(end, end.boundary()).y_ - row2.ascent();
1894                 Y2 = Y1 + row2.height();
1895                 int const endx = cursorX(end.top(), end.boundary());
1896                 X1 = !isRTL(par2) ? 0 : endx;
1897                 X2 = !isRTL(par2) ? endx : 0 + dim_.wid;
1898         }
1899
1900         if (!above && !below && &par1.getRow(beg.pos(), beg.boundary())
1901             == &par2.getRow(end.pos(), end.boundary()))
1902         {
1903                 // paint only one rectangle
1904                 int const b( !isRTL(par1) ? x + x1 : x + X1 );
1905                 int const w( !isRTL(par1) ? X2 - x1 : x2 - X1 );
1906                 pi.pain.fillRectangle(b, y1, w, y2 - y1, LColor::selection);
1907                 return;
1908         }
1909
1910         lyxerr[Debug::DEBUG] << " y1: " << y1 << " y2: " << y2
1911                << "X1:" << X1 << " x2: " << X2 << " wid: " << dim_.wid
1912                 << endl;
1913
1914         // paint upper rectangle
1915         pi.pain.fillRectangle(x + x1, y1, x2 - x1, y2 - y1,
1916                                       LColor::selection);
1917         // paint bottom rectangle
1918         pi.pain.fillRectangle(x + X1, Y1, X2 - X1, Y2 - Y1,
1919                                       LColor::selection);
1920         // paint center rectangle
1921         pi.pain.fillRectangle(x, y2, dim_.wid,
1922                               Y1 - y2, LColor::selection);
1923 }
1924 #endif
1925
1926 bool LyXText::isLastRow(pit_type pit, Row const & row) const
1927 {
1928         return row.endpos() >= pars_[pit].size()
1929                 && pit + 1 == pit_type(paragraphs().size());
1930 }
1931
1932
1933 bool LyXText::isFirstRow(pit_type pit, Row const & row) const
1934 {
1935         return row.pos() == 0 && pit == 0;
1936 }
1937
1938
1939 void LyXText::getWord(CursorSlice & from, CursorSlice & to,
1940         word_location const loc)
1941 {
1942         Paragraph const & from_par = pars_[from.pit()];
1943         switch (loc) {
1944         case lyx::WHOLE_WORD_STRICT:
1945                 if (from.pos() == 0 || from.pos() == from_par.size()
1946                     || !from_par.isLetter(from.pos())
1947                     || !from_par.isLetter(from.pos() - 1)) {
1948                         to = from;
1949                         return;
1950                 }
1951                 // no break here, we go to the next
1952
1953         case lyx::WHOLE_WORD:
1954                 // If we are already at the beginning of a word, do nothing
1955                 if (!from.pos() || !from_par.isLetter(from.pos() - 1))
1956                         break;
1957                 // no break here, we go to the next
1958
1959         case lyx::PREVIOUS_WORD:
1960                 // always move the cursor to the beginning of previous word
1961                 while (from.pos() && from_par.isLetter(from.pos() - 1))
1962                         --from.pos();
1963                 break;
1964         case lyx::NEXT_WORD:
1965                 lyxerr << "LyXText::getWord: NEXT_WORD not implemented yet"
1966                        << endl;
1967                 break;
1968         case lyx::PARTIAL_WORD:
1969                 // no need to move the 'from' cursor
1970                 break;
1971         }
1972         to = from;
1973         Paragraph & to_par = pars_[to.pit()];
1974         while (to.pos() < to_par.size() && to_par.isLetter(to.pos()))
1975                 ++to.pos();
1976 }
1977
1978
1979 void LyXText::write(Buffer const & buf, std::ostream & os) const
1980 {
1981         ParagraphList::const_iterator pit = paragraphs().begin();
1982         ParagraphList::const_iterator end = paragraphs().end();
1983         Paragraph::depth_type dth = 0;
1984         for (; pit != end; ++pit)
1985                 pit->write(buf, os, buf.params(), dth);
1986 }
1987
1988
1989 bool LyXText::read(Buffer const & buf, LyXLex & lex)
1990 {
1991         Paragraph::depth_type depth = 0;
1992
1993         while (lex.isOK()) {
1994                 lex.nextToken();
1995                 string const token = lex.getString();
1996
1997                 if (token.empty())
1998                         continue;
1999
2000                 if (token == "\\end_inset") {
2001                         break;
2002                 }
2003
2004                 if (token == "\\end_body") {
2005                         continue;
2006                 }
2007
2008                 if (token == "\\begin_body") {
2009                         continue;
2010                 }
2011
2012                 if (token == "\\end_document") {
2013                         return false;
2014                 }
2015
2016                 if (token == "\\begin_layout") {
2017                         lex.pushToken(token);
2018
2019                         Paragraph par;
2020                         par.params().depth(depth);
2021                         if (buf.params().tracking_changes)
2022                                 par.trackChanges();
2023                         par.setFont(0, LyXFont(LyXFont::ALL_INHERIT, buf.params().language));
2024                         pars_.push_back(par);
2025
2026                         // FIXME: goddamn InsetTabular makes us pass a Buffer
2027                         // not BufferParams
2028                         ::readParagraph(buf, pars_.back(), lex);
2029
2030                 } else if (token == "\\begin_deeper") {
2031                         ++depth;
2032                 } else if (token == "\\end_deeper") {
2033                         if (!depth) {
2034                                 lex.printError("\\end_deeper: " "depth is already null");
2035                         } else {
2036                                 --depth;
2037                         }
2038                 } else {
2039                         lyxerr << "Handling unknown body token: `"
2040                                << token << '\'' << endl;
2041                 }
2042         }
2043         return true;
2044 }
2045
2046
2047 int LyXText::ascent() const
2048 {
2049         return dim_.asc;
2050 }
2051
2052
2053 int LyXText::descent() const
2054 {
2055         return dim_.des;
2056 }
2057
2058
2059 int LyXText::cursorX(CursorSlice const & sl, bool boundary) const
2060 {
2061         pit_type const pit = sl.pit();
2062         Paragraph const & par = pars_[pit];
2063         if (par.rows().empty())
2064                 return 0;
2065
2066         pos_type ppos = sl.pos();
2067         // Correct position in front of big insets
2068         bool const boundary_correction = ppos != 0 && boundary;
2069         if (boundary_correction)
2070                 --ppos;
2071
2072         Row const & row = par.getRow(sl.pos(), boundary);
2073
2074         pos_type cursor_vpos = 0;
2075
2076         RowMetrics const m = computeRowMetrics(pit, row);
2077         double x = m.x;
2078
2079         pos_type const row_pos  = row.pos();
2080         pos_type const end      = row.endpos();
2081
2082         if (end <= row_pos)
2083                 cursor_vpos = row_pos;
2084         else if (ppos >= end)
2085                 cursor_vpos = isRTL(par) ? row_pos : end;
2086         else if (ppos > row_pos && ppos >= end)
2087                 // Place cursor after char at (logical) position pos - 1
2088                 cursor_vpos = (bidi.level(ppos - 1) % 2 == 0)
2089                         ? bidi.log2vis(ppos - 1) + 1 : bidi.log2vis(ppos - 1);
2090         else
2091                 // Place cursor before char at (logical) position ppos
2092                 cursor_vpos = (bidi.level(ppos) % 2 == 0)
2093                         ? bidi.log2vis(ppos) : bidi.log2vis(ppos) + 1;
2094
2095         pos_type body_pos = par.beginOfBody();
2096         if (body_pos > 0 &&
2097             (body_pos > end || !par.isLineSeparator(body_pos - 1)))
2098                 body_pos = 0;
2099
2100         // Use font span to speed things up, see below
2101         FontSpan font_span;
2102         LyXFont font;
2103
2104         for (pos_type vpos = row_pos; vpos < cursor_vpos; ++vpos) {
2105                 pos_type pos = bidi.vis2log(vpos);
2106                 if (body_pos > 0 && pos == body_pos - 1) {
2107                         x += m.label_hfill
2108                                 + font_metrics::width(par.layout()->labelsep,
2109                                                       getLabelFont(par));
2110                         if (par.isLineSeparator(body_pos - 1))
2111                                 x -= singleWidth(par, body_pos - 1);
2112                 }
2113
2114                 // Use font span to speed things up, see above
2115                 if (pos < font_span.first || pos > font_span.last) {
2116                         font_span = par.fontSpan(pos);
2117                         font = getFont(par, pos);
2118                 }
2119
2120                 x += singleWidth(par, pos, par.getChar(pos), font);
2121
2122                 if (hfillExpansion(par, row, pos))
2123                         x += (pos >= body_pos) ? m.hfill : m.label_hfill;
2124                 else if (par.isSeparator(pos) && pos >= body_pos)
2125                         x += m.separator;
2126         }
2127         
2128         // see correction above
2129         if (boundary_correction)
2130                 if (getFont(par, ppos).isVisibleRightToLeft())
2131                         x -= singleWidth(par, ppos);
2132                 else
2133                         x += singleWidth(par, ppos);
2134
2135         // Make sure inside an inset we always count from the left
2136         // edge (bidi!) -- MV
2137         if (sl.pos() < par.size()) {
2138                 font = getFont(par, sl.pos());
2139                 if (!boundary && font.isVisibleRightToLeft()
2140                   && par.isInset(sl.pos()))
2141                         x -= par.getInset(sl.pos())->width();
2142         }       
2143         return int(x);
2144 }
2145
2146
2147 int LyXText::cursorY(CursorSlice const & sl, bool boundary) const
2148 {
2149         //lyxerr << "LyXText::cursorY: boundary: " << boundary << std::endl;
2150         Paragraph const & par = getPar(sl.pit());
2151         int h = 0;
2152         h -= pars_[0].rows()[0].ascent();
2153         for (pit_type pit = 0; pit < sl.pit(); ++pit)
2154                 h += pars_[pit].height();
2155         int pos = sl.pos();
2156         if (pos && boundary)
2157                 --pos;
2158         size_t const rend = par.pos2row(pos);
2159         for (size_t rit = 0; rit != rend; ++rit)
2160                 h += par.rows()[rit].height();
2161         h += par.rows()[rend].ascent();
2162         return h;
2163 }
2164
2165
2166 // Returns the current font and depth as a message.
2167 string LyXText::currentState(LCursor & cur)
2168 {
2169         BOOST_ASSERT(this == cur.text());
2170         Buffer & buf = cur.buffer();
2171         Paragraph const & par = cur.paragraph();
2172         std::ostringstream os;
2173
2174         bool const show_change = buf.params().tracking_changes
2175                 && cur.pos() != cur.lastpos()
2176                 && par.lookupChange(cur.pos()) != Change::UNCHANGED;
2177
2178         if (show_change) {
2179                 Change change = par.lookupChangeFull(cur.pos());
2180                 Author const & a = buf.params().authors().get(change.author);
2181                 os << _("Change: ") << a.name();
2182                 if (!a.email().empty())
2183                         os << " (" << a.email() << ")";
2184                 if (change.changetime)
2185                         os << _(" at ") << ctime(&change.changetime);
2186                 os << " : ";
2187         }
2188
2189         // I think we should only show changes from the default
2190         // font. (Asger)
2191         LyXFont font = real_current_font;
2192         font.reduce(buf.params().getLyXTextClass().defaultfont());
2193
2194         // avoid _(...) re-entrance problem
2195         string const s = font.stateText(&buf.params());
2196         os << bformat(_("Font: %1$s"), s);
2197
2198         // os << bformat(_("Font: %1$s"), font.stateText(&buf.params));
2199
2200         // The paragraph depth
2201         int depth = cur.paragraph().getDepth();
2202         if (depth > 0)
2203                 os << bformat(_(", Depth: %1$d"), depth);
2204
2205         // The paragraph spacing, but only if different from
2206         // buffer spacing.
2207         Spacing const & spacing = par.params().spacing();
2208         if (!spacing.isDefault()) {
2209                 os << _(", Spacing: ");
2210                 switch (spacing.getSpace()) {
2211                 case Spacing::Single:
2212                         os << _("Single");
2213                         break;
2214                 case Spacing::Onehalf:
2215                         os << _("OneHalf");
2216                         break;
2217                 case Spacing::Double:
2218                         os << _("Double");
2219                         break;
2220                 case Spacing::Other:
2221                         os << _("Other (") << spacing.getValueAsString() << ')';
2222                         break;
2223                 case Spacing::Default:
2224                         // should never happen, do nothing
2225                         break;
2226                 }
2227         }
2228
2229 #ifdef DEVEL_VERSION
2230         os << _(", Inset: ") << &cur.inset();
2231         os << _(", Paragraph: ") << cur.pit();
2232         os << _(", Id: ") << par.id();
2233         os << _(", Position: ") << cur.pos();
2234         os << _(", Boundary: ") << cur.boundary();
2235 //      Row & row = cur.textRow();
2236 //      os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
2237 #endif
2238         return os.str();
2239 }
2240
2241
2242 string LyXText::getPossibleLabel(LCursor & cur) const
2243 {
2244         pit_type pit = cur.pit();
2245
2246         LyXLayout_ptr layout = pars_[pit].layout();
2247
2248         if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
2249                 LyXLayout_ptr const & layout2 = pars_[pit - 1].layout();
2250                 if (layout2->latextype != LATEX_PARAGRAPH) {
2251                         --pit;
2252                         layout = layout2;
2253                 }
2254         }
2255
2256         string text = layout->latexname().substr(0, 3);
2257         if (layout->latexname() == "theorem")
2258                 text = "thm"; // Create a correct prefix for prettyref
2259
2260         text += ':';
2261         if (layout->latextype == LATEX_PARAGRAPH || lyxrc.label_init_length < 0)
2262                 text.erase();
2263
2264         string par_text = pars_[pit].asString(cur.buffer(), false);
2265         for (int i = 0; i < lyxrc.label_init_length; ++i) {
2266                 if (par_text.empty())
2267                         break;
2268                 string head;
2269                 par_text = split(par_text, head, ' ');
2270                 // Is it legal to use spaces in labels ?
2271                 if (i > 0)
2272                         text += '-';
2273                 text += head;
2274         }
2275
2276         return text;
2277 }
2278
2279
2280 //pos_type LyXText::x2pos(pit_type pit, int row, int x) const
2281 //{
2282 //      int lastx = 0;
2283 //      int currx = 0;
2284 //      Paragraph const & par = pars_[pit];
2285 //      Row const & r = par.rows()[row];
2286 //      int pos = r.pos();
2287 //      for (; currx < x && pos < r.endpos(); ++pos) {
2288 //              lastx = currx;
2289 //              currx += singleWidth(par, pos);
2290 //      }
2291 //      if (abs(lastx - x) < abs(currx - x) && pos != r.pos())
2292 //              --pos;
2293 //      return pos;
2294 //}
2295
2296
2297 pos_type LyXText::x2pos(pit_type pit, int row, int x) const
2298 {
2299         BOOST_ASSERT(row < int(pars_[pit].rows().size()));
2300         bool bound = false;
2301         Row const & r = pars_[pit].rows()[row];
2302         return r.pos() + getColumnNearX(pit, r, x, bound);
2303 }
2304
2305
2306 //int LyXText::pos2x(pit_type pit, pos_type pos) const
2307 //{
2308 //      Paragraph const & par = pars_[pit];
2309 //      Row const & r = par.rows()[row];
2310 //      int x = 0;
2311 //      pos -= r.pos();
2312 //}
2313
2314
2315 // x,y are screen coordinates
2316 // sets cursor only within this LyXText
2317 void LyXText::setCursorFromCoordinates(LCursor & cur, int const x, int const y)
2318 {
2319         pit_type pit = getPitNearY(y);
2320         int yy = theCoords.get(this, pit).y_ - pars_[pit].ascent();
2321         lyxerr[Debug::DEBUG]
2322                 << BOOST_CURRENT_FUNCTION
2323                 << ": x: " << x
2324                 << " y: " << y
2325                 << " pit: " << pit
2326                 << " yy: " << yy << endl;
2327
2328         Paragraph const & par = pars_[pit];
2329         int r = 0;
2330         BOOST_ASSERT(par.rows().size());
2331         for (; r < int(par.rows().size()) - 1; ++r) {
2332                 Row const & row = par.rows()[r];
2333                 if (int(yy + row.height()) > y)
2334                         break;
2335                 yy += row.height();
2336         }
2337
2338         Row const & row = par.rows()[r];
2339
2340         lyxerr[Debug::DEBUG]
2341                 << BOOST_CURRENT_FUNCTION
2342                 << ": row " << r
2343                 << " from pos: " << row.pos()
2344                 << endl;
2345
2346         bool bound = false;
2347         int xx = x;
2348         pos_type const pos = row.pos() + getColumnNearX(pit, row, xx, bound);
2349
2350         lyxerr[Debug::DEBUG]
2351                 << BOOST_CURRENT_FUNCTION
2352                 << ": setting cursor pit: " << pit
2353                 << " pos: " << pos
2354                 << endl;
2355         
2356         setCursor(cur, pit, pos, true, bound);
2357 }