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