]> git.lyx.org Git - lyx.git/blob - src/text.C
9c04cb9a53f425f488970e63872a0ecd135171ea
[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 void LyXText::cursorRightOneWord(LCursor & cur)
1320 {
1321         BOOST_ASSERT(this == cur.text());
1322         if (cur.pos() == cur.lastpos() && cur.pit() != cur.lastpit()) {
1323                 ++cur.pit();
1324                 cur.pos() = 0;
1325         } else {
1326                 // Skip through initial nonword stuff.
1327                 // Treat floats and insets as words.
1328                 while (cur.pos() != cur.lastpos() && !cur.paragraph().isLetter(cur.pos()))
1329                         ++cur.pos();
1330                 // Advance through word.
1331                 while (cur.pos() != cur.lastpos() && cur.paragraph().isLetter(cur.pos()))
1332                         ++cur.pos();
1333         }
1334         setCursor(cur, cur.pit(), cur.pos());
1335 }
1336
1337
1338 void LyXText::cursorLeftOneWord(LCursor & cur)
1339 {
1340         BOOST_ASSERT(this == cur.text());
1341         if (cur.pos() == 0 && cur.pit() != 0) {
1342                 --cur.pit();
1343                 cur.pos() = cur.lastpos();
1344         } else {
1345                 // Skip through initial nonword stuff.
1346                 // Treat floats and insets as words.
1347                 while (cur.pos() != 0 && !cur.paragraph().isLetter(cur.pos() - 1))
1348                         --cur.pos();
1349                 // Advance through word.
1350                 while (cur.pos() != 0 && cur.paragraph().isLetter(cur.pos() - 1))
1351                         --cur.pos();
1352         }
1353         setCursor(cur, cur.pit(), cur.pos());
1354 }
1355
1356
1357 void LyXText::selectWord(LCursor & cur, word_location loc)
1358 {
1359         BOOST_ASSERT(this == cur.text());
1360         CursorSlice from = cur.top();
1361         CursorSlice to = cur.top();
1362         getWord(from, to, loc);
1363         if (cur.top() != from)
1364                 setCursor(cur, from.pit(), from.pos());
1365         if (to == from)
1366                 return;
1367         cur.resetAnchor();
1368         setCursor(cur, to.pit(), to.pos());
1369         cur.setSelection();
1370 }
1371
1372
1373 // Select the word currently under the cursor when no
1374 // selection is currently set
1375 bool LyXText::selectWordWhenUnderCursor(LCursor & cur, word_location loc)
1376 {
1377         BOOST_ASSERT(this == cur.text());
1378         if (cur.selection())
1379                 return false;
1380         selectWord(cur, loc);
1381         return cur.selection();
1382 }
1383
1384
1385 void LyXText::acceptChange(LCursor & cur)
1386 {
1387         BOOST_ASSERT(this == cur.text());
1388         if (!cur.selection() && cur.lastpos() != 0)
1389                 return;
1390
1391         CursorSlice const & startc = cur.selBegin();
1392         CursorSlice const & endc = cur.selEnd();
1393         if (startc.pit() == endc.pit()) {
1394                 recordUndoSelection(cur, Undo::INSERT);
1395                 pars_[startc.pit()].acceptChange(startc.pos(), endc.pos());
1396                 finishUndo();
1397                 cur.clearSelection();
1398                 setCursorIntern(cur, startc.pit(), 0);
1399         }
1400 #ifdef WITH_WARNINGS
1401 #warning handle multi par selection
1402 #endif
1403 }
1404
1405
1406 void LyXText::rejectChange(LCursor & cur)
1407 {
1408         BOOST_ASSERT(this == cur.text());
1409         if (!cur.selection() && cur.lastpos() != 0)
1410                 return;
1411
1412         CursorSlice const & startc = cur.selBegin();
1413         CursorSlice const & endc = cur.selEnd();
1414         if (startc.pit() == endc.pit()) {
1415                 recordUndoSelection(cur, Undo::INSERT);
1416                 pars_[startc.pit()].rejectChange(startc.pos(), endc.pos());
1417                 finishUndo();
1418                 cur.clearSelection();
1419                 setCursorIntern(cur, startc.pit(), 0);
1420         }
1421 #ifdef WITH_WARNINGS
1422 #warning handle multi par selection
1423 #endif
1424 }
1425
1426
1427 // Delete from cursor up to the end of the current or next word.
1428 void LyXText::deleteWordForward(LCursor & cur)
1429 {
1430         BOOST_ASSERT(this == cur.text());
1431         if (cur.lastpos() == 0)
1432                 cursorRight(cur);
1433         else {
1434                 cur.resetAnchor();
1435                 cur.selection() = true;
1436                 cursorRightOneWord(cur);
1437                 cur.setSelection();
1438                 cutSelection(cur, true, false);
1439         }
1440 }
1441
1442
1443 // Delete from cursor to start of current or prior word.
1444 void LyXText::deleteWordBackward(LCursor & cur)
1445 {
1446         BOOST_ASSERT(this == cur.text());
1447         if (cur.lastpos() == 0)
1448                 cursorLeft(cur);
1449         else {
1450                 cur.resetAnchor();
1451                 cur.selection() = true;
1452                 cursorLeftOneWord(cur);
1453                 cur.setSelection();
1454                 cutSelection(cur, true, false);
1455         }
1456 }
1457
1458
1459 // Kill to end of line.
1460 void LyXText::deleteLineForward(LCursor & cur)
1461 {
1462         BOOST_ASSERT(this == cur.text());
1463         if (cur.lastpos() == 0) {
1464                 // Paragraph is empty, so we just go to the right
1465                 cursorRight(cur);
1466         } else {
1467                 cur.resetAnchor();
1468                 cur.selection() = true; // to avoid deletion
1469                 cursorEnd(cur);
1470                 cur.setSelection();
1471                 // What is this test for ??? (JMarc)
1472                 if (!cur.selection())
1473                         deleteWordForward(cur);
1474                 else
1475                         cutSelection(cur, true, false);
1476         }
1477 }
1478
1479
1480 void LyXText::changeCase(LCursor & cur, LyXText::TextCase action)
1481 {
1482         BOOST_ASSERT(this == cur.text());
1483         CursorSlice from;
1484         CursorSlice to;
1485
1486         if (cur.selection()) {
1487                 from = cur.selBegin();
1488                 to = cur.selEnd();
1489         } else {
1490                 from = cur.top();
1491                 getWord(from, to, lyx::PARTIAL_WORD);
1492                 setCursor(cur, to.pit(), to.pos() + 1);
1493         }
1494
1495         recordUndoSelection(cur);
1496
1497         pos_type pos = from.pos();
1498         int par = from.pit();
1499
1500         while (par != int(pars_.size()) && (pos != to.pos() || par != to.pit())) {
1501                 pit_type pit = par;
1502                 if (pos == pars_[pit].size()) {
1503                         ++par;
1504                         pos = 0;
1505                         continue;
1506                 }
1507                 unsigned char c = pars_[pit].getChar(pos);
1508                 if (c != Paragraph::META_INSET) {
1509                         switch (action) {
1510                         case text_lowercase:
1511                                 c = lowercase(c);
1512                                 break;
1513                         case text_capitalization:
1514                                 c = uppercase(c);
1515                                 action = text_lowercase;
1516                                 break;
1517                         case text_uppercase:
1518                                 c = uppercase(c);
1519                                 break;
1520                         }
1521                 }
1522 #ifdef WITH_WARNINGS
1523 #warning changes
1524 #endif
1525                 pars_[pit].setChar(pos, c);
1526                 ++pos;
1527         }
1528 }
1529
1530
1531 void LyXText::Delete(LCursor & cur)
1532 {
1533         BOOST_ASSERT(this == cur.text());
1534         if (cur.pos() != cur.lastpos()) {
1535                 recordUndo(cur, Undo::DELETE, cur.pit());
1536                 setCursorIntern(cur, cur.pit(), cur.pos() + 1, false, cur.boundary());
1537                 backspace(cur);
1538         }
1539         // should we do anything in an else branch?
1540 }
1541
1542
1543 void LyXText::backspace(LCursor & cur)
1544 {
1545         BOOST_ASSERT(this == cur.text());
1546         if (cur.pos() == 0) {
1547                 // The cursor is at the beginning of a paragraph, so
1548                 // the the backspace will collapse two paragraphs into
1549                 // one.
1550
1551                 // but it's not allowed unless it's new
1552                 Paragraph & par = cur.paragraph();
1553                 if (par.isChangeEdited(0, par.size()))
1554                         return;
1555
1556                 // we may paste some paragraphs
1557
1558                 // is it an empty paragraph?
1559                 pos_type lastpos = cur.lastpos();
1560                 if (lastpos == 0 || (lastpos == 1 && par.isSeparator(0))) {
1561                         // This is an empty paragraph and we delete it just
1562                         // by moving the cursor one step
1563                         // left and let the DeleteEmptyParagraphMechanism
1564                         // handle the actual deletion of the paragraph.
1565
1566                         if (cur.pit() != 0) {
1567                                 cursorLeft(cur);
1568                                 return;
1569                         }
1570                 }
1571
1572                 if (cur.pit() != 0)
1573                         recordUndo(cur, Undo::DELETE, cur.pit() - 1);
1574
1575                 pit_type tmppit = cur.pit();
1576                 // We used to do cursorLeftIntern() here, but it is
1577                 // not a good idea since it triggers the auto-delete
1578                 // mechanism. So we do a cursorLeftIntern()-lite,
1579                 // without the dreaded mechanism. (JMarc)
1580                 if (cur.pit() != 0) {
1581                         // steps into the above paragraph.
1582                         setCursorIntern(cur, cur.pit() - 1,
1583                                         pars_[cur.pit() - 1].size(),
1584                                         false);
1585                 }
1586
1587                 // Pasting is not allowed, if the paragraphs have different
1588                 // layout. I think it is a real bug of all other
1589                 // word processors to allow it. It confuses the user.
1590                 // Correction: Pasting is always allowed with standard-layout
1591                 Buffer & buf = cur.buffer();
1592                 BufferParams const & bufparams = buf.params();
1593                 LyXTextClass const & tclass = bufparams.getLyXTextClass();
1594                 pit_type const cpit = cur.pit();
1595
1596                 if (cpit != tmppit
1597                     && (pars_[cpit].layout() == pars_[tmppit].layout()
1598                         || pars_[tmppit].layout() == tclass.defaultLayout())
1599                     && pars_[cpit].getAlign() == pars_[tmppit].getAlign()) {
1600                         mergeParagraph(bufparams, pars_, cpit);
1601
1602                         if (cur.pos() != 0 && pars_[cpit].isSeparator(cur.pos() - 1))
1603                                 --cur.pos();
1604
1605                         // the counters may have changed
1606                         updateCounters();
1607                         setCursor(cur, cur.pit(), cur.pos(), false);
1608                 }
1609         } else {
1610                 // this is the code for a normal backspace, not pasting
1611                 // any paragraphs
1612                 recordUndo(cur, Undo::DELETE);
1613                 // We used to do cursorLeftIntern() here, but it is
1614                 // not a good idea since it triggers the auto-delete
1615                 // mechanism. So we do a cursorLeftIntern()-lite,
1616                 // without the dreaded mechanism. (JMarc)
1617                 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1618                                 false, cur.boundary());
1619                 cur.paragraph().erase(cur.pos());
1620         }
1621
1622         if (cur.pos() == cur.lastpos())
1623                 setCurrentFont(cur);
1624
1625         setCursor(cur, cur.pit(), cur.pos(), false, cur.boundary());
1626 }
1627
1628
1629 Paragraph & LyXText::getPar(pit_type par) const
1630 {
1631         //lyxerr << "getPar: " << par << " from " << paragraphs().size() << endl;
1632         BOOST_ASSERT(par >= 0);
1633         BOOST_ASSERT(par < int(paragraphs().size()));
1634         return paragraphs()[par];
1635 }
1636
1637
1638 Row const & LyXText::firstRow() const
1639 {
1640         return *paragraphs().front().rows().begin();
1641 }
1642
1643
1644 void LyXText::redoParagraph(pit_type const pit)
1645 {
1646         // remove rows of paragraph, keep track of height changes
1647         Paragraph & par = pars_[pit];
1648
1649         // redo insets
1650         InsetList::iterator ii = par.insetlist.begin();
1651         InsetList::iterator iend = par.insetlist.end();
1652         for (; ii != iend; ++ii) {
1653                 Dimension dim;
1654                 int const w = maxwidth_ - leftMargin(pit) - rightMargin(par);
1655                 MetricsInfo mi(bv(), getFont(par, ii->pos), w);
1656                 ii->inset->metrics(mi, dim);
1657         }
1658
1659         // rebreak the paragraph
1660         par.rows().clear();
1661         Dimension dim;
1662
1663         par.setBeginOfBody();
1664         pos_type z = 0;
1665         do {
1666                 Row row(z);
1667                 rowBreakPoint(pit, row);
1668                 setRowWidth(pit, row);
1669                 setHeightOfRow(pit, row);
1670                 par.rows().push_back(row);
1671                 dim.wid = std::max(dim.wid, row.width());
1672                 dim.des += row.height();
1673                 z = row.endpos();
1674         } while (z < par.size());
1675
1676         dim.asc += par.rows()[0].ascent();
1677         dim.des -= par.rows()[0].ascent();
1678         par.dim() = dim;
1679         //lyxerr << "redoParagraph: " << par.rows().size() << " rows\n";
1680 }
1681
1682
1683 void LyXText::metrics(MetricsInfo & mi, Dimension & dim)
1684 {
1685         //BOOST_ASSERT(mi.base.textwidth);
1686         if (mi.base.textwidth)
1687                 maxwidth_ = mi.base.textwidth;
1688         //lyxerr << "LyXText::metrics: width: " << mi.base.textwidth
1689         //      << " maxWidth: " << maxwidth_ << "\nfont: " << mi.base.font << endl;
1690
1691         unsigned int h = 0;
1692         unsigned int w = 0;
1693         for (pit_type pit = 0, n = paragraphs().size(); pit != n; ++pit) {
1694                 redoParagraph(pit);
1695                 Paragraph & par = paragraphs()[pit];
1696                 h += par.height();
1697                 if (w < par.width())
1698                         w = par.width();
1699         }
1700
1701         dim.wid = w;
1702         dim.asc = pars_[0].ascent();
1703         dim.des = h - dim.asc;
1704
1705         dim_ = dim;
1706 }
1707
1708
1709 // only used for inset right now. should also be used for main text
1710 void LyXText::draw(PainterInfo & pi, int x, int y) const
1711 {
1712         paintTextInset(*this, pi, x, y);
1713 }
1714
1715
1716 /*
1717 // only used for inset right now. should also be used for main text
1718 void LyXText::drawSelection(PainterInfo & pi, int x , int) const
1719 {
1720         LCursor & cur = pi.base.bv->cursor();
1721         if (!cur.selection())
1722                 return;
1723         if (!ptr_cmp(cur.text(), this))
1724                 return;
1725
1726         lyxerr << "draw selection at " << x << endl;
1727
1728         // is there a better way of getting these two iterators?
1729         DocIterator beg = cur;
1730         DocIterator end = cur;
1731
1732         beg.top() = cur.selBegin();
1733         end.top() = cur.selEnd();
1734
1735         // the selection doesn't touch the visible screen
1736         if (bv_funcs::status(pi.base.bv, beg) == bv_funcs::CUR_BELOW
1737             || bv_funcs::status(pi.base.bv, end) == bv_funcs::CUR_ABOVE)
1738                 return;
1739
1740         Paragraph const & par1 = pars_[beg.pit()];
1741         Paragraph const & par2 = pars_[end.pit()];
1742
1743         Row const & row1 = par1.getRow(beg.pos());
1744         Row const & row2 = par2.getRow(end.pos());
1745
1746         int y1,x1,x2;
1747         if (bv_funcs::status(pi.base.bv, beg) == bv_funcs::CUR_ABOVE) {
1748                 y1 = 0;
1749                 x1 = 0;
1750                 x2 = 0;
1751         } else {
1752                 y1 = bv_funcs::getPos(beg).y_ - row1.ascent();
1753                 int const startx = cursorX(beg.top());
1754                 x1 = isRTL(par1) ? startx : 0;
1755                 x2 = isRTL(par1) ? 0 + dim_.wid : startx;
1756         }
1757
1758         int y2,X1,X2;
1759         if (bv_funcs::status(pi.base.bv, end) == bv_funcs::CUR_BELOW) {
1760                 y2 = pi.base.bv->workHeight();
1761                 X1 = 0;
1762                 X2 = 0;
1763         } else {
1764                 y2 = bv_funcs::getPos(end).y_ + row2.descent();
1765                 int const endx = cursorX(end.top());
1766                 X1 = isRTL(par2) ? 0 : endx;
1767                 X2 = isRTL(par2) ? endx : 0 + dim_.wid;
1768         }
1769
1770         lyxerr << " y1: " << y1 << " y2: " << y2
1771                 << " xo: " << xo_ << " wid: " << dim_.wid
1772                 << endl;
1773
1774         // paint big rectangle in one go
1775         pi.pain.fillRectangle(x, y1, dim_.wid, y2 - y1, LColor::selection);
1776
1777         // reset background at begin of first selected line
1778         pi.pain.fillRectangle(x + x1, y1, x2 - x1, row1.height(),
1779                 LColor::background);
1780
1781         // reset background at end of last selected line
1782         pi.pain.fillRectangle(x + X1, y2  - row2.height(),
1783                 X2 - X1, row2.height(), LColor::background);
1784 }
1785 */
1786
1787
1788 void LyXText::drawSelection(PainterInfo & pi, int x, int) const
1789 {
1790         LCursor & cur = pi.base.bv->cursor();
1791         if (!cur.selection())
1792                 return;
1793         if (!ptr_cmp(cur.text(), this))
1794                 return;
1795
1796         lyxerr << "draw selection at " << x << endl;
1797
1798         // is there a better way of getting these two iterators?
1799         DocIterator beg = cur;
1800         DocIterator end = cur;
1801
1802         beg.top() = cur.selBegin();
1803         end.top() = cur.selEnd();
1804
1805         // the selection doesn't touch the visible screen
1806         if (bv_funcs::status(pi.base.bv, beg) == bv_funcs::CUR_BELOW
1807             || bv_funcs::status(pi.base.bv, end) == bv_funcs::CUR_ABOVE)
1808                 return;
1809
1810         Paragraph const & par1 = pars_[beg.pit()];
1811         Paragraph const & par2 = pars_[end.pit()];
1812
1813         bool const above = (bv_funcs::status(pi.base.bv, beg)
1814                             == bv_funcs::CUR_ABOVE);
1815         bool const below = (bv_funcs::status(pi.base.bv, end)
1816                             == bv_funcs::CUR_BELOW);
1817         int y1,y2,x1,x2;
1818         if (above) {
1819                 y1 = 0;
1820                 y2 = 0;
1821                 x1 = 0;
1822                 x2 = dim_.wid;
1823         } else {
1824                 Row const & row1 = par1.getRow(beg.pos());
1825                 y1 = bv_funcs::getPos(beg).y_ - row1.ascent();
1826                 y2 = y1 + row1.height();
1827                 int const startx = cursorX(beg.top());
1828                 x1 = !isRTL(par1) ? startx : 0;
1829                 x2 = !isRTL(par1) ? 0 + dim_.wid : startx;
1830         }
1831
1832         int Y1,Y2,X1,X2;
1833         if (below) {
1834                 Y1 = pi.base.bv->workHeight();
1835                 Y2 = pi.base.bv->workHeight();
1836                 X1 = 0;
1837                 X2 = dim_.wid;
1838         } else {
1839                 Row const & row2 = par2.getRow(end.pos());
1840                 Y1 = bv_funcs::getPos(end).y_ - row2.ascent();
1841                 Y2 = Y1 + row2.height();
1842                 int const endx = cursorX(end.top());
1843                 X1 = !isRTL(par2) ? 0 : endx;
1844                 X2 = !isRTL(par2) ? endx : 0 + dim_.wid;
1845         }
1846
1847         if (!above && !below && &par1.getRow(beg.pos())
1848             == &par2.getRow(end.pos()))
1849         {
1850                 // paint only one rectangle
1851                 pi.pain.fillRectangle(x + x1, y1, X2 - x1, y2 - y1,
1852                                       LColor::selection);
1853                 return;
1854         }
1855
1856         // paint upper rectangle
1857         pi.pain.fillRectangle(x + x1, y1, x2 - x1, y2 - y1,
1858                                       LColor::selection);
1859         // paint bottom rectangle
1860         pi.pain.fillRectangle(x + X1, Y1, X2 - X1, Y2 - Y1,
1861                                       LColor::selection);
1862         // paint center rectangle
1863         pi.pain.fillRectangle(x, y2, dim_.wid,
1864                               Y1 - y2, LColor::selection);
1865 }
1866
1867 bool LyXText::isLastRow(pit_type pit, Row const & row) const
1868 {
1869         return row.endpos() >= pars_[pit].size()
1870                 && pit + 1 == pit_type(paragraphs().size());
1871 }
1872
1873
1874 bool LyXText::isFirstRow(pit_type pit, Row const & row) const
1875 {
1876         return row.pos() == 0 && pit == 0;
1877 }
1878
1879
1880 void LyXText::getWord(CursorSlice & from, CursorSlice & to,
1881         word_location const loc)
1882 {
1883         Paragraph const & from_par = pars_[from.pit()];
1884         switch (loc) {
1885         case lyx::WHOLE_WORD_STRICT:
1886                 if (from.pos() == 0 || from.pos() == from_par.size()
1887                     || !from_par.isLetter(from.pos())
1888                     || !from_par.isLetter(from.pos() - 1)) {
1889                         to = from;
1890                         return;
1891                 }
1892                 // no break here, we go to the next
1893
1894         case lyx::WHOLE_WORD:
1895                 // If we are already at the beginning of a word, do nothing
1896                 if (!from.pos() || !from_par.isLetter(from.pos() - 1))
1897                         break;
1898                 // no break here, we go to the next
1899
1900         case lyx::PREVIOUS_WORD:
1901                 // always move the cursor to the beginning of previous word
1902                 while (from.pos() && from_par.isLetter(from.pos() - 1))
1903                         --from.pos();
1904                 break;
1905         case lyx::NEXT_WORD:
1906                 lyxerr << "LyXText::getWord: NEXT_WORD not implemented yet"
1907                        << endl;
1908                 break;
1909         case lyx::PARTIAL_WORD:
1910                 // no need to move the 'from' cursor
1911                 break;
1912         }
1913         to = from;
1914         Paragraph & to_par = pars_[to.pit()];
1915         while (to.pos() < to_par.size() && to_par.isLetter(to.pos()))
1916                 ++to.pos();
1917 }
1918
1919
1920 void LyXText::write(Buffer const & buf, std::ostream & os) const
1921 {
1922         ParagraphList::const_iterator pit = paragraphs().begin();
1923         ParagraphList::const_iterator end = paragraphs().end();
1924         Paragraph::depth_type dth = 0;
1925         for (; pit != end; ++pit)
1926                 pit->write(buf, os, buf.params(), dth);
1927 }
1928
1929
1930 bool LyXText::read(Buffer const & buf, LyXLex & lex)
1931 {
1932         static Change current_change;
1933
1934         Paragraph::depth_type depth = 0;
1935
1936         while (lex.isOK()) {
1937                 lex.nextToken();
1938                 string const token = lex.getString();
1939
1940                 if (token.empty())
1941                         continue;
1942
1943                 if (token == "\\end_inset") {
1944                         break;
1945                 }
1946
1947                 if (token == "\\end_body") {
1948                         continue;
1949                 }
1950
1951                 if (token == "\\begin_body") {
1952                         continue;
1953                 }
1954
1955                 if (token == "\\end_document") {
1956                         return false;
1957                 }
1958
1959                 if (token == "\\begin_layout") {
1960                         lex.pushToken(token);
1961
1962                         Paragraph par;
1963                         par.params().depth(depth);
1964                         if (buf.params().tracking_changes)
1965                                 par.trackChanges();
1966                         par.setFont(0, LyXFont(LyXFont::ALL_INHERIT, buf.params().language));
1967                         pars_.push_back(par);
1968
1969                         // FIXME: goddamn InsetTabular makes us pass a Buffer
1970                         // not BufferParams
1971                         ::readParagraph(buf, pars_.back(), lex);
1972
1973                 } else if (token == "\\begin_deeper") {
1974                         ++depth;
1975                 } else if (token == "\\end_deeper") {
1976                         if (!depth) {
1977                                 lex.printError("\\end_deeper: " "depth is already null");
1978                         } else {
1979                                 --depth;
1980                         }
1981                 } else {
1982                         lyxerr << "Handling unknown body token: `"
1983                                << token << '\'' << endl;
1984                 }
1985         }
1986         return true;
1987 }
1988
1989
1990 int LyXText::ascent() const
1991 {
1992         return dim_.asc;
1993 }
1994
1995
1996 int LyXText::descent() const
1997 {
1998         return dim_.des;
1999 }
2000
2001
2002 int LyXText::cursorX(CursorSlice const & cur) const
2003 {
2004         pit_type const pit = cur.pit();
2005         Paragraph const & par = pars_[pit];
2006         if (par.rows().empty())
2007                 return 0;
2008
2009         Row const & row = par.getRow(cur.pos());
2010
2011         pos_type pos = cur.pos();
2012         pos_type cursor_vpos = 0;
2013
2014         RowMetrics const m = computeRowMetrics(pit, row);
2015         double x = m.x;
2016
2017         pos_type const row_pos  = row.pos();
2018         pos_type const end      = row.endpos();
2019
2020         if (end <= row_pos)
2021                 cursor_vpos = row_pos;
2022         else if (pos >= end)
2023                 cursor_vpos = isRTL(par) ? row_pos : end;
2024         else if (pos > row_pos && pos >= end)
2025                 // Place cursor after char at (logical) position pos - 1
2026                 cursor_vpos = (bidi.level(pos - 1) % 2 == 0)
2027                         ? bidi.log2vis(pos - 1) + 1 : bidi.log2vis(pos - 1);
2028         else
2029                 // Place cursor before char at (logical) position pos
2030                 cursor_vpos = (bidi.level(pos) % 2 == 0)
2031                         ? bidi.log2vis(pos) : bidi.log2vis(pos) + 1;
2032
2033         pos_type body_pos = par.beginOfBody();
2034         if (body_pos > 0 &&
2035             (body_pos > end || !par.isLineSeparator(body_pos - 1)))
2036                 body_pos = 0;
2037
2038         for (pos_type vpos = row_pos; vpos < cursor_vpos; ++vpos) {
2039                 pos_type pos = bidi.vis2log(vpos);
2040                 if (body_pos > 0 && pos == body_pos - 1) {
2041                         x += m.label_hfill
2042                                 + font_metrics::width(par.layout()->labelsep,
2043                                                       getLabelFont(par));
2044                         if (par.isLineSeparator(body_pos - 1))
2045                                 x -= singleWidth(par, body_pos - 1);
2046                 }
2047
2048                 if (hfillExpansion(par, row, pos)) {
2049                         x += singleWidth(par, pos);
2050                         if (pos >= body_pos)
2051                                 x += m.hfill;
2052                         else
2053                                 x += m.label_hfill;
2054                 } else if (par.isSeparator(pos)) {
2055                         x += singleWidth(par, pos);
2056                         if (pos >= body_pos)
2057                                 x += m.separator;
2058                 } else
2059                         x += singleWidth(par, pos);
2060         }
2061         return int(x);
2062 }
2063
2064
2065 int LyXText::cursorY(CursorSlice const & cur) const
2066 {
2067         Paragraph const & par = getPar(cur.pit());
2068         int h = 0;
2069         h -= pars_[0].rows()[0].ascent();
2070         for (pit_type pit = 0; pit < cur.pit(); ++pit)
2071                 h += pars_[pit].height();
2072         for (size_t rit = 0, rend = par.pos2row(cur.pos()); rit != rend; ++rit)
2073                 h += par.rows()[rit].height();
2074         h += par.rows()[par.pos2row(cur.pos())].ascent();
2075         return h;
2076 }
2077
2078
2079 // Returns the current font and depth as a message.
2080 string LyXText::currentState(LCursor & cur)
2081 {
2082         BOOST_ASSERT(this == cur.text());
2083         Buffer & buf = cur.buffer();
2084         Paragraph const & par = cur.paragraph();
2085         std::ostringstream os;
2086
2087         bool const show_change = buf.params().tracking_changes
2088                 && cur.pos() != cur.lastpos()
2089                 && par.lookupChange(cur.pos()) != Change::UNCHANGED;
2090
2091         if (show_change) {
2092                 Change change = par.lookupChangeFull(cur.pos());
2093                 Author const & a = buf.params().authors().get(change.author);
2094                 os << _("Change: ") << a.name();
2095                 if (!a.email().empty())
2096                         os << " (" << a.email() << ")";
2097                 if (change.changetime)
2098                         os << _(" at ") << ctime(&change.changetime);
2099                 os << " : ";
2100         }
2101
2102         // I think we should only show changes from the default
2103         // font. (Asger)
2104         LyXFont font = real_current_font;
2105         font.reduce(buf.params().getLyXTextClass().defaultfont());
2106
2107         // avoid _(...) re-entrance problem
2108         string const s = font.stateText(&buf.params());
2109         os << bformat(_("Font: %1$s"), s);
2110
2111         // os << bformat(_("Font: %1$s"), font.stateText(&buf.params));
2112
2113         // The paragraph depth
2114         int depth = cur.paragraph().getDepth();
2115         if (depth > 0)
2116                 os << bformat(_(", Depth: %1$d"), depth);
2117
2118         // The paragraph spacing, but only if different from
2119         // buffer spacing.
2120         Spacing const & spacing = par.params().spacing();
2121         if (!spacing.isDefault()) {
2122                 os << _(", Spacing: ");
2123                 switch (spacing.getSpace()) {
2124                 case Spacing::Single:
2125                         os << _("Single");
2126                         break;
2127                 case Spacing::Onehalf:
2128                         os << _("OneHalf");
2129                         break;
2130                 case Spacing::Double:
2131                         os << _("Double");
2132                         break;
2133                 case Spacing::Other:
2134                         os << _("Other (") << spacing.getValueAsString() << ')';
2135                         break;
2136                 case Spacing::Default:
2137                         // should never happen, do nothing
2138                         break;
2139                 }
2140         }
2141
2142 #ifdef DEVEL_VERSION
2143         os << _(", Inset: ") << &cur.inset();
2144         os << _(", Paragraph: ") << cur.pit();
2145         os << _(", Id: ") << par.id();
2146         os << _(", Position: ") << cur.pos();
2147 //      Row & row = cur.textRow();
2148 //      os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
2149 #endif
2150         return os.str();
2151 }
2152
2153
2154 string LyXText::getPossibleLabel(LCursor & cur) const
2155 {
2156         pit_type pit = cur.pit();
2157
2158         LyXLayout_ptr layout = pars_[pit].layout();
2159
2160         if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
2161                 LyXLayout_ptr const & layout2 = pars_[pit - 1].layout();
2162                 if (layout2->latextype != LATEX_PARAGRAPH) {
2163                         --pit;
2164                         layout = layout2;
2165                 }
2166         }
2167
2168         string text = layout->latexname().substr(0, 3);
2169         if (layout->latexname() == "theorem")
2170                 text = "thm"; // Create a correct prefix for prettyref
2171
2172         text += ':';
2173         if (layout->latextype == LATEX_PARAGRAPH || lyxrc.label_init_length < 0)
2174                 text.erase();
2175
2176         string par_text = pars_[pit].asString(cur.buffer(), false);
2177         for (int i = 0; i < lyxrc.label_init_length; ++i) {
2178                 if (par_text.empty())
2179                         break;
2180                 string head;
2181                 par_text = split(par_text, head, ' ');
2182                 // Is it legal to use spaces in labels ?
2183                 if (i > 0)
2184                         text += '-';
2185                 text += head;
2186         }
2187
2188         return text;
2189 }
2190
2191
2192 //pos_type LyXText::x2pos(pit_type pit, int row, int x) const
2193 //{
2194 //      int lastx = 0;
2195 //      int currx = 0;
2196 //      Paragraph const & par = pars_[pit];
2197 //      Row const & r = par.rows()[row];
2198 //      int pos = r.pos();
2199 //      for (; currx < x && pos < r.endpos(); ++pos) {
2200 //              lastx = currx;
2201 //              currx += singleWidth(par, pos);
2202 //      }
2203 //      if (abs(lastx - x) < abs(currx - x) && pos != r.pos())
2204 //              --pos;
2205 //      return pos;
2206 //}
2207
2208
2209 pos_type LyXText::x2pos(pit_type pit, int row, int x) const
2210 {
2211         bool bound = false;
2212         Row const & r = pars_[pit].rows()[row];
2213         return r.pos() + getColumnNearX(pit, r, x, bound);
2214 }
2215
2216
2217 //int LyXText::pos2x(pit_type pit, pos_type pos) const
2218 //{
2219 //      Paragraph const & par = pars_[pit];
2220 //      Row const & r = par.rows()[row];
2221 //      int x = 0;
2222 //      pos -= r.pos();
2223 //}
2224
2225
2226 // x,y are screen coordinates
2227 // sets cursor only within this LyXText
2228 void LyXText::setCursorFromCoordinates(LCursor & cur, int const x, int const y)
2229 {
2230         pit_type pit = getPitNearY(y);
2231         int yy = theCoords.get(this, pit).y_ - pars_[pit].ascent();
2232         lyxerr << "setCursorFromCoordinates: x: " << x << " y: " << y
2233                 << " pit: " << pit << " yy: " << yy << endl;
2234
2235         Paragraph const & par = pars_[pit];
2236         int r = 0;
2237         BOOST_ASSERT(par.rows().size());
2238         for (; r < int(par.rows().size()) - 1; ++r) {
2239                 Row const & row = par.rows()[r];
2240                 if (int(yy + row.height()) > y)
2241                         break;
2242                 yy += row.height();
2243         }
2244
2245         Row const & row = par.rows()[r];
2246
2247         lyxerr << "setCursorFromCoordinates:  row " << r
2248                << " from pos: " << row.pos() << endl;
2249
2250         bool bound = false;
2251         int xx = x;
2252         pos_type const pos = row.pos() + getColumnNearX(pit, row, xx, bound);
2253         setCursor(cur, pit, pos, true, bound);
2254 }