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