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