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