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