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