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