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