]> git.lyx.org Git - lyx.git/blob - src/text.C
remove a warning
[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 increase but not
600         // decrease the height. Just some point to start with so we don't have to
601         // do the assignment below too often.
602         LyXFont font = getFont(pit, row.pos());
603         LyXFont::FONT_SIZE const tmpsize = font.size();
604         font = getLayoutFont(pit);
605         LyXFont::FONT_SIZE const size = font.size();
606         font.setSize(tmpsize);
607
608         LyXFont labelfont = getLabelFont(pit);
609
610         // these are minimum values
611         double const spacing_val = layout->spacing.getValue() * spacing(*pit);
612         //lyxerr << "spacing_val = " << spacing_val << endl;
613         int maxasc  = int(font_metrics::maxAscent(font)  * spacing_val);
614         int maxdesc = int(font_metrics::maxDescent(font) * spacing_val);
615
616         // insets may be taller
617         InsetList::iterator ii = pit->insetlist.begin();
618         InsetList::iterator iend = pit->insetlist.end();
619         for ( ; ii != iend; ++ii) {
620                 if (ii->pos >= row.pos() && ii->pos < row.endpos()) {
621                         maxasc  = max(maxasc,  ii->inset->ascent());
622                         maxdesc = max(maxdesc, ii->inset->descent());
623                 }
624         }
625
626         // Check if any custom fonts are larger (Asger)
627         // This is not completely correct, but we can live with the small,
628         // cosmetic error for now.
629         int labeladdon = 0;
630         pos_type const pos_end = row.endpos();
631
632         LyXFont::FONT_SIZE maxsize =
633                 pit->highestFontInRange(row.pos(), pos_end, size);
634         if (maxsize > font.size()) {
635                 font.setSize(maxsize);
636                 maxasc  = max(maxasc,  font_metrics::maxAscent(font));
637                 maxdesc = max(maxdesc, font_metrics::maxDescent(font));
638         }
639
640         // This is nicer with box insets:
641         ++maxasc;
642         ++maxdesc;
643
644         row.ascent_of_text(maxasc);
645
646         // is it a top line?
647         if (row.pos() == 0) {
648                 BufferParams const & bufparams = bv()->buffer()->params();
649                 // some parksips VERY EASY IMPLEMENTATION
650                 if (bv()->buffer()->params().paragraph_separation
651                     == BufferParams::PARSEP_SKIP
652                         && pit != paragraphs().begin()
653                         && ((layout->isParagraph() && pit->getDepth() == 0)
654                             || (boost::prior(pit)->layout()->isParagraph()
655                                 && boost::prior(pit)->getDepth() == 0)))
656                 {
657                                 maxasc += bufparams.getDefSkip().inPixels(*bv());
658                 }
659
660                 if (pit->params().startOfAppendix())
661                         maxasc += int(3 * dh);
662
663                 // This is special code for the chapter, since the label of this
664                 // layout is printed in an extra row
665                 if (layout->counter == "chapter" && bufparams.secnumdepth >= 0) {
666                         labeladdon = int(font_metrics::maxHeight(labelfont)
667                                      * layout->spacing.getValue() * spacing(*pit));
668                 }
669
670                 // special code for the top label
671                 if ((layout->labeltype == LABEL_TOP_ENVIRONMENT
672                      || layout->labeltype == LABEL_BIBLIO
673                      || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
674                     && isFirstInSequence(pit, paragraphs())
675                     && !pit->getLabelstring().empty())
676                 {
677                         labeladdon = int(
678                                   font_metrics::maxHeight(labelfont)
679                                         * layout->spacing.getValue()
680                                         * spacing(*pit)
681                                 + (layout->topsep + layout->labelbottomsep) * dh);
682                 }
683
684                 // Add the layout spaces, for example before and after
685                 // a section, or between the items of a itemize or enumerate
686                 // environment.
687
688                 ParagraphList::iterator prev =
689                         depthHook(pit, paragraphs(), pit->getDepth());
690                 if (prev != pit
691                     && prev->layout() == layout
692                     && prev->getDepth() == pit->getDepth()
693                     && prev->getLabelWidthString() == pit->getLabelWidthString())
694                 {
695                         layoutasc = layout->itemsep * dh;
696                 } else if (pit != paragraphs().begin() || row.pos() != 0) {
697                         if (layout->topsep > 0)
698                                 layoutasc = layout->topsep * dh;
699                 }
700
701                 prev = outerHook(pit, paragraphs());
702                 if (prev != paragraphs().end()) {
703                         maxasc += int(prev->layout()->parsep * dh);
704                 } else if (pit != paragraphs().begin()) {
705                         ParagraphList::iterator prior_pit = boost::prior(pit);
706                         if (prior_pit->getDepth() != 0 ||
707                                         prior_pit->layout() == layout) {
708                                 maxasc += int(layout->parsep * dh);
709                         }
710                 }
711         }
712
713         // is it a bottom line?
714         if (row.endpos() >= pit->size()) {
715                 // add the layout spaces, for example before and after
716                 // a section, or between the items of a itemize or enumerate
717                 // environment
718                 ParagraphList::iterator nextpit = boost::next(pit);
719                 if (nextpit != paragraphs().end()) {
720                         ParagraphList::iterator cpit = pit;
721                         double usual = 0;
722                         double unusual = 0;
723
724                         if (cpit->getDepth() > nextpit->getDepth()) {
725                                 usual = cpit->layout()->bottomsep * dh;
726                                 cpit = depthHook(cpit, paragraphs(), nextpit->getDepth());
727                                 if (cpit->layout() != nextpit->layout()
728                                         || nextpit->getLabelWidthString() != cpit->getLabelWidthString())
729                                 {
730                                         unusual = cpit->layout()->bottomsep * dh;
731                                 }
732                                 layoutdesc = max(unusual, usual);
733                         } else if (cpit->getDepth() == nextpit->getDepth()) {
734                                 if (cpit->layout() != nextpit->layout()
735                                         || nextpit->getLabelWidthString() != cpit->getLabelWidthString())
736                                         layoutdesc = int(cpit->layout()->bottomsep * dh);
737                         }
738                 }
739         }
740
741         // incalculate the layout spaces
742         maxasc  += int(layoutasc  * 2 / (2 + pit->getDepth()));
743         maxdesc += int(layoutdesc * 2 / (2 + pit->getDepth()));
744
745         row.height(maxasc + maxdesc + labeladdon);
746         row.baseline(maxasc + labeladdon);
747         row.top_of_text(row.baseline() - font_metrics::maxAscent(font));
748 }
749
750
751 void LyXText::breakParagraph(ParagraphList & paragraphs, char keep_layout)
752 {
753         // allow only if at start or end, or all previous is new text
754         ParagraphList::iterator cpit = cursorPar();
755         if (cursor.pos() && cursor.pos() != cpit->size()
756             && cpit->isChangeEdited(0, cursor.pos()))
757                 return;
758
759         LyXTextClass const & tclass =
760                 bv()->buffer()->params().getLyXTextClass();
761         LyXLayout_ptr const & layout = cpit->layout();
762
763         // this is only allowed, if the current paragraph is not empty or caption
764         // and if it has not the keepempty flag active
765         if (cpit->empty() && !cpit->allowEmpty()
766            && layout->labeltype != LABEL_SENSITIVE)
767                 return;
768
769         recUndo(cursor.par());
770
771         // Always break behind a space
772         //
773         // It is better to erase the space (Dekel)
774         if (cursor.pos() < cpit->size() && cpit->isLineSeparator(cursor.pos()))
775                 cpit->erase(cursor.pos());
776
777         // break the paragraph
778         if (keep_layout)
779                 keep_layout = 2;
780         else
781                 keep_layout = layout->isEnvironment();
782
783         // we need to set this before we insert the paragraph. IMO the
784         // breakParagraph call should return a bool if it inserts the
785         // paragraph before or behind and we should react on that one
786         // but we can fix this in 1.3.0 (Jug 20020509)
787         bool const isempty = cpit->allowEmpty() && cpit->empty();
788         ::breakParagraph(bv()->buffer()->params(), paragraphs, cpit,
789                          cursor.pos(), keep_layout);
790
791         cpit = cursorPar();
792         ParagraphList::iterator next_par = boost::next(cpit);
793
794         // well this is the caption hack since one caption is really enough
795         if (layout->labeltype == LABEL_SENSITIVE) {
796                 if (!cursor.pos())
797                         // set to standard-layout
798                         cpit->applyLayout(tclass.defaultLayout());
799                 else
800                         // set to standard-layout
801                         next_par->applyLayout(tclass.defaultLayout());
802         }
803
804         // if the cursor is at the beginning of a row without prior newline,
805         // move one row up!
806         // This touches only the screen-update. Otherwise we would may have
807         // an empty row on the screen
808         RowList::iterator crit = cpit->getRow(cursor.pos());
809         if (cursor.pos() && crit->pos() == cursor.pos()
810             && !cpit->isNewline(cursor.pos() - 1))
811         {
812                 cursorLeft(bv());
813         }
814
815         while (!next_par->empty() && next_par->isNewline(0))
816                 next_par->erase(0);
817
818         updateCounters();
819         redoParagraph(cpit);
820         redoParagraph(next_par);
821
822         // This check is necessary. Otherwise the new empty paragraph will
823         // be deleted automatically. And it is more friendly for the user!
824         if (cursor.pos() || isempty)
825                 setCursor(next_par, 0);
826         else
827                 setCursor(cpit, 0);
828 }
829
830
831 // convenience function
832 void LyXText::redoParagraph()
833 {
834         clearSelection();
835         redoParagraph(cursorPar());
836         setCursorIntern(cursor.par(), cursor.pos());
837 }
838
839
840 // insert a character, moves all the following breaks in the
841 // same Paragraph one to the right and make a rebreak
842 void LyXText::insertChar(char c)
843 {
844         recordUndo(Undo::INSERT, this, cursor.par(), cursor.par());
845
846         // When the free-spacing option is set for the current layout,
847         // disable the double-space checking
848
849         bool const freeSpacing = cursorPar()->layout()->free_spacing ||
850                 cursorPar()->isFreeSpacing();
851
852         if (lyxrc.auto_number) {
853                 static string const number_operators = "+-/*";
854                 static string const number_unary_operators = "+-";
855                 static string const number_seperators = ".,:";
856
857                 if (current_font.number() == LyXFont::ON) {
858                         if (!IsDigit(c) && !contains(number_operators, c) &&
859                             !(contains(number_seperators, c) &&
860                               cursor.pos() >= 1 &&
861                               cursor.pos() < cursorPar()->size() &&
862                               getFont(cursorPar(), cursor.pos()).number() == LyXFont::ON &&
863                               getFont(cursorPar(), cursor.pos() - 1).number() == LyXFont::ON)
864                            )
865                                 number(); // Set current_font.number to OFF
866                 } else if (IsDigit(c) &&
867                            real_current_font.isVisibleRightToLeft()) {
868                         number(); // Set current_font.number to ON
869
870                         if (cursor.pos() > 0) {
871                                 char const c = cursorPar()->getChar(cursor.pos() - 1);
872                                 if (contains(number_unary_operators, c) &&
873                                     (cursor.pos() == 1 ||
874                                      cursorPar()->isSeparator(cursor.pos() - 2) ||
875                                      cursorPar()->isNewline(cursor.pos() - 2))
876                                   ) {
877                                         setCharFont(
878                                                     cursorPar(),
879                                                     cursor.pos() - 1,
880                                                     current_font);
881                                 } else if (contains(number_seperators, c) &&
882                                            cursor.pos() >= 2 &&
883                                            getFont(
884                                                    cursorPar(),
885                                                    cursor.pos() - 2).number() == LyXFont::ON) {
886                                         setCharFont(
887                                                     cursorPar(),
888                                                     cursor.pos() - 1,
889                                                     current_font);
890                                 }
891                         }
892                 }
893         }
894
895         // First check, if there will be two blanks together or a blank at
896         // the beginning of a paragraph.
897         // I decided to handle blanks like normal characters, the main
898         // difference are the special checks when calculating the row.fill
899         // (blank does not count at the end of a row) and the check here
900
901         // The bug is triggered when we type in a description environment:
902         // The current_font is not changed when we go from label to main text
903         // and it should (along with realtmpfont) when we type the space.
904         // CHECK There is a bug here! (Asger)
905
906         // store the current font.  This is because of the use of cursor
907         // movements. The moving cursor would refresh the current font
908         LyXFont realtmpfont = real_current_font;
909         LyXFont rawtmpfont = current_font;
910
911         if (!freeSpacing && IsLineSeparatorChar(c)) {
912                 if ((cursor.pos() > 0
913                      && cursorPar()->isLineSeparator(cursor.pos() - 1))
914                     || (cursor.pos() > 0
915                         && cursorPar()->isNewline(cursor.pos() - 1))
916                     || (cursor.pos() == 0)) {
917                         static bool sent_space_message = false;
918                         if (!sent_space_message) {
919                                 if (cursor.pos() == 0)
920                                         bv()->owner()->message(_("You cannot insert a space at the beginning of a paragraph. Please read the Tutorial."));
921                                 else
922                                         bv()->owner()->message(_("You cannot type two spaces this way. Please read the Tutorial."));
923                                 sent_space_message = true;
924                         }
925                         charInserted();
926                         return;
927                 }
928         }
929
930         // Here case LyXText::InsertInset already inserted the character
931         if (c != Paragraph::META_INSET)
932                 cursorPar()->insertChar(cursor.pos(), c);
933
934         setCharFont(cursorPar(), cursor.pos(), rawtmpfont);
935
936         current_font = rawtmpfont;
937         real_current_font = realtmpfont;
938         redoParagraph(cursorPar());
939         setCursor(cursor.par(), cursor.pos() + 1, false, cursor.boundary());
940
941         charInserted();
942 }
943
944
945 void LyXText::charInserted()
946 {
947         // Here we call finishUndo for every 20 characters inserted.
948         // This is from my experience how emacs does it. (Lgb)
949         static unsigned int counter;
950         if (counter < 20) {
951                 ++counter;
952         } else {
953                 finishUndo();
954                 counter = 0;
955         }
956 }
957
958
959 void LyXText::prepareToPrint(ParagraphList::iterator pit, Row & row) const
960 {
961         double w = row.fill();
962         double fill_hfill = 0;
963         double fill_label_hfill = 0;
964         double fill_separator = 0;
965         double x = 0;
966
967         bool const is_rtl =
968                 pit->isRightToLeftPar(bv()->buffer()->params());
969         if (is_rtl)
970                 x = rightMargin(*pit);
971         else
972                 x = leftMargin(pit, row.pos());
973
974         // is there a manual margin with a manual label
975         LyXLayout_ptr const & layout = pit->layout();
976
977         if (layout->margintype == MARGIN_MANUAL
978             && layout->labeltype == LABEL_MANUAL) {
979                 /// We might have real hfills in the label part
980                 int nlh = numberOfLabelHfills(*pit, row);
981
982                 // A manual label par (e.g. List) has an auto-hfill
983                 // between the label text and the body of the
984                 // paragraph too.
985                 // But we don't want to do this auto hfill if the par
986                 // is empty.
987                 if (!pit->empty())
988                         ++nlh;
989
990                 if (nlh && !pit->getLabelWidthString().empty())
991                         fill_label_hfill = labelFill(pit, row) / double(nlh);
992         }
993
994         // are there any hfills in the row?
995         int const nh = numberOfHfills(*pit, row);
996
997         if (nh) {
998                 if (w > 0)
999                         fill_hfill = w / nh;
1000         // we don't have to look at the alignment if it is ALIGN_LEFT and
1001         // if the row is already larger then the permitted width as then
1002         // we force the LEFT_ALIGN'edness!
1003         } else if (int(row.width()) < textWidth()) {
1004                 // is it block, flushleft or flushright?
1005                 // set x how you need it
1006                 int align;
1007                 if (pit->params().align() == LYX_ALIGN_LAYOUT)
1008                         align = layout->align;
1009                 else
1010                         align = pit->params().align();
1011
1012                 // Display-style insets should always be on a centred row
1013                 // The test on pit->size() is to catch zero-size pars, which
1014                 // would trigger the assert in Paragraph::getInset().
1015                 //inset = pit->size() ? pit->getInset(row.pos()) : 0;
1016                 if (!pit->empty()
1017                     && pit->isInset(row.pos())
1018                     && pit->getInset(row.pos())->display())
1019                 {
1020                         align = LYX_ALIGN_CENTER;
1021                 }
1022
1023                 switch (align) {
1024     case LYX_ALIGN_BLOCK: {
1025                                 int const ns = numberOfSeparators(*pit, row);
1026                                 bool disp_inset = false;
1027                                 if (row.endpos() < pit->size()) {
1028                                         InsetOld * in = pit->getInset(row.endpos());
1029                                         if (in)
1030                                                 disp_inset = in->display();
1031                                 }
1032                                 // If we have separators, this is not the last row of a
1033                                 // par, does not end in newline, and is not row above a
1034                                 // display inset... then stretch it
1035                                 if (ns
1036                                         && row.endpos() < pit->size()
1037                                         && !pit->isNewline(row.endpos() - 1)
1038                                         && !disp_inset
1039                                         ) {
1040                                                 fill_separator = w / ns;
1041                                 } else if (is_rtl) {
1042                                         x += w;
1043                                 }
1044                                 break;
1045                         }
1046     case LYX_ALIGN_RIGHT:
1047                         x += w;
1048                         break;
1049     case LYX_ALIGN_CENTER:
1050                         x += w / 2;
1051                         break;
1052                 }
1053         }
1054
1055         bidi.computeTables(*pit, *bv()->buffer(), row);
1056         if (is_rtl) {
1057                 pos_type body_pos = pit->beginOfBody();
1058                 pos_type end = row.endpos();
1059
1060                 if (body_pos > 0
1061                     && (body_pos > end || !pit->isLineSeparator(body_pos - 1)))
1062                 {
1063                         x += font_metrics::width(layout->labelsep, getLabelFont(pit));
1064                         if (body_pos <= end)
1065                                 x += fill_label_hfill;
1066                 }
1067         }
1068
1069         row.fill_hfill(fill_hfill);
1070         row.fill_label_hfill(fill_label_hfill);
1071         row.fill_separator(fill_separator);
1072         row.x(x);
1073 }
1074
1075
1076 // the cursor set functions have a special mechanism. When they
1077 // realize, that you left an empty paragraph, they will delete it.
1078
1079 void LyXText::cursorRightOneWord()
1080 {
1081         cursorRightOneWord(cursor);
1082         setCursor(cursorPar(), cursor.pos());
1083 }
1084
1085
1086 // Skip initial whitespace at end of word and move cursor to *start*
1087 // of prior word, not to end of next prior word.
1088 void LyXText::cursorLeftOneWord()
1089 {
1090         LyXCursor tmpcursor = cursor;
1091         cursorLeftOneWord(tmpcursor);
1092         setCursor(getPar(tmpcursor), tmpcursor.pos());
1093 }
1094
1095
1096 void LyXText::selectWord(word_location loc)
1097 {
1098         LyXCursor from = cursor;
1099         LyXCursor to = cursor;
1100         getWord(from, to, loc);
1101         if (cursor != from)
1102                 setCursor(from.par(), from.pos());
1103         if (to == from)
1104                 return;
1105         selection.cursor = cursor;
1106         setCursor(to.par(), to.pos());
1107         setSelection();
1108 }
1109
1110
1111 // Select the word currently under the cursor when no
1112 // selection is currently set
1113 bool LyXText::selectWordWhenUnderCursor(word_location loc)
1114 {
1115         if (!selection.set()) {
1116                 selectWord(loc);
1117                 return selection.set();
1118         }
1119         return false;
1120 }
1121
1122
1123 void LyXText::acceptChange()
1124 {
1125         if (!selection.set() && cursorPar()->size())
1126                 return;
1127
1128         if (selStart().par() == selEnd().par()) {
1129                 LyXCursor const & startc = selStart();
1130                 LyXCursor const & endc = selEnd();
1131                 recordUndo(Undo::INSERT, this, startc.par());
1132                 getPar(startc)->acceptChange(startc.pos(), endc.pos());
1133                 finishUndo();
1134                 clearSelection();
1135                 redoParagraph(getPar(startc));
1136                 setCursorIntern(startc.par(), 0);
1137         }
1138 #warning handle multi par selection
1139 }
1140
1141
1142 void LyXText::rejectChange()
1143 {
1144         if (!selection.set() && cursorPar()->size())
1145                 return;
1146
1147         if (selStart().par() == selEnd().par()) {
1148                 LyXCursor const & startc = selStart();
1149                 LyXCursor const & endc = selEnd();
1150                 recordUndo(Undo::INSERT, this, startc.par());
1151                 getPar(startc)->rejectChange(startc.pos(), endc.pos());
1152                 finishUndo();
1153                 clearSelection();
1154                 redoParagraph(getPar(startc));
1155                 setCursorIntern(startc.par(), 0);
1156         }
1157 #warning handle multi par selection
1158 }
1159
1160
1161 // Delete from cursor up to the end of the current or next word.
1162 void LyXText::deleteWordForward()
1163 {
1164         if (cursorPar()->empty())
1165                 cursorRight(bv());
1166         else {
1167                 LyXCursor tmpcursor = cursor;
1168                 selection.set(true); // to avoid deletion
1169                 cursorRightOneWord();
1170                 setCursor(tmpcursor, tmpcursor.par(), tmpcursor.pos());
1171                 selection.cursor = cursor;
1172                 cursor = tmpcursor;
1173                 setSelection();
1174                 cutSelection(true, false);
1175         }
1176 }
1177
1178
1179 // Delete from cursor to start of current or prior word.
1180 void LyXText::deleteWordBackward()
1181 {
1182         if (cursorPar()->empty())
1183                 cursorLeft(bv());
1184         else {
1185                 LyXCursor tmpcursor = cursor;
1186                 selection.set(true); // to avoid deletion
1187                 cursorLeftOneWord();
1188                 setCursor(tmpcursor, tmpcursor.par(), tmpcursor.pos());
1189                 selection.cursor = cursor;
1190                 cursor = tmpcursor;
1191                 setSelection();
1192                 cutSelection(true, false);
1193         }
1194 }
1195
1196
1197 // Kill to end of line.
1198 void LyXText::deleteLineForward()
1199 {
1200         if (cursorPar()->empty()) {
1201                 // Paragraph is empty, so we just go to the right
1202                 cursorRight(bv());
1203         } else {
1204                 LyXCursor tmpcursor = cursor;
1205                 selection.set(true); // to avoid deletion
1206                 cursorEnd();
1207                 setCursor(tmpcursor, tmpcursor.par(), tmpcursor.pos());
1208                 selection.cursor = cursor;
1209                 cursor = tmpcursor;
1210                 setSelection();
1211                 // What is this test for ??? (JMarc)
1212                 if (!selection.set())
1213                         deleteWordForward();
1214                 else
1215                         cutSelection(true, false);
1216         }
1217 }
1218
1219
1220 void LyXText::changeCase(LyXText::TextCase action)
1221 {
1222         LyXCursor from;
1223         LyXCursor to;
1224
1225         if (selection.set()) {
1226                 from = selStart();
1227                 to = selEnd();
1228         } else {
1229                 from = cursor;
1230                 getWord(from, to, lyx::PARTIAL_WORD);
1231                 setCursor(to.par(), to.pos() + 1);
1232         }
1233
1234         recordUndo(Undo::ATOMIC, this, from.par(), to.par());
1235
1236         pos_type pos = from.pos();
1237         int par = from.par();
1238
1239         while (par != int(paragraphs().size()) &&
1240                (pos != to.pos() || par != to.par())) {
1241                 ParagraphList::iterator pit = getPar(par);
1242                 if (pos == pit->size()) {
1243                         ++par;
1244                         pos = 0;
1245                         continue;
1246                 }
1247                 unsigned char c = pit->getChar(pos);
1248                 if (c != Paragraph::META_INSET) {
1249                         switch (action) {
1250                         case text_lowercase:
1251                                 c = lowercase(c);
1252                                 break;
1253                         case text_capitalization:
1254                                 c = uppercase(c);
1255                                 action = text_lowercase;
1256                                 break;
1257                         case text_uppercase:
1258                                 c = uppercase(c);
1259                                 break;
1260                         }
1261                 }
1262 #warning changes
1263                 pit->setChar(pos, c);
1264                 ++pos;
1265         }
1266 }
1267
1268
1269 void LyXText::Delete()
1270 {
1271         // this is a very easy implementation
1272         LyXCursor old_cursor = cursor;
1273
1274         // just move to the right
1275         cursorRight(true);
1276
1277         // if you had success make a backspace
1278         if (old_cursor.par() != cursor.par() || old_cursor.pos() != cursor.pos()) {
1279                 recordUndo(Undo::DELETE, this, old_cursor.par());
1280                 backspace();
1281         }
1282 }
1283
1284
1285 void LyXText::backspace()
1286 {
1287         // Get the font that is used to calculate the baselineskip
1288         ParagraphList::iterator pit = cursorPar();
1289         pos_type lastpos = pit->size();
1290
1291         if (cursor.pos() == 0) {
1292                 // The cursor is at the beginning of a paragraph,
1293                 // so the the backspace will collapse two paragraphs into one.
1294
1295                 // but it's not allowed unless it's new
1296                 if (pit->isChangeEdited(0, pit->size()))
1297                         return;
1298
1299                 // we may paste some paragraphs
1300
1301                 // is it an empty paragraph?
1302
1303                 if (lastpos == 0 || (lastpos == 1 && pit->isSeparator(0))) {
1304                         // This is an empty paragraph and we delete it just
1305                         // by moving the cursor one step
1306                         // left and let the DeleteEmptyParagraphMechanism
1307                         // handle the actual deletion of the paragraph.
1308
1309                         if (cursor.par()) {
1310                                 cursorLeft(bv());
1311                                 // the layout things can change the height of a row !
1312                                 redoParagraph();
1313                                 return;
1314                         }
1315                 }
1316
1317                 if (cursor.par() != 0)
1318                         recordUndo(Undo::DELETE, this, cursor.par() - 1, cursor.par());
1319
1320                 ParagraphList::iterator tmppit = cursorPar();
1321                 // We used to do cursorLeftIntern() here, but it is
1322                 // not a good idea since it triggers the auto-delete
1323                 // mechanism. So we do a cursorLeftIntern()-lite,
1324                 // without the dreaded mechanism. (JMarc)
1325                 if (cursor.par() != 0) {
1326                         // steps into the above paragraph.
1327                         setCursorIntern(cursor.par() - 1,
1328                                         getPar(cursor.par() - 1)->size(),
1329                                         false);
1330                 }
1331
1332                 // Pasting is not allowed, if the paragraphs have different
1333                 // layout. I think it is a real bug of all other
1334                 // word processors to allow it. It confuses the user.
1335                 // Correction: Pasting is always allowed with standard-layout
1336                 Buffer & buf = *bv()->buffer();
1337                 BufferParams const & bufparams = buf.params();
1338                 LyXTextClass const & tclass = bufparams.getLyXTextClass();
1339                 ParagraphList::iterator const cpit = cursorPar();
1340
1341                 if (cpit != tmppit
1342                     && (cpit->layout() == tmppit->layout()
1343                         || tmppit->layout() == tclass.defaultLayout())
1344                     && cpit->getAlign() == tmppit->getAlign()) {
1345                         mergeParagraph(bufparams, buf.paragraphs(), cpit);
1346
1347                         if (cursor.pos() && cpit->isSeparator(cursor.pos() - 1))
1348                                 cursor.pos(cursor.pos() - 1);
1349
1350                         // the counters may have changed
1351                         updateCounters();
1352                         setCursor(cursor.par(), cursor.pos(), false);
1353                 }
1354         } else {
1355                 // this is the code for a normal backspace, not pasting
1356                 // any paragraphs
1357                 recordUndo(Undo::DELETE, this, cursor.par());
1358                 // We used to do cursorLeftIntern() here, but it is
1359                 // not a good idea since it triggers the auto-delete
1360                 // mechanism. So we do a cursorLeftIntern()-lite,
1361                 // without the dreaded mechanism. (JMarc)
1362                 setCursorIntern(cursor.par(), cursor.pos() - 1,
1363                                 false, cursor.boundary());
1364                 cursorPar()->erase(cursor.pos());
1365         }
1366
1367         lastpos = cursorPar()->size();
1368         if (cursor.pos() == lastpos)
1369                 setCurrentFont();
1370
1371         redoParagraph();
1372         setCursor(cursor.par(), cursor.pos(), false, cursor.boundary());
1373 }
1374
1375
1376 ParagraphList::iterator LyXText::cursorPar() const
1377 {
1378         return getPar(cursor.par());
1379 }
1380
1381
1382 RowList::iterator LyXText::cursorRow() const
1383 {
1384         return cursorPar()->getRow(cursor.pos());
1385 }
1386
1387
1388 ParagraphList::iterator LyXText::getPar(LyXCursor const & cur) const
1389 {
1390         return getPar(cur.par());
1391 }
1392
1393
1394 ParagraphList::iterator LyXText::getPar(int par) const
1395 {
1396         BOOST_ASSERT(par >= 0);
1397         BOOST_ASSERT(par < int(paragraphs().size()));
1398         ParagraphList::iterator pit = paragraphs().begin();
1399         std::advance(pit, par);
1400         return pit;
1401 }
1402
1403
1404 RowList::iterator
1405 LyXText::getRowNearY(int y, ParagraphList::iterator & pit) const
1406 {
1407         //lyxerr << "getRowNearY: y " << y << endl;
1408 #if 1
1409         ParagraphList::iterator const
1410                 pend = boost::prior(paragraphs().end());
1411         pit = paragraphs().begin();
1412         while (int(pit->y + pit->height) < y && pit != pend)
1413                 ++pit;
1414
1415         RowList::iterator rit = pit->rows.end();
1416         RowList::iterator const rbegin = pit->rows.begin();
1417         do {
1418                 --rit;
1419         } while (rit != rbegin && int(pit->y + rit->y_offset()) > y);
1420
1421         return rit;
1422 #else
1423         pit = boost::prior(paragraphs().end());
1424
1425         RowList::iterator rit = lastRow();
1426         RowList::iterator rbegin = firstRow();
1427
1428         while (rit != rbegin && int(pit->y + rit->y_offset()) > y)
1429                 previousRow(pit, rit);
1430
1431         return rit;
1432 #endif
1433 }
1434
1435
1436 int LyXText::getDepth() const
1437 {
1438         return cursorPar()->getDepth();
1439 }
1440
1441
1442 RowList::iterator LyXText::firstRow() const
1443 {
1444         return paragraphs().front().rows.begin();
1445 }
1446
1447
1448 ParagraphList::iterator LyXText::firstPar() const
1449 {
1450         return paragraphs().begin();
1451 }
1452
1453
1454 RowList::iterator LyXText::lastRow() const
1455 {
1456         return boost::prior(endRow());
1457 }
1458
1459
1460 ParagraphList::iterator LyXText::lastPar() const
1461 {
1462         return boost::prior(endPar());
1463 }
1464
1465
1466 RowList::iterator LyXText::endRow() const
1467 {
1468         return paragraphs().back().rows.end();
1469 }
1470
1471
1472 ParagraphList::iterator LyXText::endPar() const
1473 {
1474         return paragraphs().end();
1475 }
1476
1477
1478 void LyXText::nextRow(ParagraphList::iterator & pit,
1479         RowList::iterator & rit) const
1480 {
1481         ++rit;
1482         if (rit == pit->rows.end()) {
1483                 ++pit;
1484                 if (pit == paragraphs().end())
1485                         --pit;
1486                 else
1487                         rit = pit->rows.begin();
1488         }
1489 }
1490
1491
1492 void LyXText::previousRow(ParagraphList::iterator & pit,
1493         RowList::iterator & rit) const
1494 {
1495         if (rit != pit->rows.begin())
1496                 --rit;
1497         else {
1498                 BOOST_ASSERT(pit != paragraphs().begin());
1499                 --pit;
1500                 rit = boost::prior(pit->rows.end());
1501         }
1502 }
1503
1504
1505 string LyXText::selectionAsString(Buffer const & buffer, bool label) const
1506 {
1507         if (!selection.set())
1508                 return string();
1509
1510         // should be const ...
1511         ParagraphList::iterator startpit = getPar(selStart());
1512         ParagraphList::iterator endpit = getPar(selEnd());
1513         size_t const startpos = selStart().pos();
1514         size_t const endpos = selEnd().pos();
1515
1516         if (startpit == endpit)
1517                 return startpit->asString(buffer, startpos, endpos, label);
1518
1519         // First paragraph in selection
1520         string result =
1521                 startpit->asString(buffer, startpos, startpit->size(), label) + "\n\n";
1522
1523         // The paragraphs in between (if any)
1524         ParagraphList::iterator pit = startpit;
1525         for (++pit; pit != endpit; ++pit)
1526                 result += pit->asString(buffer, 0, pit->size(), label) + "\n\n";
1527
1528         // Last paragraph in selection
1529         result += endpit->asString(buffer, 0, endpos, label);
1530
1531         return result;
1532 }
1533
1534
1535 int LyXText::parOffset(ParagraphList::iterator pit) const
1536 {
1537         return std::distance(paragraphs().begin(), pit);
1538 }
1539
1540
1541 void LyXText::redoParagraphInternal(ParagraphList::iterator pit)
1542 {
1543         // remove rows of paragraph, keep track of height changes
1544         height -= pit->height;
1545
1546         // clear old data
1547         pit->rows.clear();
1548         pit->height = 0;
1549         pit->width = 0;
1550
1551         // redo insets
1552         InsetList::iterator ii = pit->insetlist.begin();
1553         InsetList::iterator iend = pit->insetlist.end();
1554         for (; ii != iend; ++ii) {
1555                 Dimension dim;
1556                 int const w = textWidth() - leftMargin(pit) - rightMargin(*pit);
1557                 MetricsInfo mi(bv(), getFont(pit, ii->pos), w);
1558                 ii->inset->metrics(mi, dim);
1559         }
1560
1561         // rebreak the paragraph
1562         pit->setBeginOfBody();
1563         pos_type z = 0;
1564         do {
1565                 Row row(z);
1566                 rowBreakPoint(pit, row);
1567                 z = row.endpos();
1568                 fill(pit, row, textwidth_);
1569                 prepareToPrint(pit, row);
1570                 setHeightOfRow(pit, row);
1571                 row.y_offset(pit->height);
1572                 pit->rows.push_back(row);
1573                 pit->width = std::max(pit->width, row.width());
1574                 pit->height += row.height();
1575         } while (z < pit->size());
1576
1577         height += pit->height;
1578         //lyxerr << "redoParagraph: " << pit->rows.size() << " rows\n";
1579 }
1580
1581
1582 void LyXText::redoParagraphs(ParagraphList::iterator pit,
1583   ParagraphList::iterator end)
1584 {
1585         for ( ; pit != end; ++pit)
1586                 redoParagraphInternal(pit);
1587         updateParPositions();
1588 }
1589
1590
1591 void LyXText::redoParagraph(ParagraphList::iterator pit)
1592 {
1593         redoParagraphInternal(pit);
1594         updateParPositions();
1595 }
1596
1597
1598 void LyXText::fullRebreak()
1599 {
1600         redoParagraphs(paragraphs().begin(), paragraphs().end());
1601         selection.cursor = cursor;
1602 }
1603
1604
1605 void LyXText::metrics(MetricsInfo & mi, Dimension & dim)
1606 {
1607         //BOOST_ASSERT(mi.base.textwidth);
1608         if (mi.base.textwidth)
1609                 textwidth_ = mi.base.textwidth;
1610         //lyxerr << "LyXText::metrics: width: " << mi.base.textwidth
1611         //      << " textWidth: " << textWidth() << "\nfont: " << mi.base.font << endl;
1612
1613         // Rebuild row cache. This recomputes height as well.
1614         redoParagraphs(paragraphs().begin(), paragraphs().end());
1615
1616         width = maxParagraphWidth(paragraphs());
1617
1618         // final dimension
1619         dim.asc = firstRow()->ascent_of_text();
1620         dim.des = height - dim.asc;
1621         dim.wid = width;
1622 }
1623
1624
1625 // only used for inset right now. should also be used for main text
1626 void LyXText::draw(PainterInfo & pi, int x, int y) const
1627 {
1628         xo_ = x;
1629         yo_ = y;
1630         paintTextInset(*this, pi, x, y);
1631 }
1632
1633
1634 bool LyXText::isLastRow(ParagraphList::iterator pit, Row const & row) const
1635 {
1636         return row.endpos() >= pit->size()
1637                && boost::next(pit) == paragraphs().end();
1638 }
1639
1640
1641 bool LyXText::isFirstRow(ParagraphList::iterator pit, Row const & row) const
1642 {
1643         return row.pos() == 0 && pit == paragraphs().begin();
1644 }
1645
1646
1647 void LyXText::cursorLeftOneWord(LyXCursor & cursor)
1648 {
1649         // treat HFills, floats and Insets as words
1650
1651         ParagraphList::iterator pit = cursorPar();
1652         size_t pos = cursor.pos();
1653
1654         while (pos &&
1655                (pit->isSeparator(pos - 1) ||
1656                 pit->isKomma(pos - 1) ||
1657                 pit->isNewline(pos - 1)) &&
1658                !(pit->isHfill(pos - 1) ||
1659                  pit->isInset(pos - 1)))
1660                 --pos;
1661
1662         if (pos &&
1663             (pit->isInset(pos - 1) ||
1664              pit->isHfill(pos - 1))) {
1665                 --pos;
1666         } else if (!pos) {
1667                 if (pit != paragraphs().begin()) {
1668                         --pit;
1669                         pos = pit->size();
1670                 }
1671         } else {                // Here, cur != 0
1672                 while (pos > 0 && pit->isWord(pos - 1))
1673                         --pos;
1674         }
1675
1676         cursor.par(parOffset(pit));
1677         cursor.pos(pos);
1678 }
1679
1680
1681 void LyXText::cursorRightOneWord(LyXCursor & cursor)
1682 {
1683         // treat floats, HFills and Insets as words
1684         ParagraphList::iterator pit = cursorPar();
1685         pos_type pos = cursor.pos();
1686
1687         if (pos == pit->size() &&
1688                 boost::next(pit) != paragraphs().end()) {
1689                 ++pit;
1690                 pos = 0;
1691         } else {
1692                 // Skip through initial nonword stuff.
1693                 while (pos < pit->size() && !pit->isWord(pos)) {
1694                         ++pos;
1695                 }
1696                 // Advance through word.
1697                 while (pos < pit->size() && pit->isWord(pos)) {
1698                         ++pos;
1699                 }
1700         }
1701
1702         cursor.par(parOffset(pit));
1703         cursor.pos(pos);
1704 }
1705
1706
1707 void LyXText::getWord(LyXCursor & from, LyXCursor & to, word_location const loc)
1708 {
1709         ParagraphList::iterator from_par = getPar(from);
1710         ParagraphList::iterator to_par = getPar(to);
1711         switch (loc) {
1712         case lyx::WHOLE_WORD_STRICT:
1713                 if (from.pos() == 0 || from.pos() == from_par->size()
1714                     || from_par->isSeparator(from.pos())
1715                     || from_par->isKomma(from.pos())
1716                     || from_par->isNewline(from.pos())
1717                     || from_par->isSeparator(from.pos() - 1)
1718                     || from_par->isKomma(from.pos() - 1)
1719                     || from_par->isNewline(from.pos() - 1)) {
1720                         to = from;
1721                         return;
1722                 }
1723                 // no break here, we go to the next
1724
1725         case lyx::WHOLE_WORD:
1726                 // Move cursor to the beginning, when not already there.
1727                 if (from.pos() && !from_par->isSeparator(from.pos() - 1)
1728                     && !(from_par->isKomma(from.pos() - 1)
1729                          || from_par->isNewline(from.pos() - 1)))
1730                         cursorLeftOneWord(from);
1731                 break;
1732         case lyx::PREVIOUS_WORD:
1733                 // always move the cursor to the beginning of previous word
1734                 cursorLeftOneWord(from);
1735                 break;
1736         case lyx::NEXT_WORD:
1737                 lyxerr << "LyXText::getWord: NEXT_WORD not implemented yet"
1738                        << endl;
1739                 break;
1740         case lyx::PARTIAL_WORD:
1741                 break;
1742         }
1743         to = from;
1744         while (to.pos() < to_par->size()
1745                && !to_par->isSeparator(to.pos())
1746                && !to_par->isKomma(to.pos())
1747                && !to_par->isNewline(to.pos())
1748                && !to_par->isHfill(to.pos())
1749                && !to_par->isInset(to.pos()))
1750         {
1751                 to.pos(to.pos() + 1);
1752         }
1753 }
1754
1755
1756 void LyXText::write(Buffer const & buf, std::ostream & os) const
1757 {
1758         ParagraphList::const_iterator pit = paragraphs().begin();
1759         ParagraphList::const_iterator end = paragraphs().end();
1760         Paragraph::depth_type dth = 0;
1761         for (; pit != end; ++pit)
1762                 pit->write(buf, os, buf.params(), dth);
1763 }
1764
1765
1766 bool LyXText::read(Buffer const & buf, LyXLex & lex)
1767 {       
1768         static Change current_change;
1769
1770         bool the_end_read = false;
1771         ParagraphList::iterator pit = paragraphs().begin();
1772         Paragraph::depth_type depth = 0;
1773
1774         while (lex.isOK()) {
1775                 lex.nextToken();
1776                 string token = lex.getString();
1777
1778                 if (token.empty())
1779                         continue;
1780
1781                 if (in_inset_) {
1782
1783                         if (token == "\\end_inset") {
1784                                 the_end_read = true;
1785                                 break;
1786                         }
1787
1788                         if (token == "\\end_document") {
1789                                 lex.printError("\\end_document read in inset! Error in document!");
1790                                 return false;
1791                         }
1792
1793                 } else {
1794
1795                         if (token == "\\end_document") {
1796                                 the_end_read = true;
1797                                 continue;
1798                         }
1799
1800                 }
1801
1802                 // FIXME: ugly.
1803                 int unknown = 0;
1804
1805                 if (token == "\\begin_layout") {
1806                         lex.pushToken(token);
1807
1808                         Paragraph par;
1809                         par.params().depth(depth);
1810                         if (buf.params().tracking_changes)
1811                                 par.trackChanges();
1812                         LyXFont f(LyXFont::ALL_INHERIT, buf.params().language);
1813                         par.setFont(0, f);
1814
1815                         // insert after
1816                         if (pit != paragraphs().end())
1817                                 ++pit;
1818
1819                         pit = paragraphs().insert(pit, par);
1820
1821                         // FIXME: goddamn InsetTabular makes us pass a Buffer
1822                         // not BufferParams
1823                         ::readParagraph(buf, *pit, lex);
1824
1825                 } else if (token == "\\begin_deeper") {
1826                         ++depth;
1827                 } else if (token == "\\end_deeper") {
1828                         if (!depth) {
1829                                 lex.printError("\\end_deeper: " "depth is already null");
1830                         } else {
1831                                 --depth;
1832                         }
1833                 } else {
1834                         ++unknown;
1835                 }
1836
1837         }
1838         return the_end_read;
1839 }
1840
1841
1842 int LyXText::ascent() const
1843 {
1844         return firstRow()->ascent_of_text();
1845 }
1846
1847
1848 int LyXText::descent() const
1849 {
1850         return height - firstRow()->ascent_of_text();
1851 }
1852
1853
1854 int LyXText::cursorX() const
1855 {
1856         return cursorX(cursor);
1857 }
1858
1859
1860 int LyXText::cursorY() const
1861 {
1862         return cursorY(cursor);
1863 }
1864
1865
1866 int LyXText::cursorX(LyXCursor const & cur) const
1867 {
1868         ParagraphList::iterator pit = getPar(cur);
1869         if (pit->rows.empty())
1870                 return 0;
1871         Row const & row         = *pit->getRow(cur.pos());
1872         pos_type pos            = cur.pos();
1873         pos_type cursor_vpos    = 0;
1874         double x                = row.x();
1875         double fill_separator   = row.fill_separator();
1876         double fill_hfill       = row.fill_hfill();
1877         double fill_label_hfill = row.fill_label_hfill();
1878         pos_type const row_pos  = row.pos();
1879         pos_type const end      = row.endpos();
1880
1881         if (end <= row_pos)
1882                 cursor_vpos = row_pos;
1883         else if (pos >= end)
1884                 cursor_vpos = (pit->isRightToLeftPar(bv()->buffer()->params()))
1885                         ? row_pos : end;
1886         else if (pos > row_pos && pos >= end)
1887                 // Place cursor after char at (logical) position pos - 1
1888                 cursor_vpos = (bidi.level(pos - 1) % 2 == 0)
1889                         ? bidi.log2vis(pos - 1) + 1 : bidi.log2vis(pos - 1);
1890         else
1891                 // Place cursor before char at (logical) position pos
1892                 cursor_vpos = (bidi.level(pos) % 2 == 0)
1893                         ? bidi.log2vis(pos) : bidi.log2vis(pos) + 1;
1894
1895         pos_type body_pos = pit->beginOfBody();
1896         if (body_pos > 0 &&
1897             (body_pos > end || !pit->isLineSeparator(body_pos - 1)))
1898                 body_pos = 0;
1899
1900         for (pos_type vpos = row_pos; vpos < cursor_vpos; ++vpos) {
1901                 pos_type pos = bidi.vis2log(vpos);
1902                 if (body_pos > 0 && pos == body_pos - 1) {
1903                         x += fill_label_hfill
1904                                 + font_metrics::width(pit->layout()->labelsep,
1905                                                       getLabelFont(pit));
1906                         if (pit->isLineSeparator(body_pos - 1))
1907                                 x -= singleWidth(pit, body_pos - 1);
1908                 }
1909
1910                 if (hfillExpansion(*pit, row, pos)) {
1911                         x += singleWidth(pit, pos);
1912                         if (pos >= body_pos)
1913                                 x += fill_hfill;
1914                         else
1915                                 x += fill_label_hfill;
1916                 } else if (pit->isSeparator(pos)) {
1917                         x += singleWidth(pit, pos);
1918                         if (pos >= body_pos)
1919                                 x += fill_separator;
1920                 } else
1921                         x += singleWidth(pit, pos);
1922         }
1923         return int(x);
1924 }
1925
1926
1927 int LyXText::cursorY(LyXCursor const & cur) const
1928 {
1929         Paragraph & par = *getPar(cur);
1930         Row & row = *par.getRow(cur.pos());
1931         return par.y + row.y_offset() + row.baseline();
1932 }
1933