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