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