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