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