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