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