]> git.lyx.org Git - lyx.git/blob - src/text.C
small stuff, whitespace & consistent naming
[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 "encoding.h"
26 #include "funcrequest.h"
27 #include "gettext.h"
28 #include "language.h"
29 #include "LColor.h"
30 #include "lyxlength.h"
31 #include "lyxrc.h"
32 #include "lyxrow.h"
33 #include "lyxrow_funcs.h"
34 #include "metricsinfo.h"
35 #include "paragraph.h"
36 #include "paragraph_funcs.h"
37 #include "ParagraphParameters.h"
38 #include "rowpainter.h"
39 #include "text_funcs.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 bv_funcs::number;
53
54 using lyx::pos_type;
55 using lyx::word_location;
56
57 using lyx::support::contains;
58 using lyx::support::lowercase;
59 using lyx::support::uppercase;
60
61 using std::max;
62 using std::endl;
63 using std::string;
64
65
66 /// top, right, bottom pixel margin
67 extern int const PAPER_MARGIN = 20;
68 /// margin for changebar
69 extern int const CHANGEBAR_MARGIN = 10;
70 /// left margin
71 extern int const LEFT_MARGIN = PAPER_MARGIN + CHANGEBAR_MARGIN;
72
73
74
75 int bibitemMaxWidth(BufferView *, LyXFont const &);
76
77
78 BufferView * LyXText::bv()
79 {
80         BOOST_ASSERT(bv_owner != 0);
81         return bv_owner;
82 }
83
84
85 BufferView * LyXText::bv() const
86 {
87         BOOST_ASSERT(bv_owner != 0);
88         return bv_owner;
89 }
90
91
92 void LyXText::updateRowPositions()
93 {
94         ParagraphList::iterator pit = ownerParagraphs().begin();
95         ParagraphList::iterator end = ownerParagraphs().end();
96         for (height = 0; pit != end; ++pit) {
97                 pit->y = height;
98                 height += pit->height;
99         }
100 }
101
102
103 int LyXText::workWidth() const
104 {
105         return inset_owner ? inset_owner->textWidth() : bv()->workWidth();
106 }
107
108
109 int LyXText::getRealCursorX() const
110 {
111         int x = cursor.x();
112         if (the_locking_inset && the_locking_inset->getLyXText(bv()) != this)
113                 x = the_locking_inset->getLyXText(bv())->getRealCursorX();
114         return x;
115 }
116
117
118 #warning FIXME  This function seems to belong outside of LyxText.
119 unsigned char LyXText::transformChar(unsigned char c, Paragraph const & par,
120                                      pos_type pos) const
121 {
122         if (!Encodings::is_arabic(c))
123                 if (lyxrc.font_norm_type == LyXRC::ISO_8859_6_8 && IsDigit(c))
124                         return c + (0xb0 - '0');
125                 else
126                         return c;
127
128         unsigned char const prev_char = pos > 0 ? par.getChar(pos - 1) : ' ';
129         unsigned char next_char = ' ';
130
131         pos_type const par_size = par.size();
132
133         for (pos_type i = pos + 1; i < par_size; ++i) {
134                 unsigned char const par_char = par.getChar(i);
135                 if (!Encodings::IsComposeChar_arabic(par_char)) {
136                         next_char = par_char;
137                         break;
138                 }
139         }
140
141         if (Encodings::is_arabic(next_char)) {
142                 if (Encodings::is_arabic(prev_char) &&
143                         !Encodings::is_arabic_special(prev_char))
144                         return Encodings::TransformChar(c, Encodings::FORM_MEDIAL);
145                 else
146                         return Encodings::TransformChar(c, Encodings::FORM_INITIAL);
147         } else {
148                 if (Encodings::is_arabic(prev_char) &&
149                         !Encodings::is_arabic_special(prev_char))
150                         return Encodings::TransformChar(c, Encodings::FORM_FINAL);
151                 else
152                         return Encodings::TransformChar(c, Encodings::FORM_ISOLATED);
153         }
154 }
155
156 // This is the comments that some of the warnings below refers to.
157 // There are some issues in this file and I don't think they are
158 // really related to the FIX_DOUBLE_SPACE patch. I'd rather think that
159 // this is a problem that has been here almost from day one and that a
160 // larger userbase with different access patters triggers the bad
161 // behaviour. (segfaults.) What I think happen is: In several places
162 // we store the paragraph in the current cursor and then moves the
163 // cursor. This movement of the cursor will delete paragraph at the
164 // old position if it is now empty. This will make the temporary
165 // pointer to the old cursor paragraph invalid and dangerous to use.
166 // And is some cases this will trigger a segfault. I have marked some
167 // of the cases where this happens with a warning, but I am sure there
168 // are others in this file and in text2.C. There is also a note in
169 // Delete() that you should read. In Delete I store the paragraph->id
170 // instead of a pointer to the paragraph. I am pretty sure this faulty
171 // use of temporary pointers to paragraphs that might have gotten
172 // invalidated (through a cursor movement) before they are used, are
173 // the cause of the strange crashes we get reported often.
174 //
175 // It is very tiresom to change this code, especially when it is as
176 // hard to read as it is. Help to fix all the cases where this is done
177 // would be greately appreciated.
178 //
179 // Lgb
180
181 int LyXText::singleWidth(ParagraphList::iterator pit, pos_type pos) const
182 {
183         if (pos >= pit->size())
184                 return 0;
185
186         char const c = pit->getChar(pos);
187         LyXFont const & font = getFont(pit, pos);
188         return singleWidth(pit, pos, c, font);
189 }
190
191
192 int LyXText::singleWidth(ParagraphList::iterator pit,
193                          pos_type pos, char c, LyXFont const & font) const
194 {
195         if (pos >= pit->size()) {
196                 lyxerr << "in singleWidth(), pos: " << pos << endl;
197                 BOOST_ASSERT(false);
198                 return 0;
199         }
200
201
202         // The most common case is handled first (Asger)
203         if (IsPrintable(c)) {
204                 if (!font.language()->RightToLeft()) {
205                         if ((lyxrc.font_norm_type == LyXRC::ISO_8859_6_8 ||
206                              lyxrc.font_norm_type == LyXRC::ISO_10646_1)
207                             && font.language()->lang() == "arabic") {
208                                 if (Encodings::IsComposeChar_arabic(c))
209                                         return 0;
210                                 else
211                                         c = transformChar(c, *pit, pos);
212                         } else if (font.language()->lang() == "hebrew" &&
213                                  Encodings::IsComposeChar_hebrew(c))
214                                 return 0;
215                 }
216                 return font_metrics::width(c, font);
217         }
218
219         if (c == Paragraph::META_INSET) {
220                 InsetOld * tmpinset = pit->getInset(pos);
221                 BOOST_ASSERT(tmpinset);
222                 if (tmpinset->lyxCode() == InsetOld::HFILL_CODE) {
223                         // Because of the representation as vertical lines
224                         return 3;
225                 }
226                 return tmpinset->width();
227         }
228
229         if (IsSeparatorChar(c))
230                 c = ' ';
231         return font_metrics::width(c, font);
232 }
233
234
235 lyx::pos_type LyXText::log2vis(lyx::pos_type pos) const
236 {
237         return (bidi_start == -1) ? pos : log2vis_list[pos - bidi_start];
238 }
239
240
241 lyx::pos_type LyXText::vis2log(lyx::pos_type pos) const
242 {
243         return (bidi_start == -1) ? pos : vis2log_list[pos - bidi_start];
244 }
245
246
247 lyx::pos_type LyXText::bidi_level(lyx::pos_type pos) const
248 {
249         return (bidi_start == -1) ? 0 : bidi_levels[pos - bidi_start];
250 }
251
252
253 bool LyXText::bidi_InRange(lyx::pos_type pos) const
254 {
255         return bidi_start == -1 || (bidi_start <= pos && pos <= bidi_end);
256 }
257
258
259 void LyXText::computeBidiTables(Paragraph const & par,
260    Buffer const & buf, Row & row) const
261 {
262         bidi_same_direction = true;
263         if (!lyxrc.rtl_support) {
264                 bidi_start = -1;
265                 return;
266         }
267
268         InsetOld * inset = par.inInset();
269         if (inset && inset->owner() &&
270             inset->owner()->lyxCode() == InsetOld::ERT_CODE) {
271                 bidi_start = -1;
272                 return;
273         }
274
275         bidi_start = row.pos();
276         bidi_end = lastPos(par, row);
277
278         if (bidi_start > bidi_end) {
279                 bidi_start = -1;
280                 return;
281         }
282
283         if (bidi_end + 2 - bidi_start >
284             static_cast<pos_type>(log2vis_list.size())) {
285                 pos_type new_size =
286                         (bidi_end + 2 - bidi_start < 500) ?
287                         500 : 2 * (bidi_end + 2 - bidi_start);
288                 log2vis_list.resize(new_size);
289                 vis2log_list.resize(new_size);
290                 bidi_levels.resize(new_size);
291         }
292
293         vis2log_list[bidi_end + 1 - bidi_start] = -1;
294         log2vis_list[bidi_end + 1 - bidi_start] = -1;
295
296         BufferParams const & bufparams = buf.params();
297         pos_type stack[2];
298         bool const rtl_par = par.isRightToLeftPar(bufparams);
299         int level = 0;
300         bool rtl = false;
301         bool rtl0 = false;
302         pos_type const body_pos = par.beginningOfBody();
303
304         for (pos_type lpos = bidi_start; lpos <= bidi_end; ++lpos) {
305                 bool is_space = par.isLineSeparator(lpos);
306                 pos_type const pos =
307                         (is_space && lpos + 1 <= bidi_end &&
308                          !par.isLineSeparator(lpos + 1) &&
309                          !par.isNewline(lpos + 1))
310                         ? lpos + 1 : lpos;
311                 LyXFont font = par.getFontSettings(bufparams, pos);
312                 if (pos != lpos && 0 < lpos && rtl0 && font.isRightToLeft() &&
313                     font.number() == LyXFont::ON &&
314                     par.getFontSettings(bufparams, lpos - 1).number()
315                     == LyXFont::ON) {
316                         font = par.getFontSettings(bufparams, lpos);
317                         is_space = false;
318                 }
319
320                 bool new_rtl = font.isVisibleRightToLeft();
321                 bool new_rtl0 = font.isRightToLeft();
322                 int new_level;
323
324                 if (lpos == body_pos - 1
325                     && row.pos() < body_pos - 1
326                     && is_space) {
327                         new_level = rtl_par ? 1 : 0;
328                         new_rtl0 = rtl_par;
329                         new_rtl = rtl_par;
330                 } else if (new_rtl0)
331                         new_level = new_rtl ? 1 : 2;
332                 else
333                         new_level = rtl_par ? 2 : 0;
334
335                 if (is_space && new_level >= level) {
336                         new_level = level;
337                         new_rtl = rtl;
338                         new_rtl0 = rtl0;
339                 }
340
341                 int new_level2 = new_level;
342
343                 if (level == new_level && rtl0 != new_rtl0) {
344                         --new_level2;
345                         log2vis_list[lpos - bidi_start] = rtl ? 1 : -1;
346                 } else if (level < new_level) {
347                         log2vis_list[lpos - bidi_start] = rtl ? -1 : 1;
348                         if (new_level > rtl_par)
349                                 bidi_same_direction = false;
350                 } else
351                         log2vis_list[lpos - bidi_start] = new_rtl ? -1 : 1;
352                 rtl = new_rtl;
353                 rtl0 = new_rtl0;
354                 bidi_levels[lpos - bidi_start] = new_level;
355
356                 while (level > new_level2) {
357                         pos_type old_lpos = stack[--level];
358                         int delta = lpos - old_lpos - 1;
359                         if (level % 2)
360                                 delta = -delta;
361                         log2vis_list[lpos - bidi_start] += delta;
362                         log2vis_list[old_lpos - bidi_start] += delta;
363                 }
364                 while (level < new_level)
365                         stack[level++] = lpos;
366         }
367
368         while (level > 0) {
369                 pos_type const old_lpos = stack[--level];
370                 int delta = bidi_end - old_lpos;
371                 if (level % 2)
372                         delta = -delta;
373                 log2vis_list[old_lpos - bidi_start] += delta;
374         }
375
376         pos_type vpos = bidi_start - 1;
377         for (pos_type lpos = bidi_start;
378              lpos <= bidi_end; ++lpos) {
379                 vpos += log2vis_list[lpos - bidi_start];
380                 vis2log_list[vpos - bidi_start] = lpos;
381                 log2vis_list[lpos - bidi_start] = vpos;
382         }
383 }
384
385
386 // This method requires a previous call to ComputeBidiTables()
387 bool LyXText::isBoundary(Buffer const & buf, Paragraph const & par,
388                          pos_type pos) const
389 {
390         if (!lyxrc.rtl_support || pos == 0)
391                 return false;
392
393         if (!bidi_InRange(pos - 1)) {
394                 // This can happen if pos is the first char of a row.
395                 // Returning false in this case is incorrect!
396                 return false;
397         }
398
399         bool const rtl = bidi_level(pos - 1) % 2;
400         bool const rtl2 = bidi_InRange(pos)
401                 ? bidi_level(pos) % 2
402                 : par.isRightToLeftPar(buf.params());
403         return rtl != rtl2;
404 }
405
406
407 bool LyXText::isBoundary(Buffer const & buf, Paragraph const & par,
408                          pos_type pos, LyXFont const & font) const
409 {
410         if (!lyxrc.rtl_support)
411                 return false;    // This is just for speedup
412
413         bool const rtl = font.isVisibleRightToLeft();
414         bool const rtl2 = bidi_InRange(pos)
415                 ? bidi_level(pos) % 2
416                 : par.isRightToLeftPar(buf.params());
417         return rtl != rtl2;
418 }
419
420
421 int LyXText::leftMargin(ParagraphList::iterator pit, Row const & row) const
422 {
423         LyXTextClass const & tclass =
424                 bv()->buffer()->params().getLyXTextClass();
425         LyXLayout_ptr const & layout = pit->layout();
426
427         string parindent = layout->parindent;
428
429         int x = LEFT_MARGIN;
430
431         x += font_metrics::signedWidth(tclass.leftmargin(), tclass.defaultfont());
432
433         // this is the way, LyX handles the LaTeX-Environments.
434         // I have had this idea very late, so it seems to be a
435         // later added hack and this is true
436         if (!pit->getDepth()) {
437                 if (pit->layout() == tclass.defaultLayout()) {
438                         // find the previous same level paragraph
439                         if (pit != ownerParagraphs().begin()) {
440                                 ParagraphList::iterator newpit =
441                                         depthHook(pit, ownerParagraphs(),
442                                                   pit->getDepth());
443                                 if (newpit == pit &&
444                                     newpit->layout()->nextnoindent)
445                                         parindent.erase();
446                         }
447                 }
448         } else {
449                 // find the next level paragraph
450
451                 ParagraphList::iterator newpar = outerHook(pit,
452                                                            ownerParagraphs());
453
454                 // make a corresponding row. Needed to call leftMargin()
455
456                 // check wether it is a sufficent paragraph
457                 if (newpar != ownerParagraphs().end() &&
458                     newpar->layout()->isEnvironment()) {
459                         x = leftMargin(newpar, Row(newpar->size()));
460                 }
461
462                 if (newpar != ownerParagraphs().end() &&
463                     pit->layout() == tclass.defaultLayout()) {
464                         if (newpar->params().noindent())
465                                 parindent.erase();
466                         else {
467                                 parindent = newpar->layout()->parindent;
468                         }
469
470                 }
471         }
472
473         LyXFont const labelfont = getLabelFont(pit);
474         switch (layout->margintype) {
475         case MARGIN_DYNAMIC:
476                 if (!layout->leftmargin.empty()) {
477                         x += font_metrics::signedWidth(layout->leftmargin,
478                                                   tclass.defaultfont());
479                 }
480                 if (!pit->getLabelstring().empty()) {
481                         x += font_metrics::signedWidth(layout->labelindent,
482                                                   labelfont);
483                         x += font_metrics::width(pit->getLabelstring(),
484                                             labelfont);
485                         x += font_metrics::width(layout->labelsep, labelfont);
486                 }
487                 break;
488         case MARGIN_MANUAL:
489                 x += font_metrics::signedWidth(layout->labelindent, labelfont);
490                 // The width of an empty par, even with manual label, should be 0
491                 if (!pit->empty() && row.pos() >= pit->beginningOfBody()) {
492                         if (!pit->getLabelWidthString().empty()) {
493                                 x += font_metrics::width(pit->getLabelWidthString(),
494                                                labelfont);
495                                 x += font_metrics::width(layout->labelsep, labelfont);
496                         }
497                 }
498                 break;
499         case MARGIN_STATIC:
500                 x += font_metrics::signedWidth(layout->leftmargin, tclass.defaultfont()) * 4
501                         / (pit->getDepth() + 4);
502                 break;
503         case MARGIN_FIRST_DYNAMIC:
504                 if (layout->labeltype == LABEL_MANUAL) {
505                         if (row.pos() >= pit->beginningOfBody()) {
506                                 x += font_metrics::signedWidth(layout->leftmargin,
507                                                           labelfont);
508                         } else {
509                                 x += font_metrics::signedWidth(layout->labelindent,
510                                                           labelfont);
511                         }
512                 } else if (row.pos()
513                            // Special case to fix problems with
514                            // theorems (JMarc)
515                            || (layout->labeltype == LABEL_STATIC
516                                && layout->latextype == LATEX_ENVIRONMENT
517                                && !isFirstInSequence(pit, ownerParagraphs()))) {
518                         x += font_metrics::signedWidth(layout->leftmargin,
519                                                   labelfont);
520                 } else if (layout->labeltype != LABEL_TOP_ENVIRONMENT
521                            && layout->labeltype != LABEL_BIBLIO
522                            && layout->labeltype !=
523                            LABEL_CENTERED_TOP_ENVIRONMENT) {
524                         x += font_metrics::signedWidth(layout->labelindent,
525                                                   labelfont);
526                         x += font_metrics::width(layout->labelsep, labelfont);
527                         x += font_metrics::width(pit->getLabelstring(),
528                                             labelfont);
529                 }
530                 break;
531
532         case MARGIN_RIGHT_ADDRESS_BOX:
533         {
534                 // ok, a terrible hack. The left margin depends on the widest
535                 // row in this paragraph.
536                 RowList::iterator rit = pit->rows.begin();
537                 RowList::iterator end = pit->rows.end();
538                 int minfill = rit->fill();
539                 for ( ; rit != end; ++rit)
540                         if (rit->fill() < minfill)
541                                 minfill = rit->fill();
542
543                 x += font_metrics::signedWidth(layout->leftmargin,
544                         tclass.defaultfont());
545                 x += minfill;
546         }
547         break;
548         }
549
550         if (workWidth() > 0 && !pit->params().leftIndent().zero()) {
551                 LyXLength const len = pit->params().leftIndent();
552                 int const tw = inset_owner ?
553                         inset_owner->latexTextWidth(bv()) : workWidth();
554                 x += len.inPixels(tw);
555         }
556
557         LyXAlignment align;
558
559         if (pit->params().align() == LYX_ALIGN_LAYOUT)
560                 align = layout->align;
561         else
562                 align = pit->params().align();
563
564         // set the correct parindent
565         if (row.pos() == 0) {
566                 if ((layout->labeltype == LABEL_NO_LABEL
567                      || layout->labeltype == LABEL_TOP_ENVIRONMENT
568                      || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
569                      || (layout->labeltype == LABEL_STATIC
570                          && layout->latextype == LATEX_ENVIRONMENT
571                          && !isFirstInSequence(pit, ownerParagraphs())))
572                     && align == LYX_ALIGN_BLOCK
573                     && !pit->params().noindent()
574                         // in tabulars and ert paragraphs are never indented!
575                         && (!pit->inInset() || !pit->inInset()->owner() ||
576                                 (pit->inInset()->owner()->lyxCode() != InsetOld::TABULAR_CODE &&
577                                  pit->inInset()->owner()->lyxCode() != InsetOld::ERT_CODE))
578                     && (pit->layout() != tclass.defaultLayout() ||
579                         bv()->buffer()->params().paragraph_separation ==
580                         BufferParams::PARSEP_INDENT)) {
581                         x += font_metrics::signedWidth(parindent,
582                                                   tclass.defaultfont());
583                 } else if (layout->labeltype == LABEL_BIBLIO) {
584                         // ale970405 Right width for bibitems
585                         x += bibitemMaxWidth(bv(), tclass.defaultfont());
586                 }
587         }
588
589         return x;
590 }
591
592
593 int LyXText::rightMargin(Paragraph const & par,
594         Buffer const & buf, Row const &) const
595 {
596         LyXTextClass const & tclass = buf.params().getLyXTextClass();
597         LyXLayout_ptr const & layout = par.layout();
598
599         return PAPER_MARGIN
600                 + font_metrics::signedWidth(tclass.rightmargin(),
601                                        tclass.defaultfont())
602                 + font_metrics::signedWidth(layout->rightmargin,
603                                        tclass.defaultfont())
604                 * 4 / (par.getDepth() + 4);
605 }
606
607
608 int LyXText::labelEnd(ParagraphList::iterator pit, Row const & row) const
609 {
610         if (pit->layout()->margintype == MARGIN_MANUAL) {
611                 Row tmprow = row;
612                 tmprow.pos(pit->size());
613                 // return the beginning of the body
614                 return leftMargin(pit, tmprow);
615         }
616
617         // LabelEnd is only needed if the layout
618         // fills a flushleft label.
619         return 0;
620 }
621
622
623 namespace {
624
625 // this needs special handling - only newlines count as a break point
626 pos_type addressBreakPoint(pos_type i, Paragraph const & par)
627 {
628         for (; i < par.size(); ++i)
629                 if (par.isNewline(i))
630                         return i;
631
632         return par.size();
633 }
634
635 };
636
637
638 pos_type LyXText::rowBreakPoint(ParagraphList::iterator pit,
639         Row const & row) const
640 {
641         // maximum pixel width of a row.
642         int width = workWidth() - rightMargin(*pit, *bv()->buffer(), row);
643
644         // inset->textWidth() returns -1 via workWidth(),
645         // but why ?
646         if (width < 0)
647                 return pit->size();
648
649         LyXLayout_ptr const & layout = pit->layout();
650
651         if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX)
652                 return addressBreakPoint(row.pos(), *pit);
653
654         pos_type const pos = row.pos();
655         pos_type const body_pos = pit->beginningOfBody();
656         pos_type const last = pit->size();
657         pos_type point = last;
658
659         if (pos == last)
660                 return last;
661
662         // Now we iterate through until we reach the right margin
663         // or the end of the par, then choose the possible break
664         // nearest that.
665
666         int const left = leftMargin(pit, row);
667         int x = left;
668
669         // pixel width since last breakpoint
670         int chunkwidth = 0;
671
672         pos_type i = pos;
673
674         // We re-use the font resolution for the entire font span when possible
675         LyXFont font = getFont(pit, i);
676         lyx::pos_type endPosOfFontSpan = pit->getEndPosOfFontSpan(i);
677
678         for (; i < last; ++i) {
679                 if (pit->isNewline(i)) {
680                         point = i;
681                         break;
682                 }
683                 // Break before...      
684                 if (i + 1 < last) {
685                         InsetOld * in = pit->getInset(i + 1);
686                         if (in && in->display()) {
687                                 point = i;
688                                 break;
689                         }
690                         // ...and after.
691                         in = pit->getInset(i);
692                         if (in && in->display()) {
693                                 point = i;
694                                 break;
695                         }
696                 }
697
698                 char const c = pit->getChar(i);
699                 if (i > endPosOfFontSpan) {
700                         font = getFont(pit, i);
701                         endPosOfFontSpan = pit->getEndPosOfFontSpan(i);
702                 }
703
704                 int thiswidth;
705
706                 // add the auto-hfill from label end to the body
707                 if (body_pos && i == body_pos) {
708                         thiswidth = font_metrics::width(layout->labelsep, getLabelFont(pit));
709                         if (pit->isLineSeparator(i - 1))
710                                 thiswidth -= singleWidth(pit, i - 1);
711                         int left_margin = labelEnd(pit, row);
712                         if (thiswidth + x < left_margin)
713                                 thiswidth = left_margin - x;
714                         thiswidth += singleWidth(pit, i, c, font);
715                 } else {
716                         thiswidth = singleWidth(pit, i, c, font);
717                 }
718
719                 x += thiswidth;
720                 chunkwidth += thiswidth;
721
722                 InsetOld * in = pit->getInset(i);
723
724                 // break before a character that will fall off
725                 // the right of the row
726                 if (x >= width) {
727                         // if no break before, break here
728                         if (point == last || chunkwidth >= width - left) {
729                                 if (pos < i) {
730                                         point = i - 1;
731                                         break;
732                                 }
733                         }
734                 }
735
736                 if (!in || in->isChar()) {
737                         // some insets are line separators too
738                         if (pit->isLineSeparator(i)) {
739                                 point = i;
740                                 chunkwidth = 0;
741                         }
742                 }
743         }
744
745         if (point == last && x >= width) {
746                 // didn't find one, break at the point we reached the edge
747                 point = i;
748         } else if (i == last && x < width) {
749                 // found one, but we fell off the end of the par, so prefer
750                 // that.
751                 point = last;
752         }
753
754         // manual labels cannot be broken in LaTeX. But we
755         // want to make our on-screen rendering of footnotes
756         // etc. still break
757         if (body_pos && point < body_pos)
758                 point = body_pos - 1;
759
760         return point;
761 }
762
763
764 // returns the minimum space a row needs on the screen in pixel
765 int LyXText::fill(ParagraphList::iterator pit, Row & row, int paper_width) const
766 {
767         if (paper_width < 0)
768                 return 0;
769
770         int w;
771         // get the pure distance
772         pos_type const last = lastPos(*pit, row);
773
774         LyXLayout_ptr const & layout = pit->layout();
775
776         // special handling of the right address boxes
777         if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX) {
778                 int const tmpfill = row.fill();
779                 row.fill(0); // the minfill in MarginLeft()
780                 w = leftMargin(pit, row);
781                 row.fill(tmpfill);
782         } else
783                 w = leftMargin(pit, row);
784
785         pos_type const body_pos = pit->beginningOfBody();
786         pos_type i = row.pos();
787
788         if (! pit->empty() && i <= last) {
789                 // We re-use the font resolution for the entire span when possible
790                 LyXFont font = getFont(pit, i);
791                 lyx::pos_type endPosOfFontSpan = pit->getEndPosOfFontSpan(i);
792                 while (i <= last) {
793                         if (body_pos > 0 && i == body_pos) {
794                                 w += font_metrics::width(layout->labelsep, getLabelFont(pit));
795                                 if (pit->isLineSeparator(i - 1))
796                                         w -= singleWidth(pit, i - 1);
797                                 int left_margin = labelEnd(pit, row);
798                                 if (w < left_margin)
799                                         w = left_margin;
800                         }
801                         char const c = pit->getChar(i);
802                         if (IsPrintable(c) && i > endPosOfFontSpan) {
803                                 // We need to get the next font
804                                 font = getFont(pit, i);
805                                 endPosOfFontSpan = pit->getEndPosOfFontSpan(i);
806                         }
807                         w += singleWidth(pit, i, c, font);
808                         ++i;
809                 }
810         }
811         if (body_pos > 0 && body_pos > last) {
812                 w += font_metrics::width(layout->labelsep, getLabelFont(pit));
813                 if (last >= 0 && pit->isLineSeparator(last))
814                         w -= singleWidth(pit, last);
815                 int const left_margin = labelEnd(pit, row);
816                 if (w < left_margin)
817                         w = left_margin;
818         }
819
820         int const fill = paper_width - w - rightMargin(*pit, *bv()->buffer(), row);
821
822         // If this case happens, it means that our calculation
823         // of the widths of the chars when we do rowBreakPoint()
824         // went wrong for some reason. Typically in list bodies.
825         // Things just about hobble on anyway, though you'll end
826         // up with a "fill_separator" less than zero, which corresponds
827         // to inter-word spacing being too small. Hopefully this problem
828         // will die when the label hacks die.
829         if (lyxerr.debugging() && fill < 0) {
830                 lyxerr[Debug::GUI] << "Eek, fill() was < 0: " << fill
831                         << " w " << w << " paper_width " << paper_width
832                         << " right margin " << rightMargin(*pit, *bv()->buffer(), row) << endl;
833         }
834         return fill;
835 }
836
837
838 // returns the minimum space a manual label needs on the screen in pixel
839 int LyXText::labelFill(ParagraphList::iterator pit, Row const & row) const
840 {
841         pos_type last = pit->beginningOfBody();
842
843         BOOST_ASSERT(last > 0);
844
845         // -1 because a label ends either with a space that is in the label,
846         // or with the beginning of a footnote that is outside the label.
847         --last;
848
849         // a separator at this end does not count
850         if (pit->isLineSeparator(last))
851                 --last;
852
853         int w = 0;
854         pos_type i = row.pos();
855         while (i <= last) {
856                 w += singleWidth(pit, i);
857                 ++i;
858         }
859
860         int fill = 0;
861         string const & labwidstr = pit->params().labelWidthString();
862         if (!labwidstr.empty()) {
863                 LyXFont const labfont = getLabelFont(pit);
864                 int const labwidth = font_metrics::width(labwidstr, labfont);
865                 fill = max(labwidth - w, 0);
866         }
867
868         return fill;
869 }
870
871
872 LColor_color LyXText::backgroundColor() const
873 {
874         if (inset_owner)
875                 return inset_owner->backgroundColor();
876         else
877                 return LColor::background;
878 }
879
880
881 void LyXText::setHeightOfRow(ParagraphList::iterator pit, Row & row)
882 {
883         // get the maximum ascent and the maximum descent
884         double layoutasc = 0;
885         double layoutdesc = 0;
886         double tmptop = 0;
887
888         // ok, let us initialize the maxasc and maxdesc value.
889         // Only the fontsize count. The other properties
890         // are taken from the layoutfont. Nicer on the screen :)
891         LyXLayout_ptr const & layout = pit->layout();
892
893         // as max get the first character of this row then it can increase but not
894         // decrease the height. Just some point to start with so we don't have to
895         // do the assignment below too often.
896         LyXFont font = getFont(pit, row.pos());
897         LyXFont::FONT_SIZE const tmpsize = font.size();
898         font = getLayoutFont(pit);
899         LyXFont::FONT_SIZE const size = font.size();
900         font.setSize(tmpsize);
901
902         LyXFont labelfont = getLabelFont(pit);
903
904         double spacing_val = 1.0;
905         if (!pit->params().spacing().isDefault())
906                 spacing_val = pit->params().spacing().getValue();
907         else
908                 spacing_val = bv()->buffer()->params().spacing().getValue();
909         //lyxerr << "spacing_val = " << spacing_val << endl;
910
911         int maxasc  = int(font_metrics::maxAscent(font) *
912                           layout->spacing.getValue() * spacing_val);
913         int maxdesc = int(font_metrics::maxDescent(font) *
914                           layout->spacing.getValue() * spacing_val);
915
916         pos_type const pos_end = lastPos(*pit, row);
917         int labeladdon = 0;
918         int maxwidth = 0;
919
920         if (!pit->empty()) {
921                 // We re-use the font resolution for the entire font span when possible
922                 LyXFont font = getFont(pit, row.pos());
923                 lyx::pos_type endPosOfFontSpan = pit->getEndPosOfFontSpan(row.pos());
924
925                 // Optimisation
926                 Paragraph const & par = *pit;
927
928                 // Check if any insets are larger
929                 for (pos_type pos = row.pos(); pos <= pos_end; ++pos) {
930                         // Manual inlined optimised version of common case of
931                         // "maxwidth += singleWidth(pit, pos);"
932                         char const c = par.getChar(pos);
933
934                         if (IsPrintable(c)) {
935                                 if (pos > endPosOfFontSpan) {
936                                         // We need to get the next font
937                                         font = getFont(pit, pos);
938                                         endPosOfFontSpan = par.getEndPosOfFontSpan(pos);
939                                 }
940                                 if (! font.language()->RightToLeft()) {
941                                         maxwidth += font_metrics::width(c, font);
942                                 } else {
943                                         // Fall-back to normal case
944                                         maxwidth += singleWidth(pit, pos, c, font);
945                                         // And flush font cache
946                                         endPosOfFontSpan = 0;
947                                 }
948                         } else {
949                                 // Special handling of insets - are any larger?
950                                 if (par.isInset(pos)) {
951                                         InsetOld const * tmpinset = par.getInset(pos);
952                                         if (tmpinset) {
953                                                 maxwidth += tmpinset->width();
954                                                 maxasc = max(maxasc, tmpinset->ascent());
955                                                 maxdesc = max(maxdesc, tmpinset->descent());
956                                         }
957                                 } else {
958                                         // Fall-back to normal case
959                                         maxwidth += singleWidth(pit, pos, c, font);
960                                         // And flush font cache
961                                         endPosOfFontSpan = 0;
962                                 }
963                         }
964                 }
965         }
966
967         // Check if any custom fonts are larger (Asger)
968         // This is not completely correct, but we can live with the small,
969         // cosmetic error for now.
970         LyXFont::FONT_SIZE maxsize =
971                 pit->highestFontInRange(row.pos(), pos_end, size);
972         if (maxsize > font.size()) {
973                 font.setSize(maxsize);
974                 maxasc = max(maxasc, font_metrics::maxAscent(font));
975                 maxdesc = max(maxdesc, font_metrics::maxDescent(font));
976         }
977
978         // This is nicer with box insets:
979         ++maxasc;
980         ++maxdesc;
981
982         row.ascent_of_text(maxasc);
983
984         // is it a top line?
985         if (!row.pos()) {
986                 BufferParams const & bufparams = bv()->buffer()->params();
987                 // some parksips VERY EASY IMPLEMENTATION
988                 if (bv()->buffer()->params().paragraph_separation ==
989                         BufferParams::PARSEP_SKIP)
990                 {
991                         if (layout->isParagraph()
992                                 && pit->getDepth() == 0
993                                 && pit != ownerParagraphs().begin())
994                         {
995                                 maxasc += bufparams.getDefSkip().inPixels(*bv());
996                         } else if (pit != ownerParagraphs().begin() &&
997                                    boost::prior(pit)->layout()->isParagraph() &&
998                                    boost::prior(pit)->getDepth() == 0)
999                         {
1000                                 // is it right to use defskip here too? (AS)
1001                                 maxasc += bufparams.getDefSkip().inPixels(*bv());
1002                         }
1003                 }
1004
1005                 // the top margin
1006                 if (pit == ownerParagraphs().begin() && !isInInset())
1007                         maxasc += PAPER_MARGIN;
1008
1009                 // add the vertical spaces, that the user added
1010                 maxasc += getLengthMarkerHeight(*bv(), pit->params().spaceTop());
1011
1012                 // do not forget the DTP-lines!
1013                 // there height depends on the font of the nearest character
1014                 if (pit->params().lineTop())
1015
1016                         maxasc += 2 * font_metrics::ascent('x', getFont(pit, 0));
1017                 // and now the pagebreaks
1018                 if (pit->params().pagebreakTop())
1019                         maxasc += 3 * defaultRowHeight();
1020
1021                 if (pit->params().startOfAppendix())
1022                         maxasc += 3 * defaultRowHeight();
1023
1024                 // This is special code for the chapter, since the label of this
1025                 // layout is printed in an extra row
1026                 if (layout->counter == "chapter" && bufparams.secnumdepth >= 0) {
1027                         float spacing_val = 1.0;
1028                         if (!pit->params().spacing().isDefault()) {
1029                                 spacing_val = pit->params().spacing().getValue();
1030                         } else {
1031                                 spacing_val = bufparams.spacing().getValue();
1032                         }
1033
1034                         labeladdon = int(font_metrics::maxDescent(labelfont) *
1035                                          layout->spacing.getValue() *
1036                                          spacing_val)
1037                                 + int(font_metrics::maxAscent(labelfont) *
1038                                       layout->spacing.getValue() *
1039                                       spacing_val);
1040                 }
1041
1042                 // special code for the top label
1043                 if ((layout->labeltype == LABEL_TOP_ENVIRONMENT
1044                      || layout->labeltype == LABEL_BIBLIO
1045                      || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
1046                     && isFirstInSequence(pit, ownerParagraphs())
1047                     && !pit->getLabelstring().empty())
1048                 {
1049                         float spacing_val = 1.0;
1050                         if (!pit->params().spacing().isDefault()) {
1051                                 spacing_val = pit->params().spacing().getValue();
1052                         } else {
1053                                 spacing_val = bufparams.spacing().getValue();
1054                         }
1055
1056                         labeladdon = int(
1057                                 (font_metrics::maxAscent(labelfont) +
1058                                  font_metrics::maxDescent(labelfont)) *
1059                                   layout->spacing.getValue() *
1060                                   spacing_val
1061                                 + layout->topsep * defaultRowHeight()
1062                                 + layout->labelbottomsep * defaultRowHeight());
1063                 }
1064
1065                 // And now the layout spaces, for example before and after
1066                 // a section, or between the items of a itemize or enumerate
1067                 // environment.
1068
1069                 if (!pit->params().pagebreakTop()) {
1070                         ParagraphList::iterator prev =
1071                                 depthHook(pit, ownerParagraphs(),
1072                                           pit->getDepth());
1073                         if (prev != pit && prev->layout() == layout &&
1074                                 prev->getDepth() == pit->getDepth() &&
1075                                 prev->getLabelWidthString() == pit->getLabelWidthString())
1076                         {
1077                                 layoutasc = (layout->itemsep * defaultRowHeight());
1078                         } else if (pit != ownerParagraphs().begin() || row.pos() != 0) {
1079                                 tmptop = layout->topsep;
1080
1081                                 if (tmptop > 0)
1082                                         layoutasc = (tmptop * defaultRowHeight());
1083                         } else if (pit->params().lineTop()) {
1084                                 tmptop = layout->topsep;
1085
1086                                 if (tmptop > 0)
1087                                         layoutasc = (tmptop * defaultRowHeight());
1088                         }
1089
1090                         prev = outerHook(pit, ownerParagraphs());
1091                         if (prev != ownerParagraphs().end())  {
1092                                 maxasc += int(prev->layout()->parsep * defaultRowHeight());
1093                         } else if (pit != ownerParagraphs().begin()) {
1094                                 ParagraphList::iterator prior_pit = boost::prior(pit);
1095                                 if (prior_pit->getDepth() != 0 ||
1096                                     prior_pit->layout() == layout) {
1097                                         maxasc += int(layout->parsep * defaultRowHeight());
1098                                 }
1099                         }
1100                 }
1101         }
1102
1103         // is it a bottom line?
1104         if (row.end() == pit->size()) {
1105                 // the bottom margin
1106                 ParagraphList::iterator nextpit = boost::next(pit);
1107                 if (nextpit == ownerParagraphs().end() && !isInInset())
1108                         maxdesc += PAPER_MARGIN;
1109
1110                 // add the vertical spaces, that the user added
1111                 maxdesc += getLengthMarkerHeight(*bv(), pit->params().spaceBottom());
1112
1113                 // do not forget the DTP-lines!
1114                 // there height depends on the font of the nearest character
1115                 if (pit->params().lineBottom())
1116                         maxdesc += 2 * font_metrics::ascent('x',
1117                                         getFont(pit, max(pos_type(0), pit->size() - 1)));
1118
1119                 // and now the pagebreaks
1120                 if (pit->params().pagebreakBottom())
1121                         maxdesc += 3 * defaultRowHeight();
1122
1123                 // and now the layout spaces, for example before and after
1124                 // a section, or between the items of a itemize or enumerate
1125                 // environment
1126                 if (!pit->params().pagebreakBottom()
1127                     && nextpit != ownerParagraphs().end()) {
1128                         ParagraphList::iterator comparepit = pit;
1129                         float usual = 0;
1130                         float unusual = 0;
1131
1132                         if (comparepit->getDepth() > nextpit->getDepth()) {
1133                                 usual = (comparepit->layout()->bottomsep * defaultRowHeight());
1134                                 comparepit = depthHook(comparepit, ownerParagraphs(), nextpit->getDepth());
1135                                 if (comparepit->layout()!= nextpit->layout()
1136                                         || nextpit->getLabelWidthString() !=
1137                                         comparepit->getLabelWidthString())
1138                                 {
1139                                         unusual = (comparepit->layout()->bottomsep * defaultRowHeight());
1140                                 }
1141                                 if (unusual > usual)
1142                                         layoutdesc = unusual;
1143                                 else
1144                                         layoutdesc = usual;
1145                         } else if (comparepit->getDepth() ==  nextpit->getDepth()) {
1146
1147                                 if (comparepit->layout() != nextpit->layout()
1148                                         || nextpit->getLabelWidthString() !=
1149                                         comparepit->getLabelWidthString())
1150                                         layoutdesc = int(comparepit->layout()->bottomsep * defaultRowHeight());
1151                         }
1152                 }
1153         }
1154
1155         // incalculate the layout spaces
1156         maxasc += int(layoutasc * 2 / (2 + pit->getDepth()));
1157         maxdesc += int(layoutdesc * 2 / (2 + pit->getDepth()));
1158
1159         row.height(maxasc + maxdesc + labeladdon);
1160         row.baseline(maxasc + labeladdon);
1161         row.top_of_text(row.baseline() - font_metrics::maxAscent(font));
1162
1163         row.width(maxwidth);
1164         if (inset_owner) {
1165                 width = max(0, workWidth());
1166                 RowList::iterator rit = firstRow();
1167                 RowList::iterator end = endRow();
1168                 ParagraphList::iterator it = ownerParagraphs().begin();
1169                 while (rit != end) {
1170                         if (rit->width() > width)
1171                                 width = rit->width();
1172                         nextRow(it, rit);
1173                 }
1174         }
1175 }
1176
1177
1178 void LyXText::breakParagraph(ParagraphList & paragraphs, char keep_layout)
1179 {
1180         // allow only if at start or end, or all previous is new text
1181         if (cursor.pos() && cursor.pos() != cursorPar()->size()
1182                 && cursorPar()->isChangeEdited(0, cursor.pos()))
1183                 return;
1184
1185         LyXTextClass const & tclass =
1186                 bv()->buffer()->params().getLyXTextClass();
1187         LyXLayout_ptr const & layout = cursorPar()->layout();
1188
1189         // this is only allowed, if the current paragraph is not empty or caption
1190         // and if it has not the keepempty flag active
1191         if (cursorPar()->empty() && !cursorPar()->allowEmpty()
1192            && layout->labeltype != LABEL_SENSITIVE)
1193                 return;
1194
1195         recUndo(cursor.par());
1196
1197         // Always break behind a space
1198         //
1199         // It is better to erase the space (Dekel)
1200         if (cursor.pos() < cursorPar()->size()
1201              && cursorPar()->isLineSeparator(cursor.pos()))
1202            cursorPar()->erase(cursor.pos());
1203
1204         // break the paragraph
1205         if (keep_layout)
1206                 keep_layout = 2;
1207         else
1208                 keep_layout = layout->isEnvironment();
1209
1210         // we need to set this before we insert the paragraph. IMO the
1211         // breakParagraph call should return a bool if it inserts the
1212         // paragraph before or behind and we should react on that one
1213         // but we can fix this in 1.3.0 (Jug 20020509)
1214         bool const isempty = (cursorPar()->allowEmpty() && cursorPar()->empty());
1215         ::breakParagraph(bv()->buffer()->params(), paragraphs, cursorPar(),
1216                          cursor.pos(), keep_layout);
1217
1218 #warning Trouble Point! (Lgb)
1219         // When ::breakParagraph is called from within an inset we must
1220         // ensure that the correct ParagraphList is used. Today that is not
1221         // the case and the Buffer::paragraphs is used. Not good. (Lgb)
1222         ParagraphList::iterator next_par = boost::next(cursorPar());
1223
1224         // well this is the caption hack since one caption is really enough
1225         if (layout->labeltype == LABEL_SENSITIVE) {
1226                 if (!cursor.pos())
1227                         // set to standard-layout
1228                         cursorPar()->applyLayout(tclass.defaultLayout());
1229                 else
1230                         // set to standard-layout
1231                         next_par->applyLayout(tclass.defaultLayout());
1232         }
1233
1234         // if the cursor is at the beginning of a row without prior newline,
1235         // move one row up!
1236         // This touches only the screen-update. Otherwise we would may have
1237         // an empty row on the screen
1238         if (cursor.pos() && cursorRow()->pos() == cursor.pos()
1239             && !cursorPar()->isNewline(cursor.pos() - 1))
1240         {
1241                 cursorLeft(bv());
1242         }
1243
1244         while (!next_par->empty() && next_par->isNewline(0))
1245                 next_par->erase(0);
1246
1247         updateCounters();
1248         redoParagraph(cursorPar());
1249         redoParagraph(next_par);
1250
1251         // This check is necessary. Otherwise the new empty paragraph will
1252         // be deleted automatically. And it is more friendly for the user!
1253         if (cursor.pos() || isempty)
1254                 setCursor(next_par, 0);
1255         else
1256                 setCursor(cursorPar(), 0);
1257 }
1258
1259
1260 // convenience function
1261 void LyXText::redoParagraph()
1262 {
1263         clearSelection();
1264         redoParagraph(cursorPar());
1265         setCursorIntern(cursor.par(), cursor.pos());
1266 }
1267
1268
1269 // insert a character, moves all the following breaks in the
1270 // same Paragraph one to the right and make a rebreak
1271 void LyXText::insertChar(char c)
1272 {
1273         recordUndo(Undo::INSERT, this, cursor.par(), cursor.par());
1274
1275         // When the free-spacing option is set for the current layout,
1276         // disable the double-space checking
1277
1278         bool const freeSpacing = cursorPar()->layout()->free_spacing ||
1279                 cursorPar()->isFreeSpacing();
1280
1281         if (lyxrc.auto_number) {
1282                 static string const number_operators = "+-/*";
1283                 static string const number_unary_operators = "+-";
1284                 static string const number_seperators = ".,:";
1285
1286                 if (current_font.number() == LyXFont::ON) {
1287                         if (!IsDigit(c) && !contains(number_operators, c) &&
1288                             !(contains(number_seperators, c) &&
1289                               cursor.pos() >= 1 &&
1290                               cursor.pos() < cursorPar()->size() &&
1291                               getFont(cursorPar(), cursor.pos()).number() == LyXFont::ON &&
1292                               getFont(cursorPar(), cursor.pos() - 1).number() == LyXFont::ON)
1293                            )
1294                                 number(bv()); // Set current_font.number to OFF
1295                 } else if (IsDigit(c) &&
1296                            real_current_font.isVisibleRightToLeft()) {
1297                         number(bv()); // Set current_font.number to ON
1298
1299                         if (cursor.pos() > 0) {
1300                                 char const c = cursorPar()->getChar(cursor.pos() - 1);
1301                                 if (contains(number_unary_operators, c) &&
1302                                     (cursor.pos() == 1 ||
1303                                      cursorPar()->isSeparator(cursor.pos() - 2) ||
1304                                      cursorPar()->isNewline(cursor.pos() - 2))
1305                                   ) {
1306                                         setCharFont(
1307                                                     cursorPar(),
1308                                                     cursor.pos() - 1,
1309                                                     current_font);
1310                                 } else if (contains(number_seperators, c) &&
1311                                            cursor.pos() >= 2 &&
1312                                            getFont(
1313                                                    cursorPar(),
1314                                                    cursor.pos() - 2).number() == LyXFont::ON) {
1315                                         setCharFont(
1316                                                     cursorPar(),
1317                                                     cursor.pos() - 1,
1318                                                     current_font);
1319                                 }
1320                         }
1321                 }
1322         }
1323
1324
1325         // First check, if there will be two blanks together or a blank at
1326         // the beginning of a paragraph.
1327         // I decided to handle blanks like normal characters, the main
1328         // difference are the special checks when calculating the row.fill
1329         // (blank does not count at the end of a row) and the check here
1330
1331         // The bug is triggered when we type in a description environment:
1332         // The current_font is not changed when we go from label to main text
1333         // and it should (along with realtmpfont) when we type the space.
1334         // CHECK There is a bug here! (Asger)
1335
1336         // store the current font.  This is because of the use of cursor
1337         // movements. The moving cursor would refresh the current font
1338         LyXFont realtmpfont = real_current_font;
1339         LyXFont rawtmpfont = current_font;
1340
1341         if (!freeSpacing && IsLineSeparatorChar(c)) {
1342                 if ((cursor.pos() > 0
1343                      && cursorPar()->isLineSeparator(cursor.pos() - 1))
1344                     || (cursor.pos() > 0
1345                         && cursorPar()->isNewline(cursor.pos() - 1))
1346                     || (cursor.pos() == 0)) {
1347                         static bool sent_space_message = false;
1348                         if (!sent_space_message) {
1349                                 if (cursor.pos() == 0)
1350                                         bv()->owner()->message(_("You cannot insert a space at the beginning of a paragraph. Please read the Tutorial."));
1351                                 else
1352                                         bv()->owner()->message(_("You cannot type two spaces this way. Please read the Tutorial."));
1353                                 sent_space_message = true;
1354                         }
1355                         charInserted();
1356                         return;
1357                 }
1358         }
1359
1360         // Here case LyXText::InsertInset already inserted the character
1361         if (c != Paragraph::META_INSET)
1362                 cursorPar()->insertChar(cursor.pos(), c);
1363
1364         setCharFont(cursorPar(), cursor.pos(), rawtmpfont);
1365
1366         current_font = rawtmpfont;
1367         real_current_font = realtmpfont;
1368         redoParagraph(cursorPar());
1369         setCursor(cursor.par(), cursor.pos() + 1, false, cursor.boundary());
1370
1371         charInserted();
1372 }
1373
1374
1375 void LyXText::charInserted()
1376 {
1377         // Here we could call finishUndo for every 20 characters inserted.
1378         // This is from my experience how emacs does it. (Lgb)
1379         static unsigned int counter;
1380         if (counter < 20) {
1381                 ++counter;
1382         } else {
1383                 finishUndo();
1384                 counter = 0;
1385         }
1386 }
1387
1388
1389 void LyXText::prepareToPrint(ParagraphList::iterator pit,
1390            RowList::iterator const rit) const
1391 {
1392         double w = rit->fill();
1393         double fill_hfill = 0;
1394         double fill_label_hfill = 0;
1395         double fill_separator = 0;
1396         double x = 0;
1397
1398         bool const is_rtl =
1399                 pit->isRightToLeftPar(bv()->buffer()->params());
1400         if (is_rtl)
1401                 x = workWidth() > 0 ? rightMargin(*pit, *bv()->buffer(), *rit) : 0;
1402         else
1403                 x = workWidth() > 0 ? leftMargin(pit, *rit) : 0;
1404
1405         // is there a manual margin with a manual label
1406         LyXLayout_ptr const & layout = pit->layout();
1407
1408         if (layout->margintype == MARGIN_MANUAL
1409             && layout->labeltype == LABEL_MANUAL) {
1410                 /// We might have real hfills in the label part
1411                 int nlh = numberOfLabelHfills(*pit, *rit);
1412
1413                 // A manual label par (e.g. List) has an auto-hfill
1414                 // between the label text and the body of the
1415                 // paragraph too.
1416                 // But we don't want to do this auto hfill if the par
1417                 // is empty.
1418                 if (!pit->empty())
1419                         ++nlh;
1420
1421                 if (nlh && !pit->getLabelWidthString().empty()) {
1422                         fill_label_hfill = labelFill(pit, *rit) / double(nlh);
1423                 }
1424         }
1425
1426         // are there any hfills in the row?
1427         int const nh = numberOfHfills(*pit, *rit);
1428
1429         if (nh) {
1430                 if (w > 0)
1431                         fill_hfill = w / nh;
1432         // we don't have to look at the alignment if it is ALIGN_LEFT and
1433         // if the row is already larger then the permitted width as then
1434         // we force the LEFT_ALIGN'edness!
1435         } else if (int(rit->width()) < workWidth()) {
1436                 // is it block, flushleft or flushright?
1437                 // set x how you need it
1438                 int align;
1439                 if (pit->params().align() == LYX_ALIGN_LAYOUT) {
1440                         align = layout->align;
1441                 } else {
1442                         align = pit->params().align();
1443                 }
1444                 InsetOld * inset = 0;
1445                 // ERT insets should always be LEFT ALIGNED on screen
1446                 inset = pit->inInset();
1447                 if (inset && inset->owner() &&
1448                         inset->owner()->lyxCode() == InsetOld::ERT_CODE)
1449                 {
1450                         align = LYX_ALIGN_LEFT;
1451                 }
1452
1453                 // Display-style insets should always be on a centred row
1454                 // The test on pit->size() is to catch zero-size pars, which
1455                 // would trigger the assert in Paragraph::getInset().
1456                 inset = pit->size() ? pit->getInset(rit->pos()) : 0;
1457                 if (inset && inset->display()) {
1458                         align = LYX_ALIGN_CENTER;
1459                 }
1460                 
1461                 switch (align) {
1462             case LYX_ALIGN_BLOCK:
1463                 {
1464                         int const ns = numberOfSeparators(*pit, *rit);
1465                         RowList::iterator next_row = boost::next(rit);
1466                         bool disp_inset = false;
1467                         if (next_row != pit->rows.end()) {
1468                                 InsetOld * in = pit->getInset(next_row->pos());
1469                                 if (in)
1470                                         disp_inset = in->display();
1471                         }
1472                         // If we have separators, this is not the last row of a
1473                         // par, does not end in newline, and is not row above a
1474                         // display inset... then stretch it
1475                         if (ns
1476                                 && rit->end() < pit->size()
1477                                 && !pit->isNewline(next_row->pos() - 1)
1478                                 && !disp_inset
1479                                 ) {
1480                                         fill_separator = w / ns;
1481                         } else if (is_rtl) {
1482                                 x += w;
1483                         }
1484                         break;
1485             }
1486             case LYX_ALIGN_RIGHT:
1487                         x += w;
1488                         break;
1489             case LYX_ALIGN_CENTER:
1490                         x += w / 2;
1491                         break;
1492                 }
1493         }
1494
1495         computeBidiTables(*pit, *bv()->buffer(), *rit);
1496         if (is_rtl) {
1497                 pos_type body_pos = pit->beginningOfBody();
1498                 pos_type last = lastPos(*pit, *rit);
1499
1500                 if (body_pos > 0 &&
1501                                 (body_pos - 1 > last ||
1502                                  !pit->isLineSeparator(body_pos - 1))) {
1503                         x += font_metrics::width(layout->labelsep, getLabelFont(pit));
1504                         if (body_pos - 1 <= last)
1505                                 x += fill_label_hfill;
1506                 }
1507         }
1508
1509         rit->fill_hfill(fill_hfill);
1510         rit->fill_label_hfill(fill_label_hfill);
1511         rit->fill_separator(fill_separator);
1512         rit->x(x);
1513 }
1514
1515
1516 // important for the screen
1517
1518
1519 // the cursor set functions have a special mechanism. When they
1520 // realize, that you left an empty paragraph, they will delete it.
1521 // They also delete the corresponding row
1522
1523 void LyXText::cursorRightOneWord()
1524 {
1525         ::cursorRightOneWord(*this, cursor, ownerParagraphs());
1526         setCursor(cursorPar(), cursor.pos());
1527 }
1528
1529
1530 // Skip initial whitespace at end of word and move cursor to *start*
1531 // of prior word, not to end of next prior word.
1532 void LyXText::cursorLeftOneWord()
1533 {
1534         LyXCursor tmpcursor = cursor;
1535         ::cursorLeftOneWord(*this, tmpcursor, ownerParagraphs());
1536         setCursor(getPar(tmpcursor), tmpcursor.pos());
1537 }
1538
1539
1540 void LyXText::selectWord(word_location loc)
1541 {
1542         LyXCursor from = cursor;
1543         LyXCursor to = cursor;
1544         ::getWord(*this, from, to, loc, ownerParagraphs());
1545         if (cursor != from)
1546                 setCursor(from.par(), from.pos());
1547         if (to == from)
1548                 return;
1549         selection.cursor = cursor;
1550         setCursor(to.par(), to.pos());
1551         setSelection();
1552 }
1553
1554
1555 // Select the word currently under the cursor when no
1556 // selection is currently set
1557 bool LyXText::selectWordWhenUnderCursor(word_location loc)
1558 {
1559         if (!selection.set()) {
1560                 selectWord(loc);
1561                 return selection.set();
1562         }
1563         return false;
1564 }
1565
1566
1567 void LyXText::acceptChange()
1568 {
1569         if (!selection.set() && cursorPar()->size())
1570                 return;
1571
1572         if (selection.start.par() == selection.end.par()) {
1573                 LyXCursor & startc = selection.start;
1574                 LyXCursor & endc = selection.end;
1575                 recordUndo(Undo::INSERT, this, startc.par());
1576                 getPar(startc)->acceptChange(startc.pos(), endc.pos());
1577                 finishUndo();
1578                 clearSelection();
1579                 redoParagraph(getPar(startc));
1580                 setCursorIntern(startc.par(), 0);
1581         }
1582 #warning handle multi par selection
1583 }
1584
1585
1586 void LyXText::rejectChange()
1587 {
1588         if (!selection.set() && cursorPar()->size())
1589                 return;
1590
1591         if (selection.start.par() == selection.end.par()) {
1592                 LyXCursor & startc = selection.start;
1593                 LyXCursor & endc = selection.end;
1594                 recordUndo(Undo::INSERT, this, startc.par());
1595                 getPar(startc)->rejectChange(startc.pos(), endc.pos());
1596                 finishUndo();
1597                 clearSelection();
1598                 redoParagraph(getPar(startc));
1599                 setCursorIntern(startc.par(), 0);
1600         }
1601 #warning handle multi par selection
1602 }
1603
1604
1605 // This function is only used by the spellchecker for NextWord().
1606 // It doesn't handle LYX_ACCENTs and probably never will.
1607 WordLangTuple const LyXText::selectNextWordToSpellcheck(float & value)
1608 {
1609         if (the_locking_inset) {
1610                 WordLangTuple word =
1611                         the_locking_inset->selectNextWordToSpellcheck(bv(), value);
1612                 if (!word.word().empty()) {
1613                         value += float(cursor.y());
1614                         value /= float(height);
1615                         return word;
1616                 }
1617                 // we have to go on checking so move cursor to the next char
1618                 if (cursor.pos() == cursorPar()->size()) {
1619                         if (cursor.par() + 1 == int(ownerParagraphs().size()))
1620                                 return word;
1621                         cursor.par(cursor.par() + 1);
1622                         cursor.pos(0);
1623                 } else
1624                                 cursor.pos(cursor.pos() + 1);
1625         }
1626         int const tmppar = cursor.par();
1627
1628         // If this is not the very first word, skip rest of
1629         // current word because we are probably in the middle
1630         // of a word if there is text here.
1631         if (cursor.pos() || cursor.par() != 0) {
1632                 while (cursor.pos() < cursorPar()->size()
1633                        && cursorPar()->isLetter(cursor.pos()))
1634                         cursor.pos(cursor.pos() + 1);
1635         }
1636
1637         // Now, skip until we have real text (will jump paragraphs)
1638         while (true) {
1639                 ParagraphList::iterator cpit = cursorPar();
1640                 pos_type const cpos = cursor.pos();
1641
1642                 if (cpos == cpit->size()) {
1643                         if (cursor.par() + 1 != int(ownerParagraphs().size())) {
1644                                 cursor.par(cursor.par() + 1);
1645                                 cursor.pos(0);
1646                                 continue;
1647                         }
1648                         break;
1649                 }
1650
1651                 bool const is_good_inset = cpit->isInset(cpos)
1652                         && cpit->getInset(cpos)->allowSpellcheck();
1653
1654                 if (!isDeletedText(*cpit, cpos)
1655                     && (is_good_inset || cpit->isLetter(cpos)))
1656                         break;
1657
1658                 cursor.pos(cpos + 1);
1659         }
1660
1661         // now check if we hit an inset so it has to be a inset containing text!
1662         if (cursor.pos() < cursorPar()->size() &&
1663             cursorPar()->isInset(cursor.pos())) {
1664                 // lock the inset!
1665                 FuncRequest cmd(bv(), LFUN_INSET_EDIT, "left");
1666                 cursorPar()->getInset(cursor.pos())->dispatch(cmd);
1667                 // now call us again to do the above trick
1668                 // but obviously we have to start from down below ;)
1669                 return bv()->text->selectNextWordToSpellcheck(value);
1670         }
1671
1672         // Update the value if we changed paragraphs
1673         if (cursor.par() != tmppar) {
1674                 setCursor(cursor.par(), cursor.pos());
1675                 value = float(cursor.y())/float(height);
1676         }
1677
1678         // Start the selection from here
1679         selection.cursor = cursor;
1680
1681         string lang_code = getFont(cursorPar(), cursor.pos()).language()->code();
1682         // and find the end of the word (insets like optional hyphens
1683         // and ligature break are part of a word)
1684         while (cursor.pos() < cursorPar()->size()
1685                && cursorPar()->isLetter(cursor.pos())
1686                && !isDeletedText(*cursorPar(), cursor.pos()))
1687                 cursor.pos(cursor.pos() + 1);
1688
1689         // Finally, we copy the word to a string and return it
1690         string str;
1691         if (selection.cursor.pos() < cursor.pos()) {
1692                 for (pos_type i = selection.cursor.pos(); i < cursor.pos(); ++i) {
1693                         if (!cursorPar()->isInset(i))
1694                                 str += cursorPar()->getChar(i);
1695                 }
1696         }
1697         return WordLangTuple(str, lang_code);
1698 }
1699
1700
1701 // This one is also only for the spellchecker
1702 void LyXText::selectSelectedWord()
1703 {
1704         if (the_locking_inset) {
1705                 the_locking_inset->selectSelectedWord(bv());
1706                 return;
1707         }
1708         // move cursor to the beginning
1709         setCursor(selection.cursor.par(), selection.cursor.pos());
1710
1711         // set the sel cursor
1712         selection.cursor = cursor;
1713
1714         // now find the end of the word
1715         while (cursor.pos() < cursorPar()->size()
1716                && cursorPar()->isLetter(cursor.pos()))
1717                 cursor.pos(cursor.pos() + 1);
1718
1719         setCursor(cursorPar(), cursor.pos());
1720
1721         // finally set the selection
1722         setSelection();
1723 }
1724
1725
1726 // Delete from cursor up to the end of the current or next word.
1727 void LyXText::deleteWordForward()
1728 {
1729         if (cursorPar()->empty())
1730                 cursorRight(bv());
1731         else {
1732                 LyXCursor tmpcursor = cursor;
1733                 selection.set(true); // to avoid deletion
1734                 cursorRightOneWord();
1735                 setCursor(tmpcursor, tmpcursor.par(), tmpcursor.pos());
1736                 selection.cursor = cursor;
1737                 cursor = tmpcursor;
1738                 setSelection();
1739                 cutSelection(true, false);
1740         }
1741 }
1742
1743
1744 // Delete from cursor to start of current or prior word.
1745 void LyXText::deleteWordBackward()
1746 {
1747         if (cursorPar()->empty())
1748                 cursorLeft(bv());
1749         else {
1750                 LyXCursor tmpcursor = cursor;
1751                 selection.set(true); // to avoid deletion
1752                 cursorLeftOneWord();
1753                 setCursor(tmpcursor, tmpcursor.par(), tmpcursor.pos());
1754                 selection.cursor = cursor;
1755                 cursor = tmpcursor;
1756                 setSelection();
1757                 cutSelection(true, false);
1758         }
1759 }
1760
1761
1762 // Kill to end of line.
1763 void LyXText::deleteLineForward()
1764 {
1765         if (cursorPar()->empty())
1766                 // Paragraph is empty, so we just go to the right
1767                 cursorRight(bv());
1768         else {
1769                 LyXCursor tmpcursor = cursor;
1770                 // We can't store the row over a regular setCursor
1771                 // so we set it to 0 and reset it afterwards.
1772                 selection.set(true); // to avoid deletion
1773                 cursorEnd();
1774                 setCursor(tmpcursor, tmpcursor.par(), tmpcursor.pos());
1775                 selection.cursor = cursor;
1776                 cursor = tmpcursor;
1777                 setSelection();
1778                 // What is this test for ??? (JMarc)
1779                 if (!selection.set()) {
1780                         deleteWordForward();
1781                 } else {
1782                         cutSelection(true, false);
1783                 }
1784         }
1785 }
1786
1787
1788 void LyXText::changeCase(LyXText::TextCase action)
1789 {
1790         LyXCursor from;
1791         LyXCursor to;
1792
1793         if (selection.set()) {
1794                 from = selection.start;
1795                 to = selection.end;
1796         } else {
1797                 from = cursor;
1798                 ::getWord(*this, from, to, lyx::PARTIAL_WORD, ownerParagraphs());
1799                 setCursor(to.par(), to.pos() + 1);
1800         }
1801
1802         recordUndo(Undo::ATOMIC, this, from.par(), to.par());
1803
1804         pos_type pos = from.pos();
1805         int par = from.par();
1806
1807         while (par != int(ownerParagraphs().size()) &&
1808                (pos != to.pos() || par != to.par())) {
1809                 ParagraphList::iterator pit = getPar(par);
1810                 if (pos == pit->size()) {
1811                         ++par;
1812                         pos = 0;
1813                         continue;
1814                 }
1815                 unsigned char c = pit->getChar(pos);
1816                 if (c != Paragraph::META_INSET) {
1817                         switch (action) {
1818                         case text_lowercase:
1819                                 c = lowercase(c);
1820                                 break;
1821                         case text_capitalization:
1822                                 c = uppercase(c);
1823                                 action = text_lowercase;
1824                                 break;
1825                         case text_uppercase:
1826                                 c = uppercase(c);
1827                                 break;
1828                         }
1829                 }
1830 #warning changes
1831                 pit->setChar(pos, c);
1832                 ++pos;
1833         }
1834 }
1835
1836
1837 void LyXText::Delete()
1838 {
1839         // this is a very easy implementation
1840
1841         LyXCursor old_cursor = cursor;
1842         int const old_cur_par_id = cursorPar()->id();
1843         int const old_cur_par_prev_id =
1844                 old_cursor.par() ? getPar(old_cursor.par() - 1)->id() : -1;
1845
1846         // just move to the right
1847         cursorRight(bv());
1848
1849         // CHECK Look at the comment here.
1850         // This check is not very good...
1851         // The cursorRightIntern calls DeleteEmptyParagraphMechanism
1852         // and that can very well delete the par or par->previous in
1853         // old_cursor. Will a solution where we compare paragraph id's
1854         //work better?
1855         int iid = cursor.par() ? getPar(cursor.par() - 1)->id() : -1;
1856         if (iid == old_cur_par_prev_id && cursorPar()->id() != old_cur_par_id) {
1857                 // delete-empty-paragraph-mechanism has done it
1858                 return;
1859         }
1860
1861         // if you had success make a backspace
1862         if (old_cursor.par() != cursor.par() || old_cursor.pos() != cursor.pos()) {
1863                 recordUndo(Undo::DELETE, this, old_cursor.par());
1864                 backspace();
1865         }
1866 }
1867
1868
1869 void LyXText::backspace()
1870 {
1871         // Get the font that is used to calculate the baselineskip
1872         ParagraphList::iterator pit = cursorPar();
1873         pos_type lastpos = pit->size();
1874
1875         if (cursor.pos() == 0) {
1876                 // The cursor is at the beginning of a paragraph,
1877                 // so the the backspace will collapse two paragraphs into one.
1878
1879                 // but it's not allowed unless it's new
1880                 if (pit->isChangeEdited(0, pit->size()))
1881                         return;
1882
1883                 // we may paste some paragraphs
1884
1885                 // is it an empty paragraph?
1886
1887                 if (lastpos == 0 || (lastpos == 1 && pit->isSeparator(0))) {
1888                         // This is an empty paragraph and we delete it just
1889                         // by moving the cursor one step
1890                         // left and let the DeleteEmptyParagraphMechanism
1891                         // handle the actual deletion of the paragraph.
1892
1893                         if (cursor.par()) {
1894                                 ParagraphList::iterator tmppit = getPar(cursor.par() - 1);
1895                                 if (cursorPar()->layout() == tmppit->layout()
1896                                     && cursorPar()->getAlign() == tmppit->getAlign()) {
1897                                         // Inherit bottom DTD from the paragraph below.
1898                                         // (the one we are deleting)
1899                                         tmppit->params().lineBottom(cursorPar()->params().lineBottom());
1900                                         tmppit->params().spaceBottom(cursorPar()->params().spaceBottom());
1901                                         tmppit->params().pagebreakBottom(cursorPar()->params().pagebreakBottom());
1902                                 }
1903
1904                                 cursorLeft(bv());
1905
1906                                 // the layout things can change the height of a row !
1907                                 redoParagraph();
1908                                 return;
1909                         }
1910                 }
1911
1912                 if (cursor.par() != 0)
1913                         recordUndo(Undo::DELETE, this, cursor.par() - 1, cursor.par());
1914
1915                 ParagraphList::iterator tmppit = cursorPar();
1916                 // We used to do cursorLeftIntern() here, but it is
1917                 // not a good idea since it triggers the auto-delete
1918                 // mechanism. So we do a cursorLeftIntern()-lite,
1919                 // without the dreaded mechanism. (JMarc)
1920                 if (cursor.par() != 0) {
1921                         // steps into the above paragraph.
1922                         setCursorIntern(cursor.par() - 1,
1923                                         getPar(cursor.par() - 1)->size(),
1924                                         false);
1925                 }
1926
1927                 // Pasting is not allowed, if the paragraphs have different
1928                 // layout. I think it is a real bug of all other
1929                 // word processors to allow it. It confuses the user.
1930                 // Correction: Pasting is always allowed with standard-layout
1931                 Buffer & buf = *bv()->buffer();
1932                 BufferParams const & bufparams = buf.params();
1933                 LyXTextClass const & tclass = bufparams.getLyXTextClass();
1934
1935                 if (cursorPar() != tmppit
1936                     && (cursorPar()->layout() == tmppit->layout()
1937                         || tmppit->layout() == tclass.defaultLayout())
1938                     && cursorPar()->getAlign() == tmppit->getAlign()) {
1939                         mergeParagraph(bufparams,
1940                                        buf.paragraphs(), cursorPar());
1941
1942                         if (cursor.pos() && cursorPar()->isSeparator(cursor.pos() - 1))
1943                                 cursor.pos(cursor.pos() - 1);
1944
1945                         // the row may have changed, block, hfills etc.
1946                         updateCounters();
1947                         setCursor(cursor.par(), cursor.pos(), false);
1948                 }
1949         } else {
1950                 // this is the code for a normal backspace, not pasting
1951                 // any paragraphs
1952                 recordUndo(Undo::DELETE, this, cursor.par());
1953                 // We used to do cursorLeftIntern() here, but it is
1954                 // not a good idea since it triggers the auto-delete
1955                 // mechanism. So we do a cursorLeftIntern()-lite,
1956                 // without the dreaded mechanism. (JMarc)
1957                 setCursorIntern(cursor.par(), cursor.pos() - 1,
1958                                 false, cursor.boundary());
1959                 cursorPar()->erase(cursor.pos());
1960         }
1961
1962         lastpos = cursorPar()->size();
1963         if (cursor.pos() == lastpos)
1964                 setCurrentFont();
1965
1966         redoParagraph();
1967         setCursor(cursor.par(), cursor.pos(), false, !cursor.boundary());
1968 }
1969
1970
1971 ParagraphList::iterator LyXText::cursorPar() const
1972 {
1973         return getPar(cursor.par());
1974 }
1975
1976
1977 ParagraphList::iterator LyXText::getPar(LyXCursor const & cur) const
1978 {
1979         return getPar(cur.par());
1980 }
1981
1982
1983 ParagraphList::iterator LyXText::getPar(int par) const
1984 {
1985         BOOST_ASSERT(par >= 0);
1986         BOOST_ASSERT(par < int(ownerParagraphs().size()));
1987         ParagraphList::iterator pit = ownerParagraphs().begin();
1988         std::advance(pit, par);
1989         return pit;
1990 }
1991
1992
1993
1994 RowList::iterator LyXText::cursorRow() const
1995 {
1996         return getRow(*cursorPar(), cursor.pos());
1997 }
1998
1999
2000 RowList::iterator LyXText::getRow(LyXCursor const & cur) const
2001 {
2002         return getRow(*getPar(cur), cur.pos());
2003 }
2004
2005
2006 RowList::iterator LyXText::getRow(Paragraph & par, pos_type pos) const
2007 {
2008         RowList::iterator rit = boost::prior(par.rows.end());
2009         RowList::iterator const begin = par.rows.begin();
2010
2011         while (rit != begin && rit->pos() > pos)
2012                 --rit;
2013
2014         return rit;
2015 }
2016
2017
2018 RowList::iterator
2019 LyXText::getRowNearY(int y, ParagraphList::iterator & pit) const
2020 {
2021         //lyxerr << "getRowNearY: y " << y << endl;
2022
2023         pit = boost::prior(ownerParagraphs().end());
2024
2025         RowList::iterator rit = lastRow();
2026         RowList::iterator rbegin = firstRow();
2027
2028         while (rit != rbegin && int(pit->y + rit->y_offset()) > y)
2029                 previousRow(pit, rit);
2030
2031         return rit;
2032 }
2033
2034
2035 int LyXText::getDepth() const
2036 {
2037         return cursorPar()->getDepth();
2038 }
2039
2040
2041 RowList::iterator LyXText::firstRow() const
2042 {
2043         return ownerParagraphs().front().rows.begin();
2044 }
2045
2046
2047 RowList::iterator LyXText::lastRow() const
2048 {
2049         return boost::prior(endRow());
2050 }
2051
2052
2053 RowList::iterator LyXText::endRow() const
2054 {
2055         return ownerParagraphs().back().rows.end();
2056 }
2057
2058
2059 void LyXText::nextRow(ParagraphList::iterator & pit,
2060         RowList::iterator & rit) const
2061 {
2062         ++rit;
2063         if (rit == pit->rows.end()) {
2064                 ++pit;
2065                 if (pit == ownerParagraphs().end())
2066                         --pit;
2067                 else
2068                         rit = pit->rows.begin();
2069         }
2070 }
2071
2072
2073 void LyXText::previousRow(ParagraphList::iterator & pit,
2074         RowList::iterator & rit) const
2075 {
2076         if (rit != pit->rows.begin())
2077                 --rit;
2078         else {
2079                 BOOST_ASSERT(pit != ownerParagraphs().begin());
2080                 --pit;
2081                 rit = boost::prior(pit->rows.end());
2082         }
2083 }
2084
2085
2086 string LyXText::selectionAsString(Buffer const & buffer, bool label) const
2087 {
2088         if (!selection.set())
2089                 return string();
2090
2091         // should be const ...
2092         ParagraphList::iterator startpit = getPar(selection.start);
2093         ParagraphList::iterator endpit = getPar(selection.end);
2094         size_t const startpos = selection.start.pos();
2095         size_t const endpos = selection.end.pos();
2096
2097         if (startpit == endpit)
2098                 return startpit->asString(buffer, startpos, endpos, label);
2099
2100         // First paragraph in selection
2101         string result =
2102                 startpit->asString(buffer, startpos, startpit->size(), label) + "\n\n";
2103
2104         // The paragraphs in between (if any)
2105         ParagraphList::iterator pit = startpit;
2106         for (++pit; pit != endpit; ++pit)
2107                 result += pit->asString(buffer, 0, pit->size(), label) + "\n\n";
2108
2109         // Last paragraph in selection
2110         result += endpit->asString(buffer, 0, endpos, label);
2111
2112         return result;
2113 }
2114
2115
2116 int LyXText::parOffset(ParagraphList::iterator pit) const
2117 {
2118         return std::distance(ownerParagraphs().begin(), pit);
2119 }
2120
2121
2122 int LyXText::redoParagraphInternal(ParagraphList::iterator pit)
2123 {
2124         // remove rows of paragraph, keep track of height changes
2125         height -= pit->height;
2126         pit->rows.clear();
2127
2128         // redo insets
2129         InsetList::iterator ii = pit->insetlist.begin();
2130         InsetList::iterator iend = pit->insetlist.end();
2131         for (; ii != iend; ++ii) {
2132                 Dimension dim;
2133                 MetricsInfo mi(bv(), getFont(pit, ii->pos), workWidth());
2134                 ii->inset->metrics(mi, dim);
2135         }
2136
2137         // rebreak the paragraph
2138         int par_width = 0;
2139         int const ww = workWidth();
2140         pit->height = 0;
2141
2142         for (pos_type z = 0; z < pit->size() + 1; ) {
2143                 Row row(z);
2144                 z = rowBreakPoint(pit, row) + 1;
2145                 row.end(z);
2146                 pit->rows.push_back(row);
2147                 RowList::iterator rit = boost::prior(pit->rows.end());
2148                 int const f = fill(pit, *rit, ww);
2149                 int const w = ww - f;
2150                 par_width = std::max(par_width, w);
2151                 rit->fill(f);
2152                 rit->width(w);
2153                 prepareToPrint(pit, rit);
2154                 setHeightOfRow(pit, *rit);
2155                 rit->y_offset(pit->height);
2156                 pit->height += rit->height();
2157         }
2158         height += pit->height;
2159
2160         //lyxerr << "redoParagraph: " << pit->rows.size() << " rows\n";
2161         return par_width;
2162 }
2163
2164
2165 int LyXText::redoParagraphs(ParagraphList::iterator start,
2166   ParagraphList::iterator end)
2167 {
2168         int pars_width = 0;
2169         for ( ; start != end; ++start) {
2170                 int par_width = redoParagraphInternal(start);
2171                 pars_width = std::max(par_width, pars_width);
2172         }
2173         updateRowPositions();
2174         return pars_width;
2175 }
2176
2177
2178 void LyXText::redoParagraph(ParagraphList::iterator pit)
2179 {
2180         redoParagraphInternal(pit);
2181         updateRowPositions();
2182 }
2183
2184
2185 void LyXText::fullRebreak()
2186 {
2187         redoParagraphs(ownerParagraphs().begin(), ownerParagraphs().end());
2188         redoCursor();
2189         selection.cursor = cursor;
2190 }
2191
2192
2193 void LyXText::metrics(MetricsInfo & mi, Dimension & dim)
2194 {
2195         lyxerr << "LyXText::metrics: width: " << mi.base.textwidth
2196                 << " workWidth: " << workWidth() << "\nfont: " << mi.base.font << endl;
2197         //BOOST_ASSERT(mi.base.textwidth);
2198
2199         // rebuild row cache
2200         width  = 0;
2201         ///height = 0;
2202
2203         //anchor_y_ = 0;
2204         width = redoParagraphs(ownerParagraphs().begin(), ownerParagraphs().end());
2205
2206         // final dimension
2207         dim.asc = firstRow()->ascent_of_text();
2208         dim.des = height - dim.asc;
2209         dim.wid = std::max(mi.base.textwidth, int(width));
2210 }