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