]> git.lyx.org Git - lyx.git/blob - src/text.C
5 new lfuns, move all apply code out of ControlDocument and into the core.
[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 #warning This is wrong.
613                 int minfill = maxwidth_;
614                 for ( ; rit != end; ++rit)
615                         if (rit->fill() < minfill)
616                                 minfill = rit->fill();
617                 x += font_metrics::signedWidth(layout->leftmargin,
618                         tclass.defaultfont());
619                 x += minfill;
620 #endif
621                 // also wrong, but much shorter.
622                 x += maxwidth_ / 2;
623                 break;
624         }
625         }
626         
627
628         if (!pars_[pit].params().leftIndent().zero())
629                 x += pars_[pit].params().leftIndent().inPixels(maxwidth_);
630
631         LyXAlignment align;
632
633         if (pars_[pit].params().align() == LYX_ALIGN_LAYOUT)
634                 align = layout->align;
635         else
636                 align = pars_[pit].params().align();
637
638         // set the correct parindent
639         if (pos == 0
640             && (layout->labeltype == LABEL_NO_LABEL
641                || layout->labeltype == LABEL_TOP_ENVIRONMENT
642                || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
643                || (layout->labeltype == LABEL_STATIC
644                    && layout->latextype == LATEX_ENVIRONMENT
645                    && !isFirstInSequence(pit, paragraphs())))
646             && align == LYX_ALIGN_BLOCK
647             && !pars_[pit].params().noindent()
648             // in tabulars and ert paragraphs are never indented!
649             && (!pars_[pit].inInset()
650                 || (pars_[pit].inInset()->lyxCode() != InsetOld::TABULAR_CODE
651                     && pars_[pit].inInset()->lyxCode() != InsetOld::ERT_CODE))
652             && (pars_[pit].layout() != tclass.defaultLayout()
653                 || bv()->buffer()->params().paragraph_separation ==
654                    BufferParams::PARSEP_INDENT))
655         {
656                 x += font_metrics::signedWidth(parindent, tclass.defaultfont());
657         }
658
659         return x;
660 }
661
662
663 int LyXText::rightMargin(Paragraph const & par) const
664 {
665         LyXTextClass const & tclass = bv()->buffer()->params().getLyXTextClass();
666
667         return
668                 RIGHT_MARGIN
669                 + font_metrics::signedWidth(tclass.rightmargin(),
670                                        tclass.defaultfont())
671                 + font_metrics::signedWidth(par.layout()->rightmargin,
672                                        tclass.defaultfont())
673                 * 4 / (par.getDepth() + 4);
674 }
675
676
677 int LyXText::labelEnd(par_type pit) const
678 {
679         // labelEnd is only needed if the layout fills a flushleft label.
680         if (pars_[pit].layout()->margintype != MARGIN_MANUAL)
681                 return 0;
682         // return the beginning of the body
683         return leftMargin(pit);
684 }
685
686
687 namespace {
688
689 // this needs special handling - only newlines count as a break point
690 pos_type addressBreakPoint(pos_type i, Paragraph const & par)
691 {
692         pos_type const end = par.size();
693
694         for (; i < end; ++i)
695                 if (par.isNewline(i))
696                         return i + 1;
697
698         return end;
699 }
700
701 };
702
703
704 void LyXText::rowBreakPoint(par_type pit, Row & row) const
705 {
706         pos_type const end = pars_[pit].size();
707         pos_type const pos = row.pos();
708         if (pos == end) {
709                 row.endpos(end);
710                 return;
711         }
712
713         // maximum pixel width of a row
714         int width = maxwidth_ - rightMargin(pars_[pit]); // - leftMargin(pit, row);
715         if (width < 0) {
716                 row.endpos(end);
717                 return;
718         }
719
720         LyXLayout_ptr const & layout = pars_[pit].layout();
721
722         if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX) {
723                 row.endpos(addressBreakPoint(pos, pars_[pit]));
724                 return;
725         }
726
727         pos_type const body_pos = pars_[pit].beginOfBody();
728
729
730         // Now we iterate through until we reach the right margin
731         // or the end of the par, then choose the possible break
732         // nearest that.
733
734         int const left = leftMargin(pit, pos);
735         int x = left;
736
737         // pixel width since last breakpoint
738         int chunkwidth = 0;
739
740         FontIterator fi = FontIterator(*this, pit, pos);
741         pos_type point = end;
742         pos_type i = pos;
743         for ( ; i < end; ++i, ++fi) {
744                 char const c = pars_[pit].getChar(i);
745
746                 {
747                         int thiswidth = singleWidth(pit, i, c, *fi);
748
749                         // add the auto-hfill from label end to the body
750                         if (body_pos && i == body_pos) {
751                                 int add = font_metrics::width(layout->labelsep, getLabelFont(pit));
752                                 if (pars_[pit].isLineSeparator(i - 1))
753                                         add -= singleWidth(pit, i - 1);
754
755                                 add = std::max(add, labelEnd(pit) - x);
756                                 thiswidth += add;
757                         }
758
759                         x += thiswidth;
760                         chunkwidth += thiswidth;
761                 }
762
763                 // break before a character that will fall off
764                 // the right of the row
765                 if (x >= width) {
766                         // if no break before, break here
767                         if (point == end || chunkwidth >= width - left) {
768                                 if (i > pos)
769                                         point = i;
770                                 else
771                                         point = i + 1;
772
773                         }
774                         // exit on last registered breakpoint:
775                         break;
776                 }
777
778                 if (pars_[pit].isNewline(i)) {
779                         point = i + 1;
780                         break;
781                 }
782                 // Break before...
783                 if (i + 1 < end) {
784                         if (pars_[pit].isInset(i + 1) && pars_[pit].getInset(i + 1)->display()) {
785                                 point = i + 1;
786                                 break;
787                         }
788                         // ...and after.
789                         if (pars_[pit].isInset(i) && pars_[pit].getInset(i)->display()) {
790                                 point = i + 1;
791                                 break;
792                         }
793                 }
794                 
795                 if (!pars_[pit].isInset(i) || pars_[pit].getInset(i)->isChar()) {
796                         // some insets are line separators too
797                         if (pars_[pit].isLineSeparator(i)) {
798                                 // register breakpoint:
799                                 point = i + 1;
800                                 chunkwidth = 0;
801                         }
802                 }
803         }
804
805         // maybe found one, but the par is short enough.
806         if (i == end && x < width)
807                 point = end;
808
809         // manual labels cannot be broken in LaTeX. But we
810         // want to make our on-screen rendering of footnotes
811         // etc. still break
812         if (body_pos && point < body_pos)
813                 point = body_pos;
814
815         row.endpos(point);
816 }
817
818
819 void LyXText::setRowWidth(par_type pit, Row & row) const
820 {
821         // get the pure distance
822         pos_type const end = row.endpos();
823
824         string labelsep = pars_[pit].layout()->labelsep;
825         int w = leftMargin(pit, row.pos());
826
827         pos_type const body_pos = pars_[pit].beginOfBody();
828         pos_type i = row.pos();
829
830         if (i < end) {
831                 FontIterator fi = FontIterator(*this, pit, i);
832                 for ( ; i < end; ++i, ++fi) {
833                         if (body_pos > 0 && i == body_pos) {
834                                 w += font_metrics::width(labelsep, getLabelFont(pit));
835                                 if (pars_[pit].isLineSeparator(i - 1))
836                                         w -= singleWidth(pit, i - 1);
837                                 w = max(w, labelEnd(pit));
838                         }
839                         char const c = pars_[pit].getChar(i);
840                         w += singleWidth(pit, i, c, *fi);
841                 }
842         }
843
844         if (body_pos > 0 && body_pos >= end) {
845                 w += font_metrics::width(labelsep, getLabelFont(pit));
846                 if (end > 0 && pars_[pit].isLineSeparator(end - 1))
847                         w -= singleWidth(pit, end - 1);
848                 w = max(w, labelEnd(pit));
849         }
850
851         row.width(w + rightMargin(pars_[pit]));
852 }
853
854
855 // returns the minimum space a manual label needs on the screen in pixel
856 int LyXText::labelFill(par_type pit, Row const & row) const
857 {
858         pos_type last = pars_[pit].beginOfBody();
859
860         BOOST_ASSERT(last > 0);
861
862         // -1 because a label ends with a space that is in the label
863         --last;
864
865         // a separator at this end does not count
866         if (pars_[pit].isLineSeparator(last))
867                 --last;
868
869         int w = 0;
870         for (pos_type i = row.pos(); i <= last; ++i)
871                 w += singleWidth(pit, i);
872
873         string const & label = pars_[pit].params().labelWidthString();
874         if (label.empty())
875                 return 0;
876
877         return max(0, font_metrics::width(label, getLabelFont(pit)) - w);
878 }
879
880
881 LColor_color LyXText::backgroundColor() const
882 {
883         return LColor_color(LColor::color(background_color_));
884 }
885
886
887 void LyXText::setHeightOfRow(par_type pit, Row & row)
888 {
889         // get the maximum ascent and the maximum descent
890         double layoutasc = 0;
891         double layoutdesc = 0;
892         double const dh = defaultRowHeight();
893
894         // ok, let us initialize the maxasc and maxdesc value.
895         // Only the fontsize count. The other properties
896         // are taken from the layoutfont. Nicer on the screen :)
897         LyXLayout_ptr const & layout = pars_[pit].layout();
898
899         // as max get the first character of this row then it can
900         // increase but not decrease the height. Just some point to
901         // start with so we don't have to do the assignment below too
902         // often.
903         LyXFont font = getFont(pit, row.pos());
904         LyXFont::FONT_SIZE const tmpsize = font.size();
905         font = getLayoutFont(pit);
906         LyXFont::FONT_SIZE const size = font.size();
907         font.setSize(tmpsize);
908
909         LyXFont labelfont = getLabelFont(pit);
910
911         // these are minimum values
912         double const spacing_val =
913                 layout->spacing.getValue() * spacing(pars_[pit]);
914         //lyxerr << "spacing_val = " << spacing_val << endl;
915         int maxasc  = int(font_metrics::maxAscent(font)  * spacing_val);
916         int maxdesc = int(font_metrics::maxDescent(font) * spacing_val);
917
918         // insets may be taller
919         InsetList::iterator ii = pars_[pit].insetlist.begin();
920         InsetList::iterator iend = pars_[pit].insetlist.end();
921         for ( ; ii != iend; ++ii) {
922                 if (ii->pos >= row.pos() && ii->pos < row.endpos()) {
923                         maxasc  = max(maxasc,  ii->inset->ascent());
924                         maxdesc = max(maxdesc, ii->inset->descent());
925                 }
926         }
927
928         // Check if any custom fonts are larger (Asger)
929         // This is not completely correct, but we can live with the small,
930         // cosmetic error for now.
931         int labeladdon = 0;
932         pos_type const pos_end = row.endpos();
933
934         LyXFont::FONT_SIZE maxsize =
935                 pars_[pit].highestFontInRange(row.pos(), pos_end, size);
936         if (maxsize > font.size()) {
937                 font.setSize(maxsize);
938                 maxasc  = max(maxasc,  font_metrics::maxAscent(font));
939                 maxdesc = max(maxdesc, font_metrics::maxDescent(font));
940         }
941
942         // This is nicer with box insets:
943         ++maxasc;
944         ++maxdesc;
945
946         row.ascent_of_text(maxasc);
947
948         // is it a top line?
949         if (row.pos() == 0) {
950                 BufferParams const & bufparams = bv()->buffer()->params();
951                 // some parksips VERY EASY IMPLEMENTATION
952                 if (bv()->buffer()->params().paragraph_separation
953                     == BufferParams::PARSEP_SKIP
954                         && pit != 0
955                         && ((layout->isParagraph() && pars_[pit].getDepth() == 0)
956                             || (pars_[pit - 1].layout()->isParagraph()
957                                 && pars_[pit - 1].getDepth() == 0)))
958                 {
959                                 maxasc += bufparams.getDefSkip().inPixels(*bv());
960                 }
961
962                 if (pars_[pit].params().startOfAppendix())
963                         maxasc += int(3 * dh);
964
965                 // This is special code for the chapter, since the label of this
966                 // layout is printed in an extra row
967                 if (layout->counter == "chapter" && bufparams.secnumdepth >= 0) {
968                         labeladdon = int(font_metrics::maxHeight(labelfont)
969                                      * layout->spacing.getValue()
970                                      * spacing(pars_[pit]));
971                 }
972
973                 // special code for the top label
974                 if ((layout->labeltype == LABEL_TOP_ENVIRONMENT
975                      || layout->labeltype == LABEL_BIBLIO
976                      || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
977                     && isFirstInSequence(pit, paragraphs())
978                     && !pars_[pit].getLabelstring().empty())
979                 {
980                         labeladdon = int(
981                                   font_metrics::maxHeight(labelfont)
982                                         * layout->spacing.getValue()
983                                         * spacing(pars_[pit])
984                                 + (layout->topsep + layout->labelbottomsep) * dh);
985                 }
986
987                 // Add the layout spaces, for example before and after
988                 // a section, or between the items of a itemize or enumerate
989                 // environment.
990
991                 par_type prev = depthHook(pit, pars_, pars_[pit].getDepth());
992                 if (prev != pit
993                     && pars_[prev].layout() == layout
994                     && pars_[prev].getDepth() == pars_[pit].getDepth()
995                     && pars_[prev].getLabelWidthString() == pars_[pit].getLabelWidthString())
996                 {
997                         layoutasc = layout->itemsep * dh;
998                 } else if (pit != 0 || row.pos() != 0) {
999                         if (layout->topsep > 0)
1000                                 layoutasc = layout->topsep * dh;
1001                 }
1002
1003                 prev = outerHook(pit, pars_);
1004                 if (prev != par_type(pars_.size())) {
1005                         maxasc += int(pars_[prev].layout()->parsep * dh);
1006                 } else if (pit != 0) {
1007                         if (pars_[pit - 1].getDepth() != 0 ||
1008                                         pars_[pit - 1].layout() == layout) {
1009                                 maxasc += int(layout->parsep * dh);
1010                         }
1011                 }
1012         }
1013
1014         // is it a bottom line?
1015         if (row.endpos() >= pars_[pit].size()) {
1016                 // add the layout spaces, for example before and after
1017                 // a section, or between the items of a itemize or enumerate
1018                 // environment
1019                 par_type nextpit = pit + 1;
1020                 if (nextpit != par_type(pars_.size())) {
1021                         par_type cpit = pit;
1022                         double usual = 0;
1023                         double unusual = 0;
1024
1025                         if (pars_[cpit].getDepth() > pars_[nextpit].getDepth()) {
1026                                 usual = pars_[cpit].layout()->bottomsep * dh;
1027                                 cpit = depthHook(cpit, paragraphs(), pars_[nextpit].getDepth());
1028                                 if (pars_[cpit].layout() != pars_[nextpit].layout()
1029                                         || pars_[nextpit].getLabelWidthString() != pars_[cpit].getLabelWidthString())
1030                                 {
1031                                         unusual = pars_[cpit].layout()->bottomsep * dh;
1032                                 }
1033                                 layoutdesc = max(unusual, usual);
1034                         } else if (pars_[cpit].getDepth() == pars_[nextpit].getDepth()) {
1035                                 if (pars_[cpit].layout() != pars_[nextpit].layout()
1036                                         || pars_[nextpit].getLabelWidthString() != pars_[cpit].getLabelWidthString())
1037                                         layoutdesc = int(pars_[cpit].layout()->bottomsep * dh);
1038                         }
1039                 }
1040         }
1041
1042         // incalculate the layout spaces
1043         maxasc  += int(layoutasc  * 2 / (2 + pars_[pit].getDepth()));
1044         maxdesc += int(layoutdesc * 2 / (2 + pars_[pit].getDepth()));
1045
1046         row.height(maxasc + maxdesc + labeladdon);
1047         row.baseline(maxasc + labeladdon);
1048         row.top_of_text(row.baseline() - font_metrics::maxAscent(font));
1049 }
1050
1051
1052 void LyXText::breakParagraph(LCursor & cur, char keep_layout)
1053 {
1054         BOOST_ASSERT(this == cur.text());
1055         // allow only if at start or end, or all previous is new text
1056         Paragraph & cpar = cur.paragraph();
1057         par_type cpit = cur.par();
1058
1059         if (cur.pos() != 0 && cur.pos() != cur.lastpos()
1060             && cpar.isChangeEdited(0, cur.pos()))
1061                 return;
1062
1063         LyXTextClass const & tclass =
1064                 bv()->buffer()->params().getLyXTextClass();
1065         LyXLayout_ptr const & layout = cpar.layout();
1066
1067         // this is only allowed, if the current paragraph is not empty
1068         // or caption and if it has not the keepempty flag active
1069         if (cur.lastpos() == 0 && !cpar.allowEmpty()
1070            && layout->labeltype != LABEL_SENSITIVE)
1071                 return;
1072
1073         // a layout change may affect also the following paragraph
1074         recUndo(cur.par(), undoSpan(cur.par()) - 1);
1075
1076         // Always break behind a space
1077         // It is better to erase the space (Dekel)
1078         if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
1079                 cpar.erase(cur.pos());
1080
1081         // break the paragraph
1082         if (keep_layout)
1083                 keep_layout = 2;
1084         else
1085                 keep_layout = layout->isEnvironment();
1086
1087         // we need to set this before we insert the paragraph. IMO the
1088         // breakParagraph call should return a bool if it inserts the
1089         // paragraph before or behind and we should react on that one
1090         // but we can fix this in 1.3.0 (Jug 20020509)
1091         bool const isempty = cpar.allowEmpty() && cpar.empty();
1092         ::breakParagraph(bv()->buffer()->params(), paragraphs(), cpit,
1093                          cur.pos(), keep_layout);
1094
1095         cpit = cur.par();
1096         par_type next_par = cpit + 1;
1097
1098         // well this is the caption hack since one caption is really enough
1099         if (layout->labeltype == LABEL_SENSITIVE) {
1100                 if (!cur.pos())
1101                         // set to standard-layout
1102                         pars_[cpit].applyLayout(tclass.defaultLayout());
1103                 else
1104                         // set to standard-layout
1105                         pars_[next_par].applyLayout(tclass.defaultLayout());
1106         }
1107
1108         // if the cursor is at the beginning of a row without prior newline,
1109         // move one row up!
1110         // This touches only the screen-update. Otherwise we would may have
1111         // an empty row on the screen
1112         if (cur.pos() != 0 && cur.textRow().pos() == cur.pos()
1113             && !pars_[cpit].isNewline(cur.pos() - 1))
1114         {
1115                 cursorLeft(cur);
1116         }
1117
1118         while (!pars_[next_par].empty() && pars_[next_par].isNewline(0))
1119                 pars_[next_par].erase(0);
1120
1121         updateCounters();
1122         redoParagraph(cpit);
1123         redoParagraph(next_par);
1124
1125         // This check is necessary. Otherwise the new empty paragraph will
1126         // be deleted automatically. And it is more friendly for the user!
1127         if (cur.pos() != 0 || isempty)
1128                 setCursor(cur, cur.par() + 1, 0);
1129         else
1130                 setCursor(cur, cur.par(), 0);
1131 }
1132
1133
1134 // convenience function
1135 void LyXText::redoParagraph(LCursor & cur)
1136 {
1137         BOOST_ASSERT(this == cur.text());
1138         cur.clearSelection();
1139         redoParagraph(cur.par());
1140         setCursorIntern(cur, cur.par(), cur.pos());
1141 }
1142
1143
1144 // insert a character, moves all the following breaks in the
1145 // same Paragraph one to the right and make a rebreak
1146 void LyXText::insertChar(LCursor & cur, char c)
1147 {
1148         BOOST_ASSERT(this == cur.text());
1149         BOOST_ASSERT(c != Paragraph::META_INSET);
1150
1151         recordUndo(cur, Undo::INSERT);
1152
1153         Paragraph & par = cur.paragraph();
1154         // try to remove this
1155         par_type pit = cur.par();
1156
1157         bool const freeSpacing = par.layout()->free_spacing ||
1158                 par.isFreeSpacing();
1159
1160         if (lyxrc.auto_number) {
1161                 static string const number_operators = "+-/*";
1162                 static string const number_unary_operators = "+-";
1163                 static string const number_seperators = ".,:";
1164
1165                 if (current_font.number() == LyXFont::ON) {
1166                         if (!IsDigit(c) && !contains(number_operators, c) &&
1167                             !(contains(number_seperators, c) &&
1168                               cur.pos() != 0 &&
1169                               cur.pos() != cur.lastpos() &&
1170                               getFont(pit, cur.pos()).number() == LyXFont::ON &&
1171                               getFont(pit, cur.pos() - 1).number() == LyXFont::ON)
1172                            )
1173                                 number(cur); // Set current_font.number to OFF
1174                 } else if (IsDigit(c) &&
1175                            real_current_font.isVisibleRightToLeft()) {
1176                         number(cur); // Set current_font.number to ON
1177
1178                         if (cur.pos() != 0) {
1179                                 char const c = par.getChar(cur.pos() - 1);
1180                                 if (contains(number_unary_operators, c) &&
1181                                     (cur.pos() == 1
1182                                      || par.isSeparator(cur.pos() - 2)
1183                                      || par.isNewline(cur.pos() - 2))
1184                                   ) {
1185                                         setCharFont(pit, cur.pos() - 1, current_font);
1186                                 } else if (contains(number_seperators, c)
1187                                      && cur.pos() >= 2
1188                                      && getFont(pit, cur.pos() - 2).number() == LyXFont::ON) {
1189                                         setCharFont(pit, cur.pos() - 1, current_font);
1190                                 }
1191                         }
1192                 }
1193         }
1194
1195         // First check, if there will be two blanks together or a blank at
1196         // the beginning of a paragraph.
1197         // I decided to handle blanks like normal characters, the main
1198         // difference are the special checks when calculating the row.fill
1199         // (blank does not count at the end of a row) and the check here
1200
1201         // The bug is triggered when we type in a description environment:
1202         // The current_font is not changed when we go from label to main text
1203         // and it should (along with realtmpfont) when we type the space.
1204         // CHECK There is a bug here! (Asger)
1205
1206         // store the current font.  This is because of the use of cursor
1207         // movements. The moving cursor would refresh the current font
1208         LyXFont realtmpfont = real_current_font;
1209         LyXFont rawtmpfont = current_font;
1210
1211         // When the free-spacing option is set for the current layout,
1212         // disable the double-space checking
1213         if (!freeSpacing && IsLineSeparatorChar(c)) {
1214                 if (cur.pos() == 0) {
1215                         static bool sent_space_message = false;
1216                         if (!sent_space_message) {
1217                                 cur.message(_("You cannot insert a space at the "
1218                                         "beginning of a paragraph. Please read the Tutorial."));
1219                                 sent_space_message = true;
1220                                 return;
1221                         }
1222                 }
1223                 BOOST_ASSERT(cur.pos() > 0);
1224                 if (par.isLineSeparator(cur.pos() - 1)
1225                     || par.isNewline(cur.pos() - 1)) {
1226                         static bool sent_space_message = false;
1227                         if (!sent_space_message) {
1228                                 cur.message(_("You cannot type two spaces this way. "
1229                                         "Please read the Tutorial."));
1230                                 sent_space_message = true;
1231                         }
1232                         return;
1233                 }
1234         }
1235
1236         par.insertChar(cur.pos(), c);
1237         setCharFont(pit, cur.pos(), rawtmpfont);
1238
1239         current_font = rawtmpfont;
1240         real_current_font = realtmpfont;
1241         redoParagraph(cur);
1242         setCursor(cur, cur.par(), cur.pos() + 1, false, cur.boundary());
1243         charInserted();
1244 }
1245
1246
1247 void LyXText::charInserted()
1248 {
1249         // Here we call finishUndo for every 20 characters inserted.
1250         // This is from my experience how emacs does it. (Lgb)
1251         static unsigned int counter;
1252         if (counter < 20) {
1253                 ++counter;
1254         } else {
1255                 finishUndo();
1256                 counter = 0;
1257         }
1258 }
1259
1260
1261 RowMetrics LyXText::computeRowMetrics(par_type pit, Row const & row) const
1262 {
1263         RowMetrics result;
1264
1265         double w = width_ - row.width();
1266
1267         bool const is_rtl = isRTL(pars_[pit]);
1268         if (is_rtl)
1269                 result.x = rightMargin(pars_[pit]);
1270         else
1271                 result.x = leftMargin(pit, row.pos());
1272
1273         // is there a manual margin with a manual label
1274         LyXLayout_ptr const & layout = pars_[pit].layout();
1275
1276         if (layout->margintype == MARGIN_MANUAL
1277             && layout->labeltype == LABEL_MANUAL) {
1278                 /// We might have real hfills in the label part
1279                 int nlh = numberOfLabelHfills(pars_[pit], row);
1280
1281                 // A manual label par (e.g. List) has an auto-hfill
1282                 // between the label text and the body of the
1283                 // paragraph too.
1284                 // But we don't want to do this auto hfill if the par
1285                 // is empty.
1286                 if (!pars_[pit].empty())
1287                         ++nlh;
1288
1289                 if (nlh && !pars_[pit].getLabelWidthString().empty())
1290                         result.label_hfill = labelFill(pit, row) / double(nlh);
1291         }
1292
1293         // are there any hfills in the row?
1294         int const nh = numberOfHfills(pars_[pit], row);
1295
1296         if (nh) {
1297                 if (w > 0)
1298                         result.hfill = w / nh;
1299         // we don't have to look at the alignment if it is ALIGN_LEFT and
1300         // if the row is already larger then the permitted width as then
1301         // we force the LEFT_ALIGN'edness!
1302         } else if (int(row.width()) < maxwidth_) {
1303                 // is it block, flushleft or flushright?
1304                 // set x how you need it
1305                 int align;
1306                 if (pars_[pit].params().align() == LYX_ALIGN_LAYOUT)
1307                         align = layout->align;
1308                 else
1309                         align = pars_[pit].params().align();
1310
1311                 // Display-style insets should always be on a centred row
1312                 // The test on pars_[pit].size() is to catch zero-size pars, which
1313                 // would trigger the assert in Paragraph::getInset().
1314                 //inset = pars_[pit].size() ? pars_[pit].getInset(row.pos()) : 0;
1315                 if (!pars_[pit].empty()
1316                     && pars_[pit].isInset(row.pos())
1317                     && pars_[pit].getInset(row.pos())->display())
1318                 {
1319                         align = LYX_ALIGN_CENTER;
1320                 }
1321
1322                 switch (align) {
1323                 case LYX_ALIGN_BLOCK: {
1324                         int const ns = numberOfSeparators(pars_[pit], row);
1325                         bool disp_inset = false;
1326                         if (row.endpos() < pars_[pit].size()) {
1327                                 InsetBase const * in = pars_[pit].getInset(row.endpos());
1328                                 if (in)
1329                                         disp_inset = in->display();
1330                         }
1331                         // If we have separators, this is not the last row of a
1332                         // par, does not end in newline, and is not row above a
1333                         // display inset... then stretch it
1334                         if (ns
1335                             && row.endpos() < pars_[pit].size()
1336                             && !pars_[pit].isNewline(row.endpos() - 1)
1337                             && !disp_inset
1338                                 ) {
1339                                 result.separator = w / ns;
1340                         } else if (is_rtl) {
1341                                 result.x += w;
1342                         }
1343                         break;
1344                 }
1345                 case LYX_ALIGN_RIGHT:
1346                         result.x += w;
1347                         break;
1348                 case LYX_ALIGN_CENTER:
1349                         result.x += w / 2;
1350                         break;
1351                 }
1352         }
1353
1354         bidi.computeTables(pars_[pit], *bv()->buffer(), row);
1355         if (is_rtl) {
1356                 pos_type body_pos = pars_[pit].beginOfBody();
1357                 pos_type end = row.endpos();
1358
1359                 if (body_pos > 0
1360                     && (body_pos > end || !pars_[pit].isLineSeparator(body_pos - 1)))
1361                 {
1362                         result.x += font_metrics::width(layout->labelsep, getLabelFont(pit));
1363                         if (body_pos <= end)
1364                                 result.x += result.label_hfill;
1365                 }
1366         }
1367
1368         return result;
1369 }
1370
1371
1372 // the cursor set functions have a special mechanism. When they
1373 // realize, that you left an empty paragraph, they will delete it.
1374
1375 void LyXText::cursorRightOneWord(LCursor & cur)
1376 {
1377         BOOST_ASSERT(this == cur.text());
1378         if (cur.pos() == cur.lastpos() && cur.par() != cur.lastpar()) {
1379                 ++cur.par();
1380                 cur.pos() = 0;
1381         } else {
1382                 // Skip through initial nonword stuff.
1383                 // Treat floats and insets as words.
1384                 while (cur.pos() != cur.lastpos() && !cur.paragraph().isWord(cur.pos()))
1385                         ++cur.pos();
1386                 // Advance through word.
1387                 while (cur.pos() != cur.lastpos() && cur.paragraph().isWord(cur.pos()))
1388                         ++cur.pos();
1389         }
1390         setCursor(cur, cur.par(), cur.pos());
1391 }
1392
1393
1394 void LyXText::cursorLeftOneWord(LCursor & cur)
1395 {
1396         BOOST_ASSERT(this == cur.text());
1397         if (cur.pos() == 0 && cur.par() != 0) {
1398                 --cur.par();
1399                 cur.pos() = cur.lastpos();
1400         } else { 
1401                 // Skip through initial nonword stuff.
1402                 // Treat floats and insets as words.
1403                 while (cur.pos() != 0 && !cur.paragraph().isWord(cur.pos() - 1))
1404                         --cur.pos();
1405                 // Advance through word.
1406                 while (cur.pos() != 0 && cur.paragraph().isWord(cur.pos() - 1))
1407                         --cur.pos();
1408         }
1409         setCursor(cur, cur.par(), cur.pos());
1410 }
1411
1412
1413 void LyXText::selectWord(LCursor & cur, word_location loc)
1414 {
1415         BOOST_ASSERT(this == cur.text());
1416         CursorSlice from = cur.top();
1417         CursorSlice to = cur.top();
1418         getWord(from, to, loc);
1419         if (cur.top() != from)
1420                 setCursor(cur, from.par(), from.pos());
1421         if (to == from)
1422                 return;
1423         cur.resetAnchor();
1424         setCursor(cur, to.par(), to.pos());
1425         cur.setSelection();
1426 }
1427
1428
1429 // Select the word currently under the cursor when no
1430 // selection is currently set
1431 bool LyXText::selectWordWhenUnderCursor(LCursor & cur, word_location loc)
1432 {
1433         BOOST_ASSERT(this == cur.text());
1434         if (cur.selection())
1435                 return false;
1436         selectWord(cur, loc);
1437         return cur.selection();
1438 }
1439
1440
1441 void LyXText::acceptChange(LCursor & cur)
1442 {
1443         BOOST_ASSERT(this == cur.text());
1444         if (!cur.selection() && cur.lastpos() != 0)
1445                 return;
1446
1447         CursorSlice const & startc = cur.selBegin();
1448         CursorSlice const & endc = cur.selEnd();
1449         if (startc.par() == endc.par()) {
1450                 recordUndoSelection(cur, Undo::INSERT);
1451                 pars_[startc.par()].acceptChange(startc.pos(), endc.pos());
1452                 finishUndo();
1453                 cur.clearSelection();
1454                 redoParagraph(startc.par());
1455                 setCursorIntern(cur, startc.par(), 0);
1456         }
1457 #warning handle multi par selection
1458 }
1459
1460
1461 void LyXText::rejectChange(LCursor & cur)
1462 {
1463         BOOST_ASSERT(this == cur.text());
1464         if (!cur.selection() && cur.lastpos() != 0)
1465                 return;
1466
1467         CursorSlice const & startc = cur.selBegin();
1468         CursorSlice const & endc = cur.selEnd();
1469         if (startc.par() == endc.par()) {
1470                 recordUndoSelection(cur, Undo::INSERT);
1471                 pars_[startc.par()].rejectChange(startc.pos(), endc.pos());
1472                 finishUndo();
1473                 cur.clearSelection();
1474                 redoParagraph(startc.par());
1475                 setCursorIntern(cur, startc.par(), 0);
1476         }
1477 #warning handle multi par selection
1478 }
1479
1480
1481 // Delete from cursor up to the end of the current or next word.
1482 void LyXText::deleteWordForward(LCursor & cur)
1483 {
1484         BOOST_ASSERT(this == cur.text());
1485         if (cur.lastpos() == 0)
1486                 cursorRight(cur);
1487         else {
1488                 cur.resetAnchor();
1489                 cur.selection() = true;
1490                 cursorRightOneWord(cur);
1491                 cur.setSelection();
1492                 cutSelection(cur, true, false);
1493         }
1494 }
1495
1496
1497 // Delete from cursor to start of current or prior word.
1498 void LyXText::deleteWordBackward(LCursor & cur)
1499 {
1500         BOOST_ASSERT(this == cur.text());
1501         if (cur.lastpos() == 0)
1502                 cursorLeft(cur);
1503         else {
1504                 cur.resetAnchor();
1505                 cur.selection() = true;
1506                 cursorLeftOneWord(cur);
1507                 cur.setSelection();
1508                 cutSelection(cur, true, false);
1509         }
1510 }
1511
1512
1513 // Kill to end of line.
1514 void LyXText::deleteLineForward(LCursor & cur)
1515 {
1516         BOOST_ASSERT(this == cur.text());
1517         if (cur.lastpos() == 0) {
1518                 // Paragraph is empty, so we just go to the right
1519                 cursorRight(cur);
1520         } else {
1521                 cur.resetAnchor();
1522                 cur.selection() = true; // to avoid deletion
1523                 cursorEnd(cur);
1524                 cur.setSelection();
1525                 // What is this test for ??? (JMarc)
1526                 if (!cur.selection())
1527                         deleteWordForward(cur);
1528                 else
1529                         cutSelection(cur, true, false);
1530         }
1531 }
1532
1533
1534 void LyXText::changeCase(LCursor & cur, LyXText::TextCase action)
1535 {
1536         BOOST_ASSERT(this == cur.text());
1537         CursorSlice from;
1538         CursorSlice to;
1539
1540         if (cur.selection()) {
1541                 from = cur.selBegin();
1542                 to = cur.selEnd();
1543         } else {
1544                 from = cur.top();
1545                 getWord(from, to, lyx::PARTIAL_WORD);
1546                 setCursor(cur, to.par(), to.pos() + 1);
1547         }
1548
1549         recordUndoSelection(cur);
1550
1551         pos_type pos = from.pos();
1552         int par = from.par();
1553
1554         while (par != int(pars_.size()) && (pos != to.pos() || par != to.par())) {
1555                 par_type pit = par;
1556                 if (pos == pars_[pit].size()) {
1557                         ++par;
1558                         pos = 0;
1559                         continue;
1560                 }
1561                 unsigned char c = pars_[pit].getChar(pos);
1562                 if (c != Paragraph::META_INSET) {
1563                         switch (action) {
1564                         case text_lowercase:
1565                                 c = lowercase(c);
1566                                 break;
1567                         case text_capitalization:
1568                                 c = uppercase(c);
1569                                 action = text_lowercase;
1570                                 break;
1571                         case text_uppercase:
1572                                 c = uppercase(c);
1573                                 break;
1574                         }
1575                 }
1576 #warning changes
1577                 pars_[pit].setChar(pos, c);
1578                 ++pos;
1579         }
1580 }
1581
1582
1583 void LyXText::Delete(LCursor & cur)
1584 {
1585         BOOST_ASSERT(this == cur.text());
1586         // just move to the right, if we had success make a backspace
1587         CursorSlice sl = cur.top();
1588         cursorRight(cur);
1589         if (sl != cur.top()) {
1590                 recordUndo(cur, Undo::DELETE, cur.par(), 
1591                            max(par_type(0), cur.par() - 1));
1592                 backspace(cur);
1593         }
1594 }
1595
1596
1597 void LyXText::backspace(LCursor & cur)
1598 {
1599         BOOST_ASSERT(this == cur.text());
1600         if (cur.pos() == 0) {
1601                 // The cursor is at the beginning of a paragraph, so
1602                 // the the backspace will collapse two paragraphs into
1603                 // one.
1604
1605                 // but it's not allowed unless it's new
1606                 Paragraph & par = cur.paragraph();
1607                 if (par.isChangeEdited(0, par.size()))
1608                         return;
1609
1610                 // we may paste some paragraphs
1611
1612                 // is it an empty paragraph?
1613                 pos_type lastpos = cur.lastpos();
1614                 if (lastpos == 0 || (lastpos == 1 && par.isSeparator(0))) {
1615                         // This is an empty paragraph and we delete it just
1616                         // by moving the cursor one step
1617                         // left and let the DeleteEmptyParagraphMechanism
1618                         // handle the actual deletion of the paragraph.
1619
1620                         if (cur.par() != 0) {
1621                                 cursorLeft(cur);
1622                                 // the layout things can change the height of a row !
1623                                 redoParagraph(cur);
1624                                 return;
1625                         }
1626                 }
1627
1628                 if (cur.par() != 0)
1629                         recordUndo(cur, Undo::DELETE, cur.par() - 1);
1630
1631                 par_type tmppit = cur.par();
1632                 // We used to do cursorLeftIntern() here, but it is
1633                 // not a good idea since it triggers the auto-delete
1634                 // mechanism. So we do a cursorLeftIntern()-lite,
1635                 // without the dreaded mechanism. (JMarc)
1636                 if (cur.par() != 0) {
1637                         // steps into the above paragraph.
1638                         setCursorIntern(cur, cur.par() - 1,
1639                                         pars_[cur.par() - 1].size(),
1640                                         false);
1641                 }
1642
1643                 // Pasting is not allowed, if the paragraphs have different
1644                 // layout. I think it is a real bug of all other
1645                 // word processors to allow it. It confuses the user.
1646                 // Correction: Pasting is always allowed with standard-layout
1647                 Buffer & buf = *bv()->buffer();
1648                 BufferParams const & bufparams = buf.params();
1649                 LyXTextClass const & tclass = bufparams.getLyXTextClass();
1650                 par_type const cpit = cur.par();
1651
1652                 if (cpit != tmppit
1653                     && (pars_[cpit].layout() == pars_[tmppit].layout()
1654                         || pars_[tmppit].layout() == tclass.defaultLayout())
1655                     && pars_[cpit].getAlign() == pars_[tmppit].getAlign()) {
1656                         mergeParagraph(bufparams, buf.paragraphs(), cpit);
1657
1658                         if (cur.pos() != 0 && pars_[cpit].isSeparator(cur.pos() - 1))
1659                                 --cur.pos();
1660
1661                         // the counters may have changed
1662                         updateCounters();
1663                         setCursor(cur, cur.par(), cur.pos(), false);
1664                 }
1665         } else {
1666                 // this is the code for a normal backspace, not pasting
1667                 // any paragraphs
1668                 recordUndo(cur, Undo::DELETE);
1669                 // We used to do cursorLeftIntern() here, but it is
1670                 // not a good idea since it triggers the auto-delete
1671                 // mechanism. So we do a cursorLeftIntern()-lite,
1672                 // without the dreaded mechanism. (JMarc)
1673                 setCursorIntern(cur, cur.par(), cur.pos() - 1,
1674                                 false, cur.boundary());
1675                 cur.paragraph().erase(cur.pos());
1676         }
1677
1678         if (cur.pos() == cur.lastpos())
1679                 setCurrentFont(cur);
1680
1681         redoParagraph(cur);
1682         setCursor(cur, cur.par(), cur.pos(), false, cur.boundary());
1683 }
1684
1685
1686 Paragraph & LyXText::getPar(par_type par) const
1687 {
1688         //lyxerr << "getPar: " << par << " from " << paragraphs().size() << endl;
1689         BOOST_ASSERT(par >= 0);
1690         BOOST_ASSERT(par < int(paragraphs().size()));
1691         return paragraphs()[par];
1692 }
1693
1694
1695 // y is relative to this LyXText's top
1696 RowList::iterator LyXText::getRowNearY(int y, par_type & pit) const
1697 {
1698         BOOST_ASSERT(!paragraphs().empty());
1699         BOOST_ASSERT(!paragraphs().begin()->rows.empty());
1700 #if 1
1701         par_type const pend = paragraphs().size() - 1;
1702         pit = 0;
1703         while (int(pars_[pit].y + pars_[pit].height) < y && pit != pend)
1704                 ++pit;
1705
1706         RowList::iterator rit = pars_[pit].rows.end();
1707         RowList::iterator const rbegin = pars_[pit].rows.begin();
1708         do {
1709                 --rit;
1710         } while (rit != rbegin && int(pars_[pit].y + rit->y_offset()) > y);
1711
1712         return rit;
1713 #else
1714         pit = paragraphs().size() - 1;
1715
1716         RowList::iterator rit = lastRow();
1717         RowList::iterator rbegin = firstRow();
1718
1719         while (rit != rbegin && int(pars_[pit].y + rit->y_offset()) > y)
1720                 previousRow(pit, rit);
1721
1722         return rit;
1723 #endif
1724 }
1725
1726
1727 RowList::iterator LyXText::firstRow() const
1728 {
1729         return paragraphs().front().rows.begin();
1730 }
1731
1732
1733 RowList::iterator LyXText::lastRow() const
1734 {
1735         return boost::prior(endRow());
1736 }
1737
1738
1739 RowList::iterator LyXText::endRow() const
1740 {
1741         return paragraphs().back().rows.end();
1742 }
1743
1744
1745 void LyXText::nextRow(par_type & pit, RowList::iterator & rit) const
1746 {
1747         ++rit;
1748         if (rit == pars_[pit].rows.end()) {
1749                 ++pit;
1750                 if (pit == par_type(paragraphs().size()))
1751                         --pit;
1752                 else
1753                         rit = pars_[pit].rows.begin();
1754         }
1755 }
1756
1757
1758 void LyXText::previousRow(par_type & pit, RowList::iterator & rit) const
1759 {
1760         if (rit != pars_[pit].rows.begin())
1761                 --rit;
1762         else {
1763                 BOOST_ASSERT(pit != 0);
1764                 --pit;
1765                 rit = boost::prior(pars_[pit].rows.end());
1766         }
1767 }
1768
1769
1770 void LyXText::redoParagraphInternal(par_type pit)
1771 {
1772         // remove rows of paragraph, keep track of height changes
1773         height_ -= pars_[pit].height;
1774
1775         // clear old data
1776         pars_[pit].rows.clear();
1777         pars_[pit].height = 0;
1778         pars_[pit].width = 0;
1779
1780         // redo insets
1781         InsetList::iterator ii = pars_[pit].insetlist.begin();
1782         InsetList::iterator iend = pars_[pit].insetlist.end();
1783         for (; ii != iend; ++ii) {
1784                 Dimension dim;
1785                 int const w = maxwidth_ - leftMargin(pit) - rightMargin(pars_[pit]);
1786                 MetricsInfo mi(bv(), getFont(pit, ii->pos), w);
1787                 ii->inset->metrics(mi, dim);
1788         }
1789
1790         // rebreak the paragraph
1791         pars_[pit].setBeginOfBody();
1792         pos_type z = 0;
1793         do {
1794                 Row row(z);
1795                 rowBreakPoint(pit, row);
1796                 setRowWidth(pit, row);
1797                 setHeightOfRow(pit, row);
1798                 row.y_offset(pars_[pit].height);
1799                 pars_[pit].rows.push_back(row);
1800                 pars_[pit].width = std::max(pars_[pit].width, row.width());
1801                 pars_[pit].height += row.height();
1802                 z = row.endpos();
1803         } while (z < pars_[pit].size());
1804
1805         height_ += pars_[pit].height;
1806         //lyxerr << "redoParagraph: " << pars_[pit].rows.size() << " rows\n";
1807 }
1808
1809
1810 void LyXText::redoParagraphs(par_type pit, par_type end)
1811 {
1812         for ( ; pit != end; ++pit)
1813                 redoParagraphInternal(pit);
1814         updateParPositions();
1815 }
1816
1817
1818 void LyXText::redoParagraph(par_type pit)
1819 {
1820         redoParagraphInternal(pit);
1821         updateParPositions();
1822 }
1823
1824
1825 void LyXText::fullRebreak()
1826 {
1827         redoParagraphs(0, paragraphs().size());
1828         bv()->cursor().resetAnchor();
1829 }
1830
1831
1832 void LyXText::metrics(MetricsInfo & mi, Dimension & dim)
1833 {
1834         //BOOST_ASSERT(mi.base.textwidth);
1835         if (mi.base.textwidth)
1836                 maxwidth_ = mi.base.textwidth;
1837         //lyxerr << "LyXText::metrics: width: " << mi.base.textwidth
1838         //<< " maxWidth: " << maxwidth << "\nfont: " << mi.base.font
1839         //<< endl;
1840
1841         // Rebuild row cache. This recomputes height as well.
1842         redoParagraphs(0, paragraphs().size());
1843
1844         width_ = maxParagraphWidth(paragraphs());
1845
1846         // final dimension
1847         dim.asc = firstRow()->ascent_of_text();
1848         dim.des = height_ - dim.asc;
1849         dim.wid = width_;
1850 }
1851
1852
1853 // only used for inset right now. should also be used for main text
1854 void LyXText::draw(PainterInfo & pi, int x, int y) const
1855 {
1856         xo_ = x;
1857         yo_ = y;
1858         paintTextInset(*this, pi, x, y);
1859 }
1860
1861
1862 // only used for inset right now. should also be used for main text
1863 void LyXText::drawSelection(PainterInfo &, int, int) const
1864 {
1865         //lyxerr << "LyXText::drawSelection at " << x << " " << y << endl;
1866 }
1867
1868
1869 bool LyXText::isLastRow(par_type pit, Row const & row) const
1870 {
1871         return row.endpos() >= pars_[pit].size()
1872                 && pit + 1 == par_type(paragraphs().size());
1873 }
1874
1875
1876 bool LyXText::isFirstRow(par_type pit, Row const & row) const
1877 {
1878         return row.pos() == 0 && pit == 0;
1879 }
1880
1881
1882 void LyXText::getWord(CursorSlice & from, CursorSlice & to,
1883         word_location const loc)
1884 {
1885         Paragraph & from_par = pars_[from.par()];
1886         switch (loc) {
1887         case lyx::WHOLE_WORD_STRICT:
1888                 if (from.pos() == 0 || from.pos() == from_par.size()
1889                     || from_par.isSeparator(from.pos())
1890                     || from_par.isKomma(from.pos())
1891                     || from_par.isNewline(from.pos())
1892                     || from_par.isSeparator(from.pos() - 1)
1893                     || from_par.isKomma(from.pos() - 1)
1894                     || from_par.isNewline(from.pos() - 1)) {
1895                         to = from;
1896                         return;
1897                 }
1898                 // no break here, we go to the next
1899
1900         case lyx::WHOLE_WORD:
1901                 // Move cursor to the beginning, when not already there.
1902                 if (from.pos() && !from_par.isSeparator(from.pos() - 1)
1903                     && !(from_par.isKomma(from.pos() - 1)
1904                          || from_par.isNewline(from.pos() - 1)))
1905                         cursorLeftOneWord(bv()->cursor());
1906                 break;
1907         case lyx::PREVIOUS_WORD:
1908                 // always move the cursor to the beginning of previous word
1909                 cursorLeftOneWord(bv()->cursor());
1910                 break;
1911         case lyx::NEXT_WORD:
1912                 lyxerr << "LyXText::getWord: NEXT_WORD not implemented yet"
1913                        << endl;
1914                 break;
1915         case lyx::PARTIAL_WORD:
1916                 break;
1917         }
1918         to = from;
1919         Paragraph & to_par = pars_[to.par()];
1920         while (to.pos() < to_par.size()
1921                && !to_par.isSeparator(to.pos())
1922                && !to_par.isKomma(to.pos())
1923                && !to_par.isNewline(to.pos())
1924                && !to_par.isHfill(to.pos())
1925                && !to_par.isInset(to.pos()))
1926         {
1927                 ++to.pos();
1928         }
1929 }
1930
1931
1932 void LyXText::write(Buffer const & buf, std::ostream & os) const
1933 {
1934         ParagraphList::const_iterator pit = paragraphs().begin();
1935         ParagraphList::const_iterator end = paragraphs().end();
1936         Paragraph::depth_type dth = 0;
1937         for (; pit != end; ++pit)
1938                 pit->write(buf, os, buf.params(), dth);
1939 }
1940
1941
1942 bool LyXText::read(Buffer const & buf, LyXLex & lex)
1943 {
1944         static Change current_change;
1945
1946         bool the_end_read = false;
1947         Paragraph::depth_type depth = 0;
1948
1949         while (lex.isOK()) {
1950                 lex.nextToken();
1951                 string token = lex.getString();
1952
1953                 if (token.empty())
1954                         continue;
1955
1956                 if (token == "\\end_inset") {
1957                         the_end_read = true;
1958                         break;
1959                 }
1960
1961                 if (token == "\\end_document") {
1962 #warning Look here!
1963 #if 0
1964                         lex.printError("\\end_document read in inset! Error in document!");
1965 #endif
1966                         return false;
1967                 }
1968
1969                 // FIXME: ugly.
1970                 int unknown = 0;
1971
1972                 if (token == "\\begin_layout") {
1973                         lex.pushToken(token);
1974
1975                         Paragraph par;
1976                         par.params().depth(depth);
1977                         if (buf.params().tracking_changes)
1978                                 par.trackChanges();
1979                         par.setFont(0, LyXFont(LyXFont::ALL_INHERIT, buf.params().language));
1980                         pars_.push_back(par);
1981
1982                         // FIXME: goddamn InsetTabular makes us pass a Buffer
1983                         // not BufferParams
1984                         ::readParagraph(buf, pars_.back(), lex);
1985
1986                 } else if (token == "\\begin_deeper") {
1987                         ++depth;
1988                 } else if (token == "\\end_deeper") {
1989                         if (!depth) {
1990                                 lex.printError("\\end_deeper: " "depth is already null");
1991                         } else {
1992                                 --depth;
1993                         }
1994                 } else {
1995                         ++unknown;
1996                 }
1997
1998         }
1999         return the_end_read;
2000 }
2001
2002
2003 int LyXText::ascent() const
2004 {
2005         return firstRow()->ascent_of_text();
2006 }
2007
2008
2009 int LyXText::descent() const
2010 {
2011         return height_ - firstRow()->ascent_of_text();
2012 }
2013
2014
2015 int LyXText::cursorX(CursorSlice const & cur) const
2016 {
2017         par_type pit = cur.par();
2018         if (pars_[pit].rows.empty())
2019                 return xo_;
2020
2021         Row const & row = *pars_[pit].getRow(cur.pos());
2022         
2023         pos_type pos = cur.pos();
2024         pos_type cursor_vpos = 0;
2025
2026         RowMetrics const m = computeRowMetrics(pit, row);
2027         double x = m.x;
2028
2029         pos_type const row_pos  = row.pos();
2030         pos_type const end      = row.endpos();
2031
2032         if (end <= row_pos)
2033                 cursor_vpos = row_pos;
2034         else if (pos >= end)
2035                 cursor_vpos = isRTL(pars_[pit]) ? row_pos : end;
2036         else if (pos > row_pos && pos >= end)
2037                 // Place cursor after char at (logical) position pos - 1
2038                 cursor_vpos = (bidi.level(pos - 1) % 2 == 0)
2039                         ? bidi.log2vis(pos - 1) + 1 : bidi.log2vis(pos - 1);
2040         else
2041                 // Place cursor before char at (logical) position pos
2042                 cursor_vpos = (bidi.level(pos) % 2 == 0)
2043                         ? bidi.log2vis(pos) : bidi.log2vis(pos) + 1;
2044
2045         pos_type body_pos = pars_[pit].beginOfBody();
2046         if (body_pos > 0 &&
2047             (body_pos > end || !pars_[pit].isLineSeparator(body_pos - 1)))
2048                 body_pos = 0;
2049
2050         for (pos_type vpos = row_pos; vpos < cursor_vpos; ++vpos) {
2051                 pos_type pos = bidi.vis2log(vpos);
2052                 if (body_pos > 0 && pos == body_pos - 1) {
2053                         x += m.label_hfill
2054                                 + font_metrics::width(pars_[pit].layout()->labelsep,
2055                                                       getLabelFont(pit));
2056                         if (pars_[pit].isLineSeparator(body_pos - 1))
2057                                 x -= singleWidth(pit, body_pos - 1);
2058                 }
2059
2060                 if (hfillExpansion(pars_[pit], row, pos)) {
2061                         x += singleWidth(pit, pos);
2062                         if (pos >= body_pos)
2063                                 x += m.hfill;
2064                         else
2065                                 x += m.label_hfill;
2066                 } else if (pars_[pit].isSeparator(pos)) {
2067                         x += singleWidth(pit, pos);
2068                         if (pos >= body_pos)
2069                                 x += m.separator;
2070                 } else
2071                         x += singleWidth(pit, pos);
2072         }
2073         return xo_ + int(x);
2074 }
2075
2076
2077 int LyXText::cursorY(CursorSlice const & cur) const
2078 {
2079         Paragraph & par = getPar(cur.par());
2080         Row & row = *par.getRow(cur.pos());
2081         return yo_ + par.y + row.y_offset() + row.baseline();
2082 }
2083
2084
2085 // Returns the current font and depth as a message.
2086 string LyXText::currentState(LCursor & cur)
2087 {
2088         BOOST_ASSERT(this == cur.text());
2089         Buffer * buffer = bv()->buffer();
2090         Paragraph const & par = cur.paragraph();
2091         std::ostringstream os;
2092
2093         bool const show_change = buffer->params().tracking_changes
2094                 && cur.pos() != cur.lastpos()
2095                 && par.lookupChange(cur.pos()) != Change::UNCHANGED;
2096
2097         if (show_change) {
2098                 Change change = par.lookupChangeFull(cur.pos());
2099                 Author const & a = buffer->params().authors().get(change.author);
2100                 os << _("Change: ") << a.name();
2101                 if (!a.email().empty())
2102                         os << " (" << a.email() << ")";
2103                 if (change.changetime)
2104                         os << _(" at ") << ctime(&change.changetime);
2105                 os << " : ";
2106         }
2107
2108         // I think we should only show changes from the default
2109         // font. (Asger)
2110         LyXFont font = real_current_font;
2111         font.reduce(buffer->params().getLyXTextClass().defaultfont());
2112
2113         // avoid _(...) re-entrance problem
2114         string const s = font.stateText(&buffer->params());
2115         os << bformat(_("Font: %1$s"), s);
2116
2117         // os << bformat(_("Font: %1$s"), font.stateText(&buffer->params));
2118
2119         // The paragraph depth
2120         int depth = cur.paragraph().getDepth();
2121         if (depth > 0)
2122                 os << bformat(_(", Depth: %1$s"), tostr(depth));
2123
2124         // The paragraph spacing, but only if different from
2125         // buffer spacing.
2126         Spacing const & spacing = par.params().spacing();
2127         if (!spacing.isDefault()) {
2128                 os << _(", Spacing: ");
2129                 switch (spacing.getSpace()) {
2130                 case Spacing::Single:
2131                         os << _("Single");
2132                         break;
2133                 case Spacing::Onehalf:
2134                         os << _("OneHalf");
2135                         break;
2136                 case Spacing::Double:
2137                         os << _("Double");
2138                         break;
2139                 case Spacing::Other:
2140                         os << _("Other (") << spacing.getValue() << ')';
2141                         break;
2142                 case Spacing::Default:
2143                         // should never happen, do nothing
2144                         break;
2145                 }
2146         }
2147 #ifdef DEVEL_VERSION
2148         os << _(", Paragraph: ") << par.id();
2149         os << _(", Position: ") << cur.pos();
2150         Row & row = cur.textRow();
2151         os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
2152         os << _(", Inset: ") << par.inInset();
2153 #endif
2154         return os.str();
2155 }
2156
2157
2158 string LyXText::getPossibleLabel(LCursor & cur) const
2159 {
2160         par_type pit = cur.par();
2161
2162         LyXLayout_ptr layout = pars_[pit].layout();
2163
2164         if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
2165                 LyXLayout_ptr const & layout2 = pars_[pit - 1].layout();
2166                 if (layout2->latextype != LATEX_PARAGRAPH) {
2167                         --pit;
2168                         layout = layout2;
2169                 }
2170         }
2171
2172         string text = layout->latexname().substr(0, 3);
2173         if (layout->latexname() == "theorem")
2174                 text = "thm"; // Create a correct prefix for prettyref
2175
2176         text += ':';
2177         if (layout->latextype == LATEX_PARAGRAPH || lyxrc.label_init_length < 0)
2178                 text.erase();
2179
2180         string par_text = pars_[pit].asString(*cur.bv().buffer(), false);
2181         for (int i = 0; i < lyxrc.label_init_length; ++i) {
2182                 if (par_text.empty())
2183                         break;
2184                 string head;
2185                 par_text = split(par_text, head, ' ');
2186                 // Is it legal to use spaces in labels ?
2187                 if (i > 0)
2188                         text += '-';
2189                 text += head;
2190         }
2191
2192         return text;
2193 }
2194
2195
2196 int LyXText::dist(int x, int y) const
2197 {
2198         int xx = 0;
2199         int yy = 0;
2200
2201         if (x < xo_)
2202                 xx = xo_ - x;
2203         else if (x > xo_ + int(width_))
2204                 xx = x - xo_ - width_;
2205
2206         if (y < yo_ - ascent())
2207                 yy = yo_ - ascent() - y;
2208         else if (y > yo_ + descent())
2209                 yy = y - yo_ - descent();
2210
2211         return xx + yy;
2212 }