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