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