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