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