]> git.lyx.org Git - lyx.git/blob - src/text.C
remove Row::pit_ member
[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 tmprit = rowlist_.begin();
609                 while (tmprit != rowlist_.end()
610                        && getPar(tmprit) != pit)
611                         ++tmprit;
612
613                 int minfill = tmprit->fill();
614                 while (boost::next(tmprit) != rowlist_.end() &&
615                        getPar(boost::next(tmprit)) == pit) {
616                         ++tmprit;
617                         if (tmprit->fill() < minfill)
618                                 minfill = tmprit->fill();
619                 }
620
621                 x += font_metrics::signedWidth(layout->leftmargin,
622                         tclass.defaultfont());
623                 x += minfill;
624         }
625         break;
626         }
627
628         if (workWidth() > 0 && !pit->params().leftIndent().zero()) {
629                 LyXLength const len = pit->params().leftIndent();
630                 int const tw = inset_owner ?
631                         inset_owner->latexTextWidth(bv()) : workWidth();
632                 x += len.inPixels(tw);
633         }
634
635         LyXAlignment align;
636
637         if (pit->params().align() == LYX_ALIGN_LAYOUT)
638                 align = layout->align;
639         else
640                 align = pit->params().align();
641
642         // set the correct parindent
643         if (row.pos() == 0) {
644                 if ((layout->labeltype == LABEL_NO_LABEL
645                      || layout->labeltype == LABEL_TOP_ENVIRONMENT
646                      || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
647                      || (layout->labeltype == LABEL_STATIC
648                          && layout->latextype == LATEX_ENVIRONMENT
649                          && !isFirstInSequence(pit, ownerParagraphs())))
650                     && align == LYX_ALIGN_BLOCK
651                     && !pit->params().noindent()
652                         // in tabulars and ert paragraphs are never indented!
653                         && (!pit->inInset() || !pit->inInset()->owner() ||
654                                 (pit->inInset()->owner()->lyxCode() != InsetOld::TABULAR_CODE &&
655                                  pit->inInset()->owner()->lyxCode() != InsetOld::ERT_CODE))
656                     && (pit->layout() != tclass.defaultLayout() ||
657                         bv()->buffer()->params.paragraph_separation ==
658                         BufferParams::PARSEP_INDENT)) {
659                         x += font_metrics::signedWidth(parindent,
660                                                   tclass.defaultfont());
661                 } else if (layout->labeltype == LABEL_BIBLIO) {
662                         // ale970405 Right width for bibitems
663                         x += bibitemMaxWidth(bv(), tclass.defaultfont());
664                 }
665         }
666
667         return x;
668 }
669
670
671 int LyXText::rightMargin(ParagraphList::iterator pit,
672         Buffer const & buf, Row const & row) const
673 {
674         InsetOld * ins;
675
676         if (row.pos() < pit->size())
677                 if ((pit->getChar(row.pos()) == Paragraph::META_INSET) &&
678                     (ins = pit->getInset(row.pos())) &&
679                     (ins->needFullRow() || ins->display()))
680                         return PAPER_MARGIN;
681
682         LyXTextClass const & tclass = buf.params.getLyXTextClass();
683         LyXLayout_ptr const & layout = pit->layout();
684
685         return PAPER_MARGIN
686                 + font_metrics::signedWidth(tclass.rightmargin(),
687                                        tclass.defaultfont());
688                 + font_metrics::signedWidth(layout->rightmargin,
689                                        tclass.defaultfont())
690                 * 4 / (pit->getDepth() + 4);
691 }
692
693
694 int LyXText::labelEnd(ParagraphList::iterator pit, Row const & row) const
695 {
696         if (pit->layout()->margintype == MARGIN_MANUAL) {
697                 Row tmprow = row;
698                 tmprow.pos(pit->size());
699                 // return the beginning of the body
700                 return leftMargin(pit, tmprow);
701         }
702
703         // LabelEnd is only needed if the layout
704         // fills a flushleft label.
705         return 0;
706 }
707
708
709 namespace {
710
711 // this needs special handling - only newlines count as a break point
712 pos_type addressBreakPoint(pos_type i, Paragraph const & par)
713 {
714         for (; i < par.size(); ++i) {
715                 if (par.isNewline(i))
716                         return i;
717         }
718
719         return par.size();
720 }
721
722 };
723
724
725 pos_type LyXText::rowBreakPoint(ParagraphList::iterator pit,
726         Row const & row) const
727 {
728         // maximum pixel width of a row.
729         int width = workWidth() - rightMargin(pit, *bv()->buffer(), row);
730
731         // inset->textWidth() returns -1 via workWidth(),
732         // but why ?
733         if (width < 0)
734                 return pit->size();
735
736         LyXLayout_ptr const & layout = pit->layout();
737
738         if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX)
739                 return addressBreakPoint(row.pos(), *pit);
740
741         pos_type const pos = row.pos();
742         pos_type const body_pos = pit->beginningOfBody();
743         pos_type const last = pit->size();
744         pos_type point = last;
745
746         if (pos == last)
747                 return last;
748
749         // Now we iterate through until we reach the right margin
750         // or the end of the par, then choose the possible break
751         // nearest that.
752
753         int const left = leftMargin(pit, row);
754         int x = left;
755
756         // pixel width since last breakpoint
757         int chunkwidth = 0;
758         bool fullrow = false;
759
760         pos_type i = pos;
761
762         // We re-use the font resolution for the entire font span when possible
763         LyXFont font = getFont(pit, i);
764         lyx::pos_type endPosOfFontSpan = pit->getEndPosOfFontSpan(i);
765
766         for (; i < last; ++i) {
767                 if (pit->isNewline(i)) {
768                         point = i;
769                         break;
770                 }
771
772                 char const c = pit->getChar(i);
773
774                 int thiswidth;
775
776                 // add the auto-hfill from label end to the body
777                 if (body_pos && i == body_pos) {
778                         thiswidth = font_metrics::width(layout->labelsep, getLabelFont(pit));
779                         if (pit->isLineSeparator(i - 1))
780                                 thiswidth -= singleWidth(pit, i - 1);
781                         int left_margin = labelEnd(pit, row);
782                         if (thiswidth + x < left_margin)
783                                 thiswidth = left_margin - x;
784                         thiswidth += singleWidth(pit, i, c);
785                 } else {
786                         // Manual inlined optimised version of common case of "thiswidth = singleWidth(pit, i, c);"
787                         if (IsPrintable(c)) {
788                                 if (pos > endPosOfFontSpan) {
789                                         // We need to get the next font
790                                         font = getFont(pit, i);
791                                         endPosOfFontSpan = pit->getEndPosOfFontSpan(i);
792                                 }
793                                 if (! font.language()->RightToLeft()) {
794                                         thiswidth = font_metrics::width(c, font);
795                                 } else {
796                                         // Fall-back to normal case
797                                         thiswidth = singleWidth(pit, i, c);
798                                         // And flush font cache
799                                         endPosOfFontSpan = 0;
800                                 }
801                         } else {
802                                 // Fall-back to normal case
803                                 thiswidth = singleWidth(pit, i, c);
804                                 // And flush font cache
805                                 endPosOfFontSpan = 0;
806                         }
807                 }
808
809                 x += thiswidth;
810                 chunkwidth += thiswidth;
811
812                 InsetOld * in = pit->isInset(i) ? pit->getInset(i) : 0;
813                 fullrow = in && (in->display() || in->needFullRow());
814
815                 // break before a character that will fall off
816                 // the right of the row
817                 if (x >= width) {
818                         // if no break before or we are at an inset
819                         // that will take up a row, break here
820                         if (point == last || fullrow || chunkwidth >= (width - left)) {
821                                 if (pos < i)
822                                         point = i - 1;
823                                 else
824                                         point = i;
825                         }
826                         break;
827                 }
828
829                 if (!in || in->isChar()) {
830                         // some insets are line separators too
831                         if (pit->isLineSeparator(i)) {
832                                 point = i;
833                                 chunkwidth = 0;
834                         }
835                         continue;
836                 }
837
838                 if (!fullrow)
839                         continue;
840
841                 // full row insets start at a new row
842                 if (i == pos) {
843                         if (pos < last - 1) {
844                                 point = i;
845                                 if (pit->isLineSeparator(i + 1))
846                                         ++point;
847                         } else {
848                                 // to avoid extra rows
849                                 point = last;
850                         }
851                 } else {
852                         point = i - 1;
853                 }
854
855                 return point;
856         }
857
858         if (point == last && x >= width) {
859                 // didn't find one, break at the point we reached the edge
860                 point = i;
861         } else if (i == last && x < width) {
862                 // found one, but we fell off the end of the par, so prefer
863                 // that.
864                 point = last;
865         }
866
867         // manual labels cannot be broken in LaTeX. But we
868         // want to make our on-screen rendering of footnotes
869         // etc. still break
870         if (!fullrow && body_pos && point < body_pos)
871                 point = body_pos - 1;
872
873         return point;
874 }
875
876
877 // returns the minimum space a row needs on the screen in pixel
878 int LyXText::fill(RowList::iterator row, int paper_width) const
879 {
880         if (paper_width < 0)
881                 return 0;
882
883         int w;
884         // get the pure distance
885         ParagraphList::iterator pit = getPar(row);
886         pos_type const last = lastPrintablePos(*this, pit, row);
887
888         LyXLayout_ptr const & layout = pit->layout();
889
890         // special handling of the right address boxes
891         if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX) {
892                 int const tmpfill = row->fill();
893                 row->fill(0); // the minfill in MarginLeft()
894                 w = leftMargin(pit, *row);
895                 row->fill(tmpfill);
896         } else
897                 w = leftMargin(pit, *row);
898
899         pos_type const body_pos = pit->beginningOfBody();
900         pos_type i = row->pos();
901
902         if (! pit->empty() && i <= last) {
903                 // We re-use the font resolution for the entire span when possible
904                 LyXFont font = getFont(pit, i);
905                 lyx::pos_type endPosOfFontSpan = pit->getEndPosOfFontSpan(i);
906                 while (i <= last) {
907                         if (body_pos > 0 && i == body_pos) {
908                                 w += font_metrics::width(layout->labelsep, getLabelFont(pit));
909                                 if (pit->isLineSeparator(i - 1))
910                                         w -= singleWidth(pit, i - 1);
911                                 int left_margin = labelEnd(pit, *row);
912                                 if (w < left_margin)
913                                         w = left_margin;
914                         }
915                         { // Manual inlined an optimised version of the common case of "w += singleWidth(pit, i);"
916                                 char const c = pit->getChar(i);
917
918                                 if (IsPrintable(c)) {
919                                         if (i > endPosOfFontSpan) {
920                                                 // We need to get the next font
921                                                 font = getFont(pit, i);
922                                                 endPosOfFontSpan = pit->getEndPosOfFontSpan(i);
923                                         }
924                                         if (!font.language()->RightToLeft()) {
925                                                 w += font_metrics::width(c, font);
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                                 } else {
933                                         // Fall-back to the normal case
934                                         w += singleWidth(pit, i, c);
935                                         // And flush font cache
936                                         endPosOfFontSpan = 0;
937                                 }
938                         }
939                         ++i;
940                 }
941         }
942         if (body_pos > 0 && body_pos > last) {
943                 w += font_metrics::width(layout->labelsep, getLabelFont(pit));
944                 if (last >= 0 && pit->isLineSeparator(last))
945                         w -= singleWidth(pit, last);
946                 int const left_margin = labelEnd(pit, *row);
947                 if (w < left_margin)
948                         w = left_margin;
949         }
950
951         int const fill = paper_width - w - rightMargin(pit, *bv()->buffer(), *row);
952
953         // If this case happens, it means that our calculation
954         // of the widths of the chars when we do rowBreakPoint()
955         // went wrong for some reason. Typically in list bodies.
956         // Things just about hobble on anyway, though you'll end
957         // up with a "fill_separator" less than zero, which corresponds
958         // to inter-word spacing being too small. Hopefully this problem
959         // will die when the label hacks die.
960         if (lyxerr.debugging() && fill < 0) {
961                 lyxerr[Debug::GUI] << "Eek, fill() was < 0: " << fill
962                         << " w " << w << " paper_width " << paper_width
963                         << " right margin " << rightMargin(pit, *bv()->buffer(), *row) << endl;
964         }
965         return fill;
966 }
967
968
969 // returns the minimum space a manual label needs on the screen in pixel
970 int LyXText::labelFill(ParagraphList::iterator pit, Row const & row) const
971 {
972         pos_type last = pit->beginningOfBody();
973
974         Assert(last > 0);
975
976         // -1 because a label ends either with a space that is in the label,
977         // or with the beginning of a footnote that is outside the label.
978         --last;
979
980         // a separator at this end does not count
981         if (pit->isLineSeparator(last))
982                 --last;
983
984         int w = 0;
985         pos_type i = row.pos();
986         while (i <= last) {
987                 w += singleWidth(pit, i);
988                 ++i;
989         }
990
991         int fill = 0;
992         string const & labwidstr = pit->params().labelWidthString();
993         if (!labwidstr.empty()) {
994                 LyXFont const labfont = getLabelFont(pit);
995                 int const labwidth = font_metrics::width(labwidstr, labfont);
996                 fill = max(labwidth - w, 0);
997         }
998
999         return fill;
1000 }
1001
1002
1003 LColor::color LyXText::backgroundColor() const
1004 {
1005         if (inset_owner)
1006                 return inset_owner->backgroundColor();
1007         else
1008                 return LColor::background;
1009 }
1010
1011
1012 void LyXText::setHeightOfRow(RowList::iterator rit)
1013 {
1014         Assert(rit != rows().end());
1015
1016         // get the maximum ascent and the maximum descent
1017         double layoutasc = 0;
1018         double layoutdesc = 0;
1019         double tmptop = 0;
1020
1021         // ok, let us initialize the maxasc and maxdesc value.
1022         // Only the fontsize count. The other properties
1023         // are taken from the layoutfont. Nicer on the screen :)
1024         ParagraphList::iterator pit = getPar(rit);
1025
1026         LyXLayout_ptr const & layout = pit->layout();
1027
1028         // as max get the first character of this row then it can increase but not
1029         // decrease the height. Just some point to start with so we don't have to
1030         // do the assignment below too often.
1031         LyXFont font = getFont(pit, rit->pos());
1032         LyXFont::FONT_SIZE const tmpsize = font.size();
1033         font = getLayoutFont(pit);
1034         LyXFont::FONT_SIZE const size = font.size();
1035         font.setSize(tmpsize);
1036
1037         LyXFont labelfont = getLabelFont(pit);
1038
1039         double spacing_val = 1.0;
1040         if (!pit->params().spacing().isDefault())
1041                 spacing_val = pit->params().spacing().getValue();
1042         else
1043                 spacing_val = bv()->buffer()->params.spacing.getValue();
1044         //lyxerr << "spacing_val = " << spacing_val << endl;
1045
1046         int maxasc  = int(font_metrics::maxAscent(font) *
1047                           layout->spacing.getValue() * spacing_val);
1048         int maxdesc = int(font_metrics::maxDescent(font) *
1049                           layout->spacing.getValue() * spacing_val);
1050
1051         pos_type const pos_end = lastPos(*this, pit, rit);
1052         int labeladdon = 0;
1053         int maxwidth = 0;
1054
1055         if (!pit->empty()) {
1056                 // We re-use the font resolution for the entire font span when possible
1057                 LyXFont font = getFont(pit, rit->pos());
1058                 lyx::pos_type endPosOfFontSpan = pit->getEndPosOfFontSpan(rit->pos());
1059
1060                 // Optimisation
1061                 Paragraph const & par = *pit;
1062
1063                 // Check if any insets are larger
1064                 for (pos_type pos = rit->pos(); pos <= pos_end; ++pos) {
1065                         // Manual inlined optimised version of common case of
1066                         // "maxwidth += singleWidth(pit, pos);"
1067                         char const c = par.getChar(pos);
1068
1069                         if (IsPrintable(c)) {
1070                                 if (pos > endPosOfFontSpan) {
1071                                         // We need to get the next font
1072                                         font = getFont(pit, pos);
1073                                         endPosOfFontSpan = par.getEndPosOfFontSpan(pos);
1074                                 }
1075                                 if (! font.language()->RightToLeft()) {
1076                                         maxwidth += font_metrics::width(c, font);
1077                                 } else {
1078                                         // Fall-back to normal case
1079                                         maxwidth += singleWidth(pit, pos, c);
1080                                         // And flush font cache
1081                                         endPosOfFontSpan = 0;
1082                                 }
1083                         } else {
1084                                 // Special handling of insets - are any larger?
1085                                 if (par.isInset(pos)) {
1086                                         InsetOld const * tmpinset = par.getInset(pos);
1087                                         if (tmpinset) {
1088 #if 1 // this is needed for deep update on initialitation
1089 #warning inset->update FIXME
1090                                                 //tmpinset->update(bv());
1091                                                 LyXFont const tmpfont = getFont(pit, pos);
1092                                                 Dimension dim;
1093                                                 MetricsInfo mi(bv(), tmpfont, workWidth());
1094                                                 tmpinset->metrics(mi, dim);
1095                                                 maxwidth += dim.wid;
1096                                                 maxasc = max(maxasc, dim.asc);
1097                                                 maxdesc = max(maxdesc, dim.des);
1098 #else
1099                                                 maxwidth += tmpinset->width();
1100                                                 maxasc = max(maxasc, tmpinset->ascent());
1101                                                 maxdesc = max(maxdesc, tmpinset->descent());
1102 #endif
1103                                         }
1104                                 } else {
1105                                         // Fall-back to normal case
1106                                         maxwidth += singleWidth(pit, pos, c);
1107                                         // And flush font cache
1108                                         endPosOfFontSpan = 0;
1109                                 }
1110                         }
1111                 }
1112         }
1113
1114         // Check if any custom fonts are larger (Asger)
1115         // This is not completely correct, but we can live with the small,
1116         // cosmetic error for now.
1117         LyXFont::FONT_SIZE maxsize =
1118                 pit->highestFontInRange(rit->pos(), pos_end, size);
1119         if (maxsize > font.size()) {
1120                 font.setSize(maxsize);
1121                 maxasc = max(maxasc, font_metrics::maxAscent(font));
1122                 maxdesc = max(maxdesc, font_metrics::maxDescent(font));
1123         }
1124
1125         // This is nicer with box insets:
1126         ++maxasc;
1127         ++maxdesc;
1128
1129         rit->ascent_of_text(maxasc);
1130
1131         // is it a top line?
1132         if (!rit->pos()) {
1133
1134                 // some parksips VERY EASY IMPLEMENTATION
1135                 if (bv()->buffer()->params.paragraph_separation ==
1136                         BufferParams::PARSEP_SKIP)
1137                 {
1138                         if (layout->isParagraph()
1139                                 && pit->getDepth() == 0
1140                                 && pit != ownerParagraphs().begin())
1141                         {
1142                                 maxasc += bv()->buffer()->params.getDefSkip().inPixels(*bv());
1143                         } else if (pit != ownerParagraphs().begin() &&
1144                                    boost::prior(pit)->layout()->isParagraph() &&
1145                                    boost::prior(pit)->getDepth() == 0)
1146                         {
1147                                 // is it right to use defskip here too? (AS)
1148                                 maxasc += bv()->buffer()->params.getDefSkip().inPixels(*bv());
1149                         }
1150                 }
1151
1152                 // the top margin
1153                 if (pit == ownerParagraphs().begin() && !isInInset())
1154                         maxasc += PAPER_MARGIN;
1155
1156                 // add the vertical spaces, that the user added
1157                 maxasc += getLengthMarkerHeight(*bv(), pit->params().spaceTop());
1158
1159                 // do not forget the DTP-lines!
1160                 // there height depends on the font of the nearest character
1161                 if (pit->params().lineTop())
1162
1163                         maxasc += 2 * font_metrics::ascent('x', getFont(pit, 0));
1164                 // and now the pagebreaks
1165                 if (pit->params().pagebreakTop())
1166                         maxasc += 3 * defaultRowHeight();
1167
1168                 if (pit->params().startOfAppendix())
1169                         maxasc += 3 * defaultRowHeight();
1170
1171                 // This is special code for the chapter, since the label of this
1172                 // layout is printed in an extra row
1173                 if (layout->labeltype == LABEL_COUNTER_CHAPTER
1174                         && bv()->buffer()->params.secnumdepth >= 0)
1175                 {
1176                         float spacing_val = 1.0;
1177                         if (!pit->params().spacing().isDefault()) {
1178                                 spacing_val = pit->params().spacing().getValue();
1179                         } else {
1180                                 spacing_val = bv()->buffer()->params.spacing.getValue();
1181                         }
1182
1183                         labeladdon = int(font_metrics::maxDescent(labelfont) *
1184                                          layout->spacing.getValue() *
1185                                          spacing_val)
1186                                 + int(font_metrics::maxAscent(labelfont) *
1187                                       layout->spacing.getValue() *
1188                                       spacing_val);
1189                 }
1190
1191                 // special code for the top label
1192                 if ((layout->labeltype == LABEL_TOP_ENVIRONMENT
1193                      || layout->labeltype == LABEL_BIBLIO
1194                      || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
1195                     && isFirstInSequence(pit, ownerParagraphs())
1196                     && !pit->getLabelstring().empty())
1197                 {
1198                         float spacing_val = 1.0;
1199                         if (!pit->params().spacing().isDefault()) {
1200                                 spacing_val = pit->params().spacing().getValue();
1201                         } else {
1202                                 spacing_val = bv()->buffer()->params.spacing.getValue();
1203                         }
1204
1205                         labeladdon = int(
1206                                 (font_metrics::maxAscent(labelfont) +
1207                                  font_metrics::maxDescent(labelfont)) *
1208                                   layout->spacing.getValue() *
1209                                   spacing_val
1210                                 + layout->topsep * defaultRowHeight()
1211                                 + layout->labelbottomsep * defaultRowHeight());
1212                 }
1213
1214                 // And now the layout spaces, for example before and after
1215                 // a section, or between the items of a itemize or enumerate
1216                 // environment.
1217
1218                 if (!pit->params().pagebreakTop()) {
1219                         ParagraphList::iterator prev =
1220                                 depthHook(pit, ownerParagraphs(),
1221                                           pit->getDepth());
1222                         if (prev != pit && prev->layout() == layout &&
1223                                 prev->getDepth() == pit->getDepth() &&
1224                                 prev->getLabelWidthString() == pit->getLabelWidthString())
1225                         {
1226                                 layoutasc = (layout->itemsep * defaultRowHeight());
1227                         } else if (rit != rows().begin()) {
1228                                 tmptop = layout->topsep;
1229
1230                                 if (boost::prior(pit)->getDepth() >= pit->getDepth()) {
1231                                         tmptop -= getPar(boost::prior(rit))->layout()->bottomsep;
1232                                 }
1233
1234                                 if (tmptop > 0)
1235                                         layoutasc = (tmptop * defaultRowHeight());
1236                         } else if (pit->params().lineTop()) {
1237                                 tmptop = layout->topsep;
1238
1239                                 if (tmptop > 0)
1240                                         layoutasc = (tmptop * defaultRowHeight());
1241                         }
1242
1243                         prev = outerHook(pit, ownerParagraphs());
1244                         if (prev != ownerParagraphs().end())  {
1245                                 maxasc += int(prev->layout()->parsep * defaultRowHeight());
1246                         } else if (pit != ownerParagraphs().begin()) {
1247                                 ParagraphList::iterator prior_pit = boost::prior(pit);
1248                                 if (prior_pit->getDepth() != 0 ||
1249                                     prior_pit->layout() == layout) {
1250                                         maxasc += int(layout->parsep * defaultRowHeight());
1251                                 }
1252                         }
1253                 }
1254         }
1255
1256         // is it a bottom line?
1257         RowList::iterator next_rit = boost::next(rit);
1258         if (next_rit == rows().end() || getPar(next_rit) != pit) {
1259                 // the bottom margin
1260                 ParagraphList::iterator nextpit = boost::next(pit);
1261                 if (nextpit == ownerParagraphs().end() &&
1262                     !isInInset())
1263                         maxdesc += PAPER_MARGIN;
1264
1265                 // add the vertical spaces, that the user added
1266                 maxdesc += getLengthMarkerHeight(*bv(), pit->params().spaceBottom());
1267
1268                 // do not forget the DTP-lines!
1269                 // there height depends on the font of the nearest character
1270                 if (pit->params().lineBottom())
1271                         maxdesc += 2 * font_metrics::ascent('x',
1272                                         getFont(pit, max(pos_type(0), pit->size() - 1)));
1273
1274                 // and now the pagebreaks
1275                 if (pit->params().pagebreakBottom())
1276                         maxdesc += 3 * defaultRowHeight();
1277
1278                 // and now the layout spaces, for example before and after
1279                 // a section, or between the items of a itemize or enumerate
1280                 // environment
1281                 if (!pit->params().pagebreakBottom()
1282                     && nextpit != ownerParagraphs().end()) {
1283                         ParagraphList::iterator comparepit = pit;
1284                         float usual = 0;
1285                         float unusual = 0;
1286
1287                         if (comparepit->getDepth() > nextpit->getDepth()) {
1288                                 usual = (comparepit->layout()->bottomsep * defaultRowHeight());
1289                                 comparepit = depthHook(comparepit, ownerParagraphs(), nextpit->getDepth());
1290                                 if (comparepit->layout()!= nextpit->layout()
1291                                         || nextpit->getLabelWidthString() !=
1292                                         comparepit->getLabelWidthString())
1293                                 {
1294                                         unusual = (comparepit->layout()->bottomsep * defaultRowHeight());
1295                                 }
1296                                 if (unusual > usual)
1297                                         layoutdesc = unusual;
1298                                 else
1299                                         layoutdesc = usual;
1300                         } else if (comparepit->getDepth() ==  nextpit->getDepth()) {
1301
1302                                 if (comparepit->layout() != nextpit->layout()
1303                                         || nextpit->getLabelWidthString() !=
1304                                         comparepit->getLabelWidthString())
1305                                         layoutdesc = int(comparepit->layout()->bottomsep * defaultRowHeight());
1306                         }
1307                 }
1308         }
1309
1310         // incalculate the layout spaces
1311         maxasc += int(layoutasc * 2 / (2 + pit->getDepth()));
1312         maxdesc += int(layoutdesc * 2 / (2 + pit->getDepth()));
1313
1314         // calculate the new height of the text
1315         height -= rit->height();
1316
1317         rit->height(maxasc + maxdesc + labeladdon);
1318         rit->baseline(maxasc + labeladdon);
1319
1320         height += rit->height();
1321
1322         rit->top_of_text(rit->baseline() - font_metrics::maxAscent(font));
1323
1324         double x = 0;
1325         if (layout->margintype != MARGIN_RIGHT_ADDRESS_BOX) {
1326                 // this IS needed
1327                 rit->width(maxwidth);
1328                 double dummy;
1329                 prepareToPrint(pit, rit, x, dummy, dummy, dummy, false);
1330         }
1331         rit->width(int(maxwidth + x));
1332         if (inset_owner) {
1333                 width = max(0, workWidth());
1334                 RowList::iterator it = rows().begin();
1335                 RowList::iterator end = rows().end();
1336                 for (; it != end; ++it)
1337                         if (it->width() > width)
1338                                 width = it->width();
1339         }
1340 }
1341
1342
1343 void LyXText::breakParagraph(ParagraphList & paragraphs, char keep_layout)
1344 {
1345         // allow only if at start or end, or all previous is new text
1346         if (cursor.pos() && cursor.pos() != cursor.par()->size()
1347                 && cursor.par()->isChangeEdited(0, cursor.pos()))
1348                 return;
1349
1350         LyXTextClass const & tclass =
1351                 bv()->buffer()->params.getLyXTextClass();
1352         LyXLayout_ptr const & layout = cursor.par()->layout();
1353
1354         // this is only allowed, if the current paragraph is not empty or caption
1355         // and if it has not the keepempty flag active
1356         if (cursor.par()->empty() && !cursor.par()->allowEmpty()
1357            && layout->labeltype != LABEL_SENSITIVE)
1358                 return;
1359
1360         recordUndo(bv(), Undo::ATOMIC, cursor.par());
1361
1362         // Always break behind a space
1363         //
1364         // It is better to erase the space (Dekel)
1365         if (cursor.pos() < cursor.par()->size()
1366              && cursor.par()->isLineSeparator(cursor.pos()))
1367            cursor.par()->erase(cursor.pos());
1368
1369         // break the paragraph
1370         if (keep_layout)
1371                 keep_layout = 2;
1372         else
1373                 keep_layout = layout->isEnvironment();
1374
1375         // we need to set this before we insert the paragraph. IMO the
1376         // breakParagraph call should return a bool if it inserts the
1377         // paragraph before or behind and we should react on that one
1378         // but we can fix this in 1.3.0 (Jug 20020509)
1379         bool const isempty = (cursor.par()->allowEmpty() && cursor.par()->empty());
1380         ::breakParagraph(bv()->buffer()->params, paragraphs, cursor.par(),
1381                          cursor.pos(), keep_layout);
1382
1383         // well this is the caption hack since one caption is really enough
1384         if (layout->labeltype == LABEL_SENSITIVE) {
1385                 if (!cursor.pos())
1386                         // set to standard-layout
1387                         cursor.par()->applyLayout(tclass.defaultLayout());
1388                 else
1389                         // set to standard-layout
1390                         boost::next(cursor.par())->applyLayout(tclass.defaultLayout());
1391         }
1392
1393         // if the cursor is at the beginning of a row without prior newline,
1394         // move one row up!
1395         // This touches only the screen-update. Otherwise we would may have
1396         // an empty row on the screen
1397         if (cursor.pos() && cursorRow()->pos() == cursor.pos()
1398             && !cursor.par()->isNewline(cursor.pos() - 1))
1399         {
1400                 cursorLeft(bv());
1401         }
1402
1403         removeParagraph(cursorRow());
1404
1405 #warning Trouble Point! (Lgb)
1406         // When ::breakParagraph is called from within an inset we must
1407         // ensure that the correct ParagraphList is used. Today that is not
1408         // the case and the Buffer::paragraphs is used. Not good. (Lgb)
1409         ParagraphList::iterator next_par = boost::next(cursor.par());
1410
1411         while (!next_par->empty() && next_par->isNewline(0))
1412                 next_par->erase(0);
1413
1414         insertParagraph(next_par, boost::next(cursorRow()));
1415         updateCounters();
1416
1417         // This check is necessary. Otherwise the new empty paragraph will
1418         // be deleted automatically. And it is more friendly for the user!
1419         if (cursor.pos() || isempty)
1420                 setCursor(next_par, 0);
1421         else
1422                 setCursor(cursor.par(), 0);
1423
1424         redoParagraph(cursor.par());
1425 }
1426
1427
1428 // convenience function
1429 void LyXText::redoParagraph()
1430 {
1431         clearSelection();
1432         redoParagraph(cursor.par());
1433         setCursorIntern(cursor.par(), cursor.pos());
1434 }
1435
1436
1437 // insert a character, moves all the following breaks in the
1438 // same Paragraph one to the right and make a rebreak
1439 void LyXText::insertChar(char c)
1440 {
1441         recordUndo(bv(), Undo::INSERT, cursor.par());
1442
1443         // When the free-spacing option is set for the current layout,
1444         // disable the double-space checking
1445
1446         bool const freeSpacing = cursor.par()->layout()->free_spacing ||
1447                 cursor.par()->isFreeSpacing();
1448
1449         if (lyxrc.auto_number) {
1450                 static string const number_operators = "+-/*";
1451                 static string const number_unary_operators = "+-";
1452                 static string const number_seperators = ".,:";
1453
1454                 if (current_font.number() == LyXFont::ON) {
1455                         if (!IsDigit(c) && !contains(number_operators, c) &&
1456                             !(contains(number_seperators, c) &&
1457                               cursor.pos() >= 1 &&
1458                               cursor.pos() < cursor.par()->size() &&
1459                               getFont(cursor.par(), cursor.pos()).number() == LyXFont::ON &&
1460                               getFont(cursor.par(), cursor.pos() - 1).number() == LyXFont::ON)
1461                            )
1462                                 number(bv()); // Set current_font.number to OFF
1463                 } else if (IsDigit(c) &&
1464                            real_current_font.isVisibleRightToLeft()) {
1465                         number(bv()); // Set current_font.number to ON
1466
1467                         if (cursor.pos() > 0) {
1468                                 char const c = cursor.par()->getChar(cursor.pos() - 1);
1469                                 if (contains(number_unary_operators, c) &&
1470                                     (cursor.pos() == 1 ||
1471                                      cursor.par()->isSeparator(cursor.pos() - 2) ||
1472                                      cursor.par()->isNewline(cursor.pos() - 2))
1473                                   ) {
1474                                         setCharFont(
1475                                                     cursor.par(),
1476                                                     cursor.pos() - 1,
1477                                                     current_font);
1478                                 } else if (contains(number_seperators, c) &&
1479                                            cursor.pos() >= 2 &&
1480                                            getFont(
1481                                                    cursor.par(),
1482                                                    cursor.pos() - 2).number() == LyXFont::ON) {
1483                                         setCharFont(
1484                                                     cursor.par(),
1485                                                     cursor.pos() - 1,
1486                                                     current_font);
1487                                 }
1488                         }
1489                 }
1490         }
1491
1492
1493         // First check, if there will be two blanks together or a blank at
1494         // the beginning of a paragraph.
1495         // I decided to handle blanks like normal characters, the main
1496         // difference are the special checks when calculating the row.fill
1497         // (blank does not count at the end of a row) and the check here
1498
1499         // The bug is triggered when we type in a description environment:
1500         // The current_font is not changed when we go from label to main text
1501         // and it should (along with realtmpfont) when we type the space.
1502         // CHECK There is a bug here! (Asger)
1503
1504         // store the current font.  This is because of the use of cursor
1505         // movements. The moving cursor would refresh the current font
1506         LyXFont realtmpfont = real_current_font;
1507         LyXFont rawtmpfont = current_font;
1508
1509         if (!freeSpacing && IsLineSeparatorChar(c)) {
1510                 if ((cursor.pos() > 0
1511                      && cursor.par()->isLineSeparator(cursor.pos() - 1))
1512                     || (cursor.pos() > 0
1513                         && cursor.par()->isNewline(cursor.pos() - 1))
1514                     || (cursor.pos() == 0)) {
1515                         static bool sent_space_message = false;
1516                         if (!sent_space_message) {
1517                                 if (cursor.pos() == 0)
1518                                         bv()->owner()->message(_("You cannot insert a space at the beginning of a paragraph. Please read the Tutorial."));
1519                                 else
1520                                         bv()->owner()->message(_("You cannot type two spaces this way. Please read the Tutorial."));
1521                                 sent_space_message = true;
1522                         }
1523                         charInserted();
1524                         return;
1525                 }
1526         }
1527
1528         // Here case LyXText::InsertInset already inserted the character
1529         if (c != Paragraph::META_INSET)
1530                 cursor.par()->insertChar(cursor.pos(), c);
1531
1532         setCharFont(cursor.par(), cursor.pos(), rawtmpfont);
1533
1534         current_font = rawtmpfont;
1535         real_current_font = realtmpfont;
1536         redoParagraph(cursor.par());
1537         setCursor(cursor.par(), cursor.pos() + 1, false, cursor.boundary());
1538
1539         charInserted();
1540 }
1541
1542
1543 void LyXText::charInserted()
1544 {
1545         // Here we could call FinishUndo for every 20 characters inserted.
1546         // This is from my experience how emacs does it. (Lgb)
1547         static unsigned int counter;
1548         if (counter < 20) {
1549                 ++counter;
1550         } else {
1551                 finishUndo();
1552                 counter = 0;
1553         }
1554 }
1555
1556
1557 void LyXText::prepareToPrint(ParagraphList::iterator pit,
1558            RowList::iterator rit, double & x,
1559                              double & fill_separator,
1560                              double & fill_hfill,
1561                              double & fill_label_hfill,
1562                              bool bidi) const
1563 {
1564         double w = rit->fill();
1565         fill_hfill = 0;
1566         fill_label_hfill = 0;
1567         fill_separator = 0;
1568         fill_label_hfill = 0;
1569
1570         bool const is_rtl =
1571                 pit->isRightToLeftPar(bv()->buffer()->params);
1572         if (is_rtl)
1573                 x = workWidth() > 0 ? rightMargin(pit, *bv()->buffer(), *rit) : 0;
1574         else
1575                 x = workWidth() > 0 ? leftMargin(pit, *rit) : 0;
1576
1577         // is there a manual margin with a manual label
1578         LyXLayout_ptr const & layout = pit->layout();
1579
1580         if (layout->margintype == MARGIN_MANUAL
1581             && layout->labeltype == LABEL_MANUAL) {
1582                 /// We might have real hfills in the label part
1583                 int nlh = numberOfLabelHfills(*this, pit, rit);
1584
1585                 // A manual label par (e.g. List) has an auto-hfill
1586                 // between the label text and the body of the
1587                 // paragraph too.
1588                 // But we don't want to do this auto hfill if the par
1589                 // is empty.
1590                 if (!pit->empty())
1591                         ++nlh;
1592
1593                 if (nlh && !pit->getLabelWidthString().empty()) {
1594                         fill_label_hfill = labelFill(pit, *rit) / double(nlh);
1595                 }
1596         }
1597
1598         // are there any hfills in the row?
1599         int const nh = numberOfHfills(*this, pit, rit);
1600
1601         if (nh) {
1602                 if (w > 0)
1603                         fill_hfill = w / nh;
1604         // we don't have to look at the alignment if it is ALIGN_LEFT and
1605         // if the row is already larger then the permitted width as then
1606         // we force the LEFT_ALIGN'edness!
1607         } else if (int(rit->width()) < workWidth()) {
1608                 // is it block, flushleft or flushright?
1609                 // set x how you need it
1610                 int align;
1611                 if (pit->params().align() == LYX_ALIGN_LAYOUT) {
1612                         align = layout->align;
1613                 } else {
1614                         align = pit->params().align();
1615                 }
1616
1617                 // center displayed insets
1618                 InsetOld * inset = 0;
1619                 if (rit->pos() < pit->size()
1620                     && pit->isInset(rit->pos())
1621                     && (inset = pit->getInset(rit->pos()))
1622                     && (inset->display())) // || (inset->scroll() < 0)))
1623                     align = (inset->lyxCode() == InsetOld::MATHMACRO_CODE)
1624                         ? LYX_ALIGN_BLOCK : LYX_ALIGN_CENTER;
1625                 // ERT insets should always be LEFT ALIGNED on screen
1626                 inset = pit->inInset();
1627                 if (inset && inset->owner() &&
1628                         inset->owner()->lyxCode() == InsetOld::ERT_CODE)
1629                 {
1630                         align = LYX_ALIGN_LEFT;
1631                 }
1632
1633                 switch (align) {
1634             case LYX_ALIGN_BLOCK:
1635             {
1636                         int const ns = numberOfSeparators(*this, pit, rit);
1637                         RowList::iterator next_row = boost::next(rit);
1638                         ParagraphList::iterator next_pit;
1639
1640                         if (ns && next_row != rowlist_.end() &&
1641                             (next_pit = getPar(next_row)) == pit &&
1642                             !(next_pit->isNewline(next_row->pos() - 1))
1643                             && !(next_pit->isInset(next_row->pos()) &&
1644                                  next_pit->getInset(next_row->pos()) &&
1645                                  next_pit->getInset(next_row->pos())->display())
1646                                 ) {
1647                                 fill_separator = w / ns;
1648                         } else if (is_rtl) {
1649                                 x += w;
1650                         }
1651                         break;
1652             }
1653             case LYX_ALIGN_RIGHT:
1654                         x += w;
1655                         break;
1656             case LYX_ALIGN_CENTER:
1657                         x += w / 2;
1658                         break;
1659                 }
1660         }
1661         if (!bidi)
1662                 return;
1663
1664         computeBidiTables(pit, bv()->buffer(), rit);
1665         if (is_rtl) {
1666                 pos_type body_pos = pit->beginningOfBody();
1667                 pos_type last = lastPos(*this, pit, rit);
1668
1669                 if (body_pos > 0 &&
1670                     (body_pos - 1 > last ||
1671                      !pit->isLineSeparator(body_pos - 1))) {
1672                         x += font_metrics::width(layout->labelsep, getLabelFont(pit));
1673                         if (body_pos - 1 <= last)
1674                                 x += fill_label_hfill;
1675                 }
1676         }
1677 }
1678
1679
1680 // important for the screen
1681
1682
1683 // the cursor set functions have a special mechanism. When they
1684 // realize, that you left an empty paragraph, they will delete it.
1685 // They also delete the corresponding row
1686
1687 void LyXText::cursorRightOneWord()
1688 {
1689         ::cursorRightOneWord(cursor, ownerParagraphs());
1690         setCursor(cursor.par(), cursor.pos());
1691 }
1692
1693
1694 // Skip initial whitespace at end of word and move cursor to *start*
1695 // of prior word, not to end of next prior word.
1696 void LyXText::cursorLeftOneWord()
1697 {
1698         LyXCursor tmpcursor = cursor;
1699         ::cursorLeftOneWord(tmpcursor, ownerParagraphs());
1700         setCursor(tmpcursor.par(), tmpcursor.pos());
1701 }
1702
1703
1704 void LyXText::selectWord(word_location loc)
1705 {
1706         LyXCursor from = cursor;
1707         LyXCursor to;
1708         ::getWord(from, to, loc, ownerParagraphs());
1709         if (cursor != from)
1710                 setCursor(from.par(), from.pos());
1711         if (to == from)
1712                 return;
1713         selection.cursor = cursor;
1714         setCursor(to.par(), to.pos());
1715         setSelection();
1716 }
1717
1718
1719 // Select the word currently under the cursor when no
1720 // selection is currently set
1721 bool LyXText::selectWordWhenUnderCursor(word_location loc)
1722 {
1723         if (!selection.set()) {
1724                 selectWord(loc);
1725                 return selection.set();
1726         }
1727         return false;
1728 }
1729
1730
1731 void LyXText::acceptChange()
1732 {
1733         if (!selection.set() && cursor.par()->size())
1734                 return;
1735
1736         if (selection.start.par() == selection.end.par()) {
1737                 LyXCursor & startc = selection.start;
1738                 LyXCursor & endc = selection.end;
1739                 recordUndo(bv(), Undo::INSERT, startc.par());
1740                 startc.par()->acceptChange(startc.pos(), endc.pos());
1741                 finishUndo();
1742                 clearSelection();
1743                 redoParagraph(startc.par());
1744                 setCursorIntern(startc.par(), 0);
1745         }
1746 #warning handle multi par selection
1747 }
1748
1749
1750 void LyXText::rejectChange()
1751 {
1752         if (!selection.set() && cursor.par()->size())
1753                 return;
1754
1755         if (selection.start.par() == selection.end.par()) {
1756                 LyXCursor & startc = selection.start;
1757                 LyXCursor & endc = selection.end;
1758                 recordUndo(bv(), Undo::INSERT, startc.par());
1759                 startc.par()->rejectChange(startc.pos(), endc.pos());
1760                 finishUndo();
1761                 clearSelection();
1762                 redoParagraph(startc.par());
1763                 setCursorIntern(startc.par(), 0);
1764         }
1765 #warning handle multi par selection
1766 }
1767
1768
1769 // This function is only used by the spellchecker for NextWord().
1770 // It doesn't handle LYX_ACCENTs and probably never will.
1771 WordLangTuple const
1772 LyXText::selectNextWordToSpellcheck(float & value)
1773 {
1774         if (the_locking_inset) {
1775                 WordLangTuple word = the_locking_inset->selectNextWordToSpellcheck(bv(), value);
1776                 if (!word.word().empty()) {
1777                         value += float(cursor.y());
1778                         value /= float(height);
1779                         return word;
1780                 }
1781                 // we have to go on checking so move cursor to the next char
1782                 if (cursor.pos() == cursor.par()->size()) {
1783                         if (boost::next(cursor.par()) == ownerParagraphs().end())
1784                                 return word;
1785                         cursor.par(boost::next(cursor.par()));
1786                         cursor.pos(0);
1787                 } else
1788                         cursor.pos(cursor.pos() + 1);
1789         }
1790         ParagraphList::iterator tmppit = cursor.par();
1791
1792         // If this is not the very first word, skip rest of
1793         // current word because we are probably in the middle
1794         // of a word if there is text here.
1795         if (cursor.pos() || cursor.par() != ownerParagraphs().begin()) {
1796                 while (cursor.pos() < cursor.par()->size()
1797                        && cursor.par()->isLetter(cursor.pos()))
1798                         cursor.pos(cursor.pos() + 1);
1799         }
1800
1801         // Now, skip until we have real text (will jump paragraphs)
1802         while (true) {
1803                 ParagraphList::iterator cpit = cursor.par();
1804                 pos_type const cpos(cursor.pos());
1805
1806                 if (cpos == cpit->size()) {
1807                         if (boost::next(cpit) != ownerParagraphs().end()) {
1808                                 cursor.par(boost::next(cpit));
1809                                 cursor.pos(0);
1810                                 continue;
1811                         }
1812                         break;
1813                 }
1814
1815                 bool const is_good_inset = cpit->isInset(cpos)
1816                         && cpit->getInset(cpos)->allowSpellcheck();
1817
1818                 if (!isDeletedText(*cpit, cpos)
1819                     && (is_good_inset || cpit->isLetter(cpos)))
1820                         break;
1821
1822                 cursor.pos(cpos + 1);
1823         }
1824
1825         // now check if we hit an inset so it has to be a inset containing text!
1826         if (cursor.pos() < cursor.par()->size() &&
1827             cursor.par()->isInset(cursor.pos())) {
1828                 // lock the inset!
1829                 FuncRequest cmd(bv(), LFUN_INSET_EDIT, "left");
1830                 cursor.par()->getInset(cursor.pos())->localDispatch(cmd);
1831                 // now call us again to do the above trick
1832                 // but obviously we have to start from down below ;)
1833                 return bv()->text->selectNextWordToSpellcheck(value);
1834         }
1835
1836         // Update the value if we changed paragraphs
1837         if (cursor.par() != tmppit) {
1838                 setCursor(cursor.par(), cursor.pos());
1839                 value = float(cursor.y())/float(height);
1840         }
1841
1842         // Start the selection from here
1843         selection.cursor = cursor;
1844
1845         string lang_code = getFont(cursor.par(), cursor.pos()).language()->code();
1846         // and find the end of the word (insets like optional hyphens
1847         // and ligature break are part of a word)
1848         while (cursor.pos() < cursor.par()->size()
1849                && cursor.par()->isLetter(cursor.pos())
1850                && !isDeletedText(*cursor.par(), cursor.pos()))
1851                 cursor.pos(cursor.pos() + 1);
1852
1853         // Finally, we copy the word to a string and return it
1854         string str;
1855         if (selection.cursor.pos() < cursor.pos()) {
1856                 pos_type i;
1857                 for (i = selection.cursor.pos(); i < cursor.pos(); ++i) {
1858                         if (!cursor.par()->isInset(i))
1859                                 str += cursor.par()->getChar(i);
1860                 }
1861         }
1862         return WordLangTuple(str, lang_code);
1863 }
1864
1865
1866 // This one is also only for the spellchecker
1867 void LyXText::selectSelectedWord()
1868 {
1869         if (the_locking_inset) {
1870                 the_locking_inset->selectSelectedWord(bv());
1871                 return;
1872         }
1873         // move cursor to the beginning
1874         setCursor(selection.cursor.par(), selection.cursor.pos());
1875
1876         // set the sel cursor
1877         selection.cursor = cursor;
1878
1879         // now find the end of the word
1880         while (cursor.pos() < cursor.par()->size()
1881                && cursor.par()->isLetter(cursor.pos()))
1882                 cursor.pos(cursor.pos() + 1);
1883
1884         setCursor(cursor.par(), cursor.pos());
1885
1886         // finally set the selection
1887         setSelection();
1888 }
1889
1890
1891 // Delete from cursor up to the end of the current or next word.
1892 void LyXText::deleteWordForward()
1893 {
1894         if (cursor.par()->empty())
1895                 cursorRight(bv());
1896         else {
1897                 LyXCursor tmpcursor = cursor;
1898                 selection.set(true); // to avoid deletion
1899                 cursorRightOneWord();
1900                 setCursor(tmpcursor, tmpcursor.par(), tmpcursor.pos());
1901                 selection.cursor = cursor;
1902                 cursor = tmpcursor;
1903                 setSelection();
1904
1905                 // Great, CutSelection() gets rid of multiple spaces.
1906                 cutSelection(true, false);
1907         }
1908 }
1909
1910
1911 // Delete from cursor to start of current or prior word.
1912 void LyXText::deleteWordBackward()
1913 {
1914         if (cursor.par()->empty())
1915                 cursorLeft(bv());
1916         else {
1917                 LyXCursor tmpcursor = cursor;
1918                 selection.set(true); // to avoid deletion
1919                 cursorLeftOneWord();
1920                 setCursor(tmpcursor, tmpcursor.par(), tmpcursor.pos());
1921                 selection.cursor = cursor;
1922                 cursor = tmpcursor;
1923                 setSelection();
1924                 cutSelection(true, false);
1925         }
1926 }
1927
1928
1929 // Kill to end of line.
1930 void LyXText::deleteLineForward()
1931 {
1932         if (cursor.par()->empty())
1933                 // Paragraph is empty, so we just go to the right
1934                 cursorRight(bv());
1935         else {
1936                 LyXCursor tmpcursor = cursor;
1937                 // We can't store the row over a regular setCursor
1938                 // so we set it to 0 and reset it afterwards.
1939                 selection.set(true); // to avoid deletion
1940                 cursorEnd();
1941                 setCursor(tmpcursor, tmpcursor.par(), tmpcursor.pos());
1942                 selection.cursor = cursor;
1943                 cursor = tmpcursor;
1944                 setSelection();
1945                 // What is this test for ??? (JMarc)
1946                 if (!selection.set()) {
1947                         deleteWordForward();
1948                 } else {
1949                         cutSelection(true, false);
1950                 }
1951         }
1952 }
1953
1954
1955 void LyXText::changeCase(LyXText::TextCase action)
1956 {
1957         LyXCursor from;
1958         LyXCursor to;
1959
1960         if (selection.set()) {
1961                 from = selection.start;
1962                 to = selection.end;
1963         } else {
1964                 from = cursor;
1965                 ::getWord(from, to, lyx::PARTIAL_WORD, ownerParagraphs());
1966                 setCursor(to.par(), to.pos() + 1);
1967         }
1968
1969         recordUndo(bv(), Undo::ATOMIC, from.par(), to.par());
1970
1971         pos_type pos = from.pos();
1972         ParagraphList::iterator pit = from.par();
1973
1974         while (pit != ownerParagraphs().end() &&
1975                (pos != to.pos() || pit != to.par())) {
1976                 if (pos == pit->size()) {
1977                         ++pit;
1978                         pos = 0;
1979                         continue;
1980                 }
1981                 unsigned char c = pit->getChar(pos);
1982                 if (!IsInsetChar(c)) {
1983                         switch (action) {
1984                         case text_lowercase:
1985                                 c = lowercase(c);
1986                                 break;
1987                         case text_capitalization:
1988                                 c = uppercase(c);
1989                                 action = text_lowercase;
1990                                 break;
1991                         case text_uppercase:
1992                                 c = uppercase(c);
1993                                 break;
1994                         }
1995                 }
1996 #warning changes
1997                 pit->setChar(pos, c);
1998                 ++pos;
1999         }
2000 }
2001
2002
2003 void LyXText::Delete()
2004 {
2005         // this is a very easy implementation
2006
2007         LyXCursor old_cursor = cursor;
2008         int const old_cur_par_id = old_cursor.par()->id();
2009         int const old_cur_par_prev_id =
2010                 (old_cursor.par() != ownerParagraphs().begin() ?
2011                  boost::prior(old_cursor.par())->id() : -1);
2012
2013         // just move to the right
2014         cursorRight(bv());
2015
2016         // CHECK Look at the comment here.
2017         // This check is not very good...
2018         // The cursorRightIntern calls DeleteEmptyParagrapgMechanism
2019         // and that can very well delete the par or par->previous in
2020         // old_cursor. Will a solution where we compare paragraph id's
2021         //work better?
2022         if ((cursor.par() != ownerParagraphs().begin() ? boost::prior(cursor.par())->id() : -1)
2023             == old_cur_par_prev_id
2024             && cursor.par()->id() != old_cur_par_id) {
2025                 // delete-empty-paragraph-mechanism has done it
2026                 return;
2027         }
2028
2029         // if you had success make a backspace
2030         if (old_cursor.par() != cursor.par() || old_cursor.pos() != cursor.pos()) {
2031                 LyXCursor tmpcursor = cursor;
2032                 // to make sure undo gets the right cursor position
2033                 cursor = old_cursor;
2034                 recordUndo(bv(), Undo::DELETE, cursor.par());
2035                 cursor = tmpcursor;
2036                 backspace();
2037         }
2038 }
2039
2040
2041 void LyXText::backspace()
2042 {
2043         // Get the font that is used to calculate the baselineskip
2044         pos_type lastpos = cursor.par()->size();
2045
2046         if (cursor.pos() == 0) {
2047                 // The cursor is at the beginning of a paragraph,
2048                 // so the the backspace will collapse two paragraphs into one.
2049
2050                 // but it's not allowed unless it's new
2051                 if (cursor.par()->isChangeEdited(0, cursor.par()->size()))
2052                         return;
2053
2054                 // we may paste some paragraphs
2055
2056                 // is it an empty paragraph?
2057
2058                 if (lastpos == 0
2059                      || (lastpos == 1 && cursor.par()->isSeparator(0))) {
2060                         // This is an empty paragraph and we delete it just
2061                         // by moving the cursor one step
2062                         // left and let the DeleteEmptyParagraphMechanism
2063                         // handle the actual deletion of the paragraph.
2064
2065                         if (cursor.par() != ownerParagraphs().begin()) {
2066                                 ParagraphList::iterator tmppit = boost::prior(cursor.par());
2067                                 if (cursor.par()->layout() == tmppit->layout()
2068                                     && cursor.par()->getAlign() == tmppit->getAlign()) {
2069                                         // Inherit bottom DTD from the paragraph below.
2070                                         // (the one we are deleting)
2071                                         tmppit->params().lineBottom(cursor.par()->params().lineBottom());
2072                                         tmppit->params().spaceBottom(cursor.par()->params().spaceBottom());
2073                                         tmppit->params().pagebreakBottom(cursor.par()->params().pagebreakBottom());
2074                                 }
2075
2076                                 cursorLeft(bv());
2077
2078                                 // the layout things can change the height of a row !
2079                                 setHeightOfRow(cursorRow());
2080                                 return;
2081                         }
2082                 }
2083
2084                 if (cursor.par() != ownerParagraphs().begin()) {
2085                         recordUndo(bv(), Undo::DELETE,
2086                                 boost::prior(cursor.par()),
2087                                 cursor.par());
2088                 }
2089
2090                 ParagraphList::iterator tmppit = cursor.par();
2091                 RowList::iterator tmprow = cursorRow();
2092
2093                 // We used to do cursorLeftIntern() here, but it is
2094                 // not a good idea since it triggers the auto-delete
2095                 // mechanism. So we do a cursorLeftIntern()-lite,
2096                 // without the dreaded mechanism. (JMarc)
2097                 if (cursor.par() != ownerParagraphs().begin()) {
2098                         // steps into the above paragraph.
2099                         setCursorIntern(boost::prior(cursor.par()),
2100                                         boost::prior(cursor.par())->size(),
2101                                         false);
2102                 }
2103
2104                 // Pasting is not allowed, if the paragraphs have different
2105                 // layout. I think it is a real bug of all other
2106                 // word processors to allow it. It confuses the user.
2107                 //Correction: Pasting is always allowed with standard-layout
2108                 LyXTextClass const & tclass =
2109                         bv()->buffer()->params.getLyXTextClass();
2110
2111                 if (cursor.par() != tmppit
2112                     && (cursor.par()->layout() == tmppit->layout()
2113                         || tmppit->layout() == tclass.defaultLayout())
2114                     && cursor.par()->getAlign() == tmppit->getAlign()) {
2115                         removeParagraph(tmprow);
2116                         removeRow(tmprow);
2117                         mergeParagraph(bv()->buffer()->params,
2118                                 bv()->buffer()->paragraphs, cursor.par());
2119
2120                         if (cursor.pos() && cursor.par()->isSeparator(cursor.pos() - 1))
2121                                 cursor.pos(cursor.pos() - 1);
2122
2123                         // the row may have changed, block, hfills etc.
2124                         updateCounters();
2125                         setCursor(cursor.par(), cursor.pos(), false);
2126                 }
2127         } else {
2128                 // this is the code for a normal backspace, not pasting
2129                 // any paragraphs
2130                 recordUndo(bv(), Undo::DELETE, cursor.par());
2131                 // We used to do cursorLeftIntern() here, but it is
2132                 // not a good idea since it triggers the auto-delete
2133                 // mechanism. So we do a cursorLeftIntern()-lite,
2134                 // without the dreaded mechanism. (JMarc)
2135                 setCursorIntern(cursor.par(), cursor.pos() - 1,
2136                                 false, cursor.boundary());
2137                 cursor.par()->erase(cursor.pos());
2138         }
2139
2140         lastpos = cursor.par()->size();
2141         if (cursor.pos() == lastpos)
2142                 setCurrentFont();
2143
2144         redoParagraph();
2145         setCursor(cursor.par(), cursor.pos(), false, !cursor.boundary());
2146 }
2147
2148
2149 RowList::iterator LyXText::cursorRow() const
2150 {
2151         return getRow(cursor.par(), cursor.pos());
2152 }
2153
2154
2155 RowList::iterator LyXText::getRow(LyXCursor const & cur) const
2156 {
2157         return getRow(cur.par(), cur.pos());
2158 }
2159
2160
2161 RowList::iterator
2162 LyXText::getRow(ParagraphList::iterator pit, pos_type pos) const
2163 {
2164         if (rows().empty())
2165                 return rowlist_.end();
2166
2167         // find the first row of the specified paragraph
2168         RowList::iterator rit = rowlist_.begin();
2169         RowList::iterator end = rowlist_.end();
2170         while (boost::next(rit) != end && getPar(rit) != pit) {
2171                 ++rit;
2172         }
2173
2174         // now find the wanted row
2175         while (rit->pos() < pos
2176                && boost::next(rit) != end
2177                && getPar(boost::next(rit)) == pit
2178                && boost::next(rit)->pos() <= pos) {
2179                 ++rit;
2180         }
2181
2182         return rit;
2183 }
2184
2185
2186 // returns pointer to a specified row
2187 RowList::iterator
2188 LyXText::getRow(ParagraphList::iterator pit, pos_type pos, int & y) const
2189 {
2190         y = 0;
2191
2192         if (rows().empty())
2193                 return rowlist_.end();
2194
2195         // find the first row of the specified paragraph
2196         RowList::iterator rit = rowlist_.begin();
2197         RowList::iterator end = rowlist_.end();
2198         while (boost::next(rit) != end && getPar(rit) != pit) {
2199                 y += rit->height();
2200                 ++rit;
2201         }
2202
2203         // now find the wanted row
2204         while (rit->pos() < pos
2205                && boost::next(rit) != end
2206                && getPar(boost::next(rit)) == pit
2207                && boost::next(rit)->pos() <= pos) {
2208                 y += rit->height();
2209                 ++rit;
2210         }
2211
2212         return rit;
2213 }
2214
2215
2216 // returns pointer to some fancy row 'below' specified row
2217 RowList::iterator LyXText::cursorIRow() const
2218 {
2219         int y = 0;
2220         return getRow(cursor.par(), cursor.pos(), y);
2221 }
2222
2223
2224 RowList::iterator LyXText::getRowNearY(int & y) const
2225 {
2226         RowList::iterator rit = anchor_row_;
2227         RowList::iterator const beg = rows().begin();
2228         RowList::iterator const end = rows().end();
2229
2230         if (rows().empty()) {
2231                 y = 0;
2232                 return end;
2233         }
2234         if (rit == end)
2235                 rit = beg;
2236
2237         int tmpy = rit->y();
2238
2239         if (tmpy <= y) {
2240                 while (rit != end && tmpy <= y) {
2241                         tmpy += rit->height();
2242                         ++rit;
2243                 }
2244                 if (rit != beg) {
2245                         --rit;
2246                         tmpy -= rit->height();
2247                 }
2248         } else {
2249                 while (rit != beg && tmpy > y) {
2250                         --rit;
2251                         tmpy -= rit->height();
2252                 }
2253         }
2254         if (tmpy < 0 || rit == end) {
2255                 tmpy = 0;
2256                 rit = beg;
2257         }
2258
2259         // return the rel y
2260         y = tmpy;
2261
2262         return rit;
2263 }
2264
2265
2266 int LyXText::getDepth() const
2267 {
2268         return cursor.par()->getDepth();
2269 }
2270
2271
2272 #warning Expensive. Remove before 1.4!
2273 // computes a ParagraphList::iterator from RowList::iterator by
2274 // counting zeros in the sequence of pos values.
2275
2276 ParagraphList::iterator LyXText::getPar(RowList::iterator row) const
2277 {
2278         if (row == rows().end()) {
2279                 lyxerr << "getPar() pit at end " << endl;
2280                 Assert(false);
2281         }
2282
2283         if (row == rows().begin()) {
2284                 return ownerParagraphs().begin();
2285         }
2286
2287         ParagraphList::iterator pit = ownerParagraphs().begin();
2288         RowList::iterator rit = rows().begin();
2289         RowList::iterator rend = rows().end();
2290         for (++rit ; rit != rend; ++rit) {
2291                 if (rit->pos() == 0) {
2292                         ++pit;
2293                         if (pit == ownerParagraphs().end()) {
2294                                 lyxerr << "unexpected in LyXText::getPar()" << endl;
2295                                 Assert(false);
2296                         }
2297                 }
2298                 if (rit == row) {
2299                         return pit;
2300                 }
2301         }
2302
2303         lyxerr << "LyXText::getPar: row not found " << endl;
2304         Assert(false);
2305         return ownerParagraphs().end(); // shut up compiler
2306 }
2307
2308
2309 RowList::iterator LyXText::beginRow(ParagraphList::iterator pit) const
2310 {
2311         int n = std::distance(ownerParagraphs().begin(), pit);
2312
2313         RowList::iterator rit = rows().begin();
2314         RowList::iterator end = rows().end();
2315         for ( ; rit != end; ++rit)
2316                 if (rit->pos() == 0 && n-- == 0)
2317                         return rit;
2318
2319         return rit;
2320 }
2321
2322
2323 RowList::iterator LyXText::endRow(ParagraphList::iterator pit) const
2324 {
2325         return beginRow(boost::next(pit));
2326 }
2327
2328
2329 RowList::iterator LyXText::endRow(RowList::iterator rit) const
2330 {
2331         for (++rit; rit != rows().end() && rit->pos(); ++rit)
2332                 ;
2333         return rit;
2334 }