]> git.lyx.org Git - lyx.git/blob - src/text.C
Fix crash when row did rebreak while drawing (fix #351).
[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 "lyxrow.h"
15 #include "lyxtextclasslist.h"
16 #include "paragraph.h"
17 #include "gettext.h"
18 #include "bufferparams.h"
19 #include "buffer.h"
20 #include "debug.h"
21 #include "lyxrc.h"
22 #include "LyXView.h"
23 #include "Painter.h"
24 #include "tracer.h"
25 #include "font.h"
26 #include "encoding.h"
27 #include "lyxscreen.h"
28 #include "bufferview_funcs.h"
29 #include "BufferView.h"
30 #include "language.h"
31 #include "ParagraphParameters.h"
32 #include "undo_funcs.h"
33 #include "font.h"
34
35 #include "insets/insetbib.h"
36 #include "insets/insettext.h"
37
38 #include "support/textutils.h"
39 #include "support/LAssert.h"
40 #include "support/lstrings.h"
41
42 #include <algorithm>
43
44 using std::max;
45 using std::min;
46 using std::endl;
47 using std::pair;
48 using lyx::pos_type;
49
50 namespace {
51
52 int const LYX_PAPER_MARGIN = 20;
53
54 } // namespace anon
55
56 extern int bibitemMaxWidth(BufferView *, LyXFont const &);
57
58
59 int LyXText::workWidth(BufferView * bview) const
60 {
61         if (inset_owner) {
62                 return inset_owner->textWidth(bview);
63         }
64         return bview->workWidth();
65 }
66
67
68 int LyXText::workWidth(BufferView * bview, Inset * inset) const
69 {
70         Paragraph * par = 0;
71         pos_type pos = -1;
72
73         par = inset->parOwner();
74         if (par)
75                 pos = par->getPositionOfInset(inset);
76
77         if (!par || pos == -1) {
78                 lyxerr << "LyXText::workWidth: something is wrong,"
79                         " fall back to the brute force method" << endl;
80                 Buffer::inset_iterator it = bview->buffer()->inset_iterator_begin();
81                 Buffer::inset_iterator end = bview->buffer()->inset_iterator_end();
82                 for (; it != end; ++it) {
83                         if (*it == inset) {
84                                 par = it.getPar();
85                                 pos = it.getPos();
86                                 break;
87                         }
88                 }
89         }
90
91         if (!par) {
92                 return workWidth(bview);
93         }
94
95         LyXLayout const & layout =
96                 textclasslist[bview->buffer()->params.textclass][par->layout()];
97
98         if (layout.margintype != MARGIN_RIGHT_ADDRESS_BOX) {
99                 // Optimization here: in most cases, the real row is
100                 // not needed, but only the par/pos values. So we just
101                 // construct a dummy row for leftMargin. (JMarc)
102                 Row dummyrow;
103                 dummyrow.par(par);
104                 dummyrow.pos(pos);
105                 return workWidth(bview) - leftMargin(bview, &dummyrow);
106         } else {
107                 int dummy_y;
108                 Row * row = getRow(par, pos, dummy_y);
109                 Row * frow = row;
110                 while (frow->previous() && frow->par() == frow->previous()->par())
111                         frow = frow->previous();
112                 unsigned int maxw = 0;
113                 while (frow->next() && frow->par() == frow->next()->par()) {
114                         if ((frow != row) && (maxw < frow->width()))
115                                 maxw = frow->width();
116                         frow = frow->next();
117                 }
118                 if (maxw)
119                         return maxw;
120         }
121         return workWidth(bview);
122 }
123
124
125 int LyXText::getRealCursorX(BufferView * bview) const
126 {
127         int x = cursor.x();
128         if (the_locking_inset && (the_locking_inset->getLyXText(bview)!=this))
129                 x = the_locking_inset->getLyXText(bview)->getRealCursorX(bview);
130         return x;
131 }
132
133
134 unsigned char LyXText::transformChar(unsigned char c, Paragraph * par,
135                         pos_type pos) const
136 {
137         if (!Encodings::is_arabic(c))
138                 if (lyxrc.font_norm_type == LyXRC::ISO_8859_6_8 && IsDigit(c))
139                         return c + (0xb0 - '0');
140                 else
141                         return c;
142
143         unsigned char const prev_char = pos > 0 ? par->getChar(pos-1) : ' ';
144         unsigned char next_char = ' ';
145
146         for (pos_type i = pos+1; i < par->size(); ++i)
147                 if (!Encodings::IsComposeChar_arabic(par->getChar(i))) {
148                         next_char = par->getChar(i);
149                         break;
150                 }
151
152         if (Encodings::is_arabic(next_char)) {
153                 if (Encodings::is_arabic(prev_char))
154                         return Encodings::TransformChar(c, Encodings::FORM_MEDIAL);
155                 else
156                         return Encodings::TransformChar(c, Encodings::FORM_INITIAL);
157         } else {
158                 if (Encodings::is_arabic(prev_char))
159                         return Encodings::TransformChar(c, Encodings::FORM_FINAL);
160                 else
161                         return Encodings::TransformChar(c, Encodings::FORM_ISOLATED);
162         }
163 }
164
165 // This is the comments that some of the warnings below refers to.
166 // There are some issues in this file and I don't think they are
167 // really related to the FIX_DOUBLE_SPACE patch. I'd rather think that
168 // this is a problem that has been here almost from day one and that a
169 // larger userbase with differenct access patters triggers the bad
170 // behaviour. (segfaults.) What I think happen is: In several places
171 // we store the paragraph in the current cursor and then moves the
172 // cursor. This movement of the cursor will delete paragraph at the
173 // old position if it is now empty. This will make the temporary
174 // pointer to the old cursor paragraph invalid and dangerous to use.
175 // And is some cases this will trigger a segfault. I have marked some
176 // of the cases where this happens with a warning, but I am sure there
177 // are others in this file and in text2.C. There is also a note in
178 // Delete() that you should read. In Delete I store the paragraph->id
179 // instead of a pointer to the paragraph. I am pretty sure this faulty
180 // use of temporary pointers to paragraphs that might have gotten
181 // invalidated (through a cursor movement) before they are used, are
182 // the cause of the strange crashes we get reported often.
183 //
184 // It is very tiresom to change this code, especially when it is as
185 // hard to read as it is. Help to fix all the cases where this is done
186 // would be greately appreciated.
187 //
188 // Lgb
189
190 int LyXText::singleWidth(BufferView * bview, Paragraph * par,
191                          pos_type pos) const
192 {
193         char const c = par->getChar(pos);
194         return singleWidth(bview, par, pos, c);
195 }
196
197
198 int LyXText::singleWidth(BufferView * bview, Paragraph * par,
199                          pos_type pos, char c) const
200 {
201         LyXFont const font = getFont(bview->buffer(), par, pos);
202
203         // The most common case is handled first (Asger)
204         if (IsPrintable(c)) {
205                 if (font.language()->RightToLeft()) {
206                         if (font.language()->lang() == "arabic" &&
207                             (lyxrc.font_norm_type == LyXRC::ISO_8859_6_8 ||
208                              lyxrc.font_norm_type == LyXRC::ISO_10646_1))
209                                 if (Encodings::IsComposeChar_arabic(c))
210                                         return 0;
211                                 else
212                                         c = transformChar(c, par, pos);
213                         else if (font.language()->lang() == "hebrew" &&
214                                  Encodings::IsComposeChar_hebrew(c))
215                                 return 0;
216                 }
217                 return lyxfont::width(c, font);
218
219         } else if (IsHfillChar(c)) {
220                 return 3;       /* Because of the representation
221                                  * as vertical lines */
222         } else if (c == Paragraph::META_INSET) {
223                 Inset * tmpinset = par->getInset(pos);
224                 if (tmpinset) {
225 #if 1
226                         // this IS needed otherwise on initialitation we don't get the fill
227                         // of the row right (ONLY on initialization if we read a file!)
228                         // should be changed! (Jug 20011204)
229                         tmpinset->update(bview, font);
230 #endif
231                         return tmpinset->width(bview, font);
232                 } else
233                         return 0;
234
235         } else if (IsSeparatorChar(c))
236                 c = ' ';
237         else if (IsNewlineChar(c))
238                 c = 'n';
239         return lyxfont::width(c, font);
240 }
241
242
243 // Returns the paragraph position of the last character in the specified row
244 pos_type LyXText::rowLast(Row const * row) const
245 {
246         if (!row->next() || row->next()->par() != row->par()) {
247                 return row->par()->size() - 1;
248         } else {
249                 return row->next()->pos() - 1;
250         }
251 }
252
253
254 pos_type LyXText::rowLastPrintable(Row const * row) const
255 {
256         pos_type const last = rowLast(row);
257         bool ignore_the_space_on_the_last_position = true;
258         Inset * ins;
259         // we have to consider a space on the last position in this case!
260         if (row->next() && row->par() == row->next()->par() &&
261             row->next()->par()->getChar(last+1) == Paragraph::META_INSET &&
262             (ins=row->next()->par()->getInset(last+1)) &&
263             (ins->needFullRow() || ins->display()))
264         {
265                 ignore_the_space_on_the_last_position = false;
266         }
267         if (last >= row->pos()
268             && row->next()
269             && row->next()->par() == row->par()
270             && row->par()->isSeparator(last)
271                 && ignore_the_space_on_the_last_position)
272                 return last - 1;
273         else
274                 return last;
275 }
276
277
278 void LyXText::computeBidiTables(Buffer const * buf, Row * row) const
279 {
280         bidi_same_direction = true;
281         if (!lyxrc.rtl_support) {
282                 bidi_start = -1;
283                 return;
284         }
285
286         bidi_start = row->pos();
287         bidi_end = rowLastPrintable(row);
288
289         if (bidi_start > bidi_end) {
290                 bidi_start = -1;
291                 return;
292         }
293
294         if (bidi_end + 2 - bidi_start >
295             static_cast<pos_type>(log2vis_list.size())) {
296                 pos_type new_size =
297                         (bidi_end + 2 - bidi_start < 500) ?
298                         500 : 2 * (bidi_end + 2 - bidi_start);
299                 log2vis_list.resize(new_size);
300                 vis2log_list.resize(new_size);
301                 bidi_levels.resize(new_size);
302         }
303
304         vis2log_list[bidi_end + 1 - bidi_start] = -1;
305         log2vis_list[bidi_end + 1 - bidi_start] = -1;
306
307         pos_type stack[2];
308         bool const rtl_par =
309                 row->par()->getParLanguage(buf->params)->RightToLeft();
310         int level = 0;
311         bool rtl = false;
312         bool rtl0 = false;
313         pos_type const main_body = beginningOfMainBody(buf, row->par());
314
315         for (pos_type lpos = bidi_start;
316              lpos <= bidi_end; ++lpos) {
317                 bool is_space = row->par()->isLineSeparator(lpos);
318                 pos_type const pos =
319                         (is_space && lpos + 1 <= bidi_end &&
320                          !row->par()->isLineSeparator(lpos + 1) &&
321                          !row->par()->isNewline(lpos + 1))
322                         ? lpos + 1 : lpos;
323                 LyXFont font = row->par()->getFontSettings(buf->params, pos);
324                 if (pos != lpos && 0 < lpos && rtl0 && font.isRightToLeft() &&
325                     font.number() == LyXFont::ON &&
326                     row->par()->getFontSettings(buf->params, lpos - 1).number()
327                     == LyXFont::ON) {
328                         font = row->par()->getFontSettings(buf->params, lpos);
329                         is_space = false;
330                 }
331
332
333                 bool new_rtl = font.isVisibleRightToLeft();
334                 bool new_rtl0 = font.isRightToLeft();
335                 int new_level;
336
337                 if (lpos == main_body - 1
338                     && row->pos() < main_body - 1
339                     && is_space) {
340                         new_level = (rtl_par) ? 1 : 0;
341                         new_rtl = new_rtl0 = rtl_par;
342                 } else if (new_rtl0)
343                         new_level = (new_rtl) ? 1 : 2;
344                 else
345                         new_level = (rtl_par) ? 2 : 0;
346
347                 if (is_space && new_level >= level) {
348                         new_level = level;
349                         new_rtl = rtl;
350                         new_rtl0 = rtl0;
351                 }
352
353                 int new_level2 = new_level;
354
355                 if (level == new_level && rtl0 != new_rtl0) {
356                         --new_level2;
357                         log2vis_list[lpos - bidi_start] = (rtl) ? 1 : -1;
358                 } else if (level < new_level) {
359                         log2vis_list[lpos - bidi_start] =  (rtl) ? -1 : 1;
360                         if (new_level > rtl_par)
361                                 bidi_same_direction = false;
362                 } else
363                         log2vis_list[lpos - bidi_start] = (new_rtl) ? -1 : 1;
364                 rtl = new_rtl;
365                 rtl0 = new_rtl0;
366                 bidi_levels[lpos - bidi_start] = new_level;
367
368                 while (level > new_level2) {
369                         pos_type old_lpos = stack[--level];
370                         int delta = lpos - old_lpos - 1;
371                         if (level % 2)
372                                 delta = -delta;
373                         log2vis_list[lpos - bidi_start] += delta;
374                         log2vis_list[old_lpos - bidi_start] += delta;
375                 }
376                 while (level < new_level)
377                         stack[level++] = lpos;
378         }
379
380         while (level > 0) {
381                 pos_type const old_lpos = stack[--level];
382                 int delta = bidi_end - old_lpos;
383                 if (level % 2)
384                         delta = -delta;
385                 log2vis_list[old_lpos - bidi_start] += delta;
386         }
387
388         pos_type vpos = bidi_start - 1;
389         for (pos_type lpos = bidi_start;
390              lpos <= bidi_end; ++lpos) {
391                 vpos += log2vis_list[lpos - bidi_start];
392                 vis2log_list[vpos - bidi_start] = lpos;
393                 log2vis_list[lpos - bidi_start] = vpos;
394         }
395 }
396
397
398 // This method requires a previous call to ComputeBidiTables()
399 bool LyXText::isBoundary(Buffer const * buf, Paragraph * par,
400                          pos_type pos) const
401 {
402         if (!lyxrc.rtl_support || pos == 0)
403                 return false;
404
405         if (!bidi_InRange(pos - 1)) {
406                 /// This can happen if pos is the first char of a row.
407                 /// Returning false in this case is incorrect!
408                 return false;
409         }
410
411         bool const rtl = bidi_level(pos - 1) % 2;
412         bool const rtl2 = bidi_InRange(pos)
413                 ? bidi_level(pos) % 2
414                 : par->isRightToLeftPar(buf->params);
415         return rtl != rtl2;
416 }
417
418
419 bool LyXText::isBoundary(Buffer const * buf, Paragraph * par,
420                          pos_type pos, LyXFont const & font) const
421 {
422         if (!lyxrc.rtl_support)
423                 return false;    // This is just for speedup
424
425         bool const rtl = font.isVisibleRightToLeft();
426         bool const rtl2 = bidi_InRange(pos)
427                 ? bidi_level(pos) % 2
428                 : par->isRightToLeftPar(buf->params);
429         return rtl != rtl2;
430 }
431
432 void LyXText::drawNewline(DrawRowParams & p, pos_type const pos)
433 {
434         // Draw end-of-line marker
435         LyXFont const font = getFont(p.bv->buffer(), p.row->par(), pos);
436         int const wid = lyxfont::width('n', font);
437         int const asc = lyxfont::maxAscent(font);
438         int const y = p.yo + p.row->baseline();
439         int xp[3];
440         int yp[3];
441
442         yp[0] = int(y - 0.875 * asc * 0.75);
443         yp[1] = int(y - 0.500 * asc * 0.75);
444         yp[2] = int(y - 0.125 * asc * 0.75);
445
446         if (bidi_level(pos) % 2 == 0) {
447                 xp[0] = int(p.x + wid * 0.375);
448                 xp[1] = int(p.x);
449                 xp[2] = int(p.x + wid * 0.375);
450         } else {
451                 xp[0] = int(p.x + wid * 0.625);
452                 xp[1] = int(p.x + wid);
453                 xp[2] = int(p.x + wid * 0.625);
454         }
455
456         p.pain->lines(xp, yp, 3, LColor::eolmarker);
457
458         yp[0] = int(y - 0.500 * asc * 0.75);
459         yp[1] = int(y - 0.500 * asc * 0.75);
460         yp[2] = int(y - asc * 0.75);
461
462         if (bidi_level(pos) % 2 == 0) {
463                 xp[0] = int(p.x);
464                 xp[1] = int(p.x + wid);
465                 xp[2] = int(p.x + wid);
466         } else {
467                 xp[0] = int(p.x + wid);
468                 xp[1] = int(p.x);
469                 xp[2] = int(p.x);
470         }
471
472         p.pain->lines(xp, yp, 3, LColor::eolmarker);
473
474         p.x += wid;
475 }
476
477
478 bool LyXText::drawInset(DrawRowParams & p, pos_type const pos)
479 {
480         Inset * inset = p.row->par()->getInset(pos);
481
482         // FIXME: shouldn't happen
483         if (!inset) {
484                 return true;
485         }
486
487         LyXFont const & font = getFont(p.bv->buffer(), p.row->par(), pos);
488         // we need this here as the row pointer may be illegal
489         // at a later time (Jug20020502)
490         Row * prev = p.row->previous();
491
492         inset->update(p.bv, font, false);
493         inset->draw(p.bv, font, p.yo + p.row->baseline(), p.x, p.cleared);
494
495         if (!need_break_row && !inset_owner
496             && p.bv->text->status() == CHANGED_IN_DRAW) {
497                 if (prev && prev->par() == p.row->par()) {
498                         breakAgainOneRow(p.bv, prev);
499                         if (prev->next() != p.row) {
500                                 // breakAgainOneRow() has removed p.row
501                                 p.row = 0;  // see what this breaks
502                                 need_break_row = prev;
503                         } else {
504                                 need_break_row = p.row;
505                         }
506                 } else if (!prev) {
507                         need_break_row = firstrow;
508                 } else {
509                         need_break_row = prev->next();
510                 }
511                 setCursor(p.bv, cursor.par(), cursor.pos());
512                 return false;
513         }
514         return true;
515 }
516
517
518 void LyXText::drawForeignMark(DrawRowParams & p, float const orig_x, LyXFont const & orig_font)
519 {
520         if (!lyxrc.mark_foreign_language)
521                 return;
522         if (orig_font.language() == latex_language)
523                 return;
524         if (orig_font.language() == p.bv->buffer()->params.language)
525                 return;
526
527         int const y = p.yo + p.row->height() - 1;
528         p.pain->line(int(orig_x), y, int(p.x), y, LColor::language);
529 }
530
531
532 void LyXText::drawHebrewComposeChar(DrawRowParams & p, pos_type & vpos)
533 {
534         pos_type pos = vis2log(vpos);
535
536         string str;
537
538         // first char
539         char c = p.row->par()->getChar(pos);
540         str += c;
541         ++vpos;
542
543         LyXFont const & font = getFont(p.bv->buffer(), p.row->par(), pos);
544         int const width = lyxfont::width(c, font);
545         int dx = 0;
546
547         for (pos_type i = pos-1; i >= 0; --i) {
548                 c = p.row->par()->getChar(i);
549                 if (!Encodings::IsComposeChar_hebrew(c)) {
550                         if (IsPrintableNonspace(c)) {
551                                 int const width2 =
552                                         singleWidth(p.bv, p.row->par(), i, c);
553                                 // dalet / resh
554                                 dx = (c == 'ø' || c == 'ã')
555                                         ? width2 - width
556                                         : (width2 - width) / 2;
557                         }
558                         break;
559                 }
560         }
561
562         // Draw nikud
563         p.pain->text(int(p.x) + dx, p.yo + p.row->baseline(), str, font);
564 }
565
566
567 void LyXText::drawArabicComposeChar(DrawRowParams & p, pos_type & vpos)
568 {
569         pos_type pos = vis2log(vpos);
570         string str;
571
572         // first char
573         char c = p.row->par()->getChar(pos);
574         c = transformChar(c, p.row->par(), pos);
575         str +=c;
576         ++vpos;
577
578         LyXFont const & font = getFont(p.bv->buffer(), p.row->par(), pos);
579         int const width = lyxfont::width(c, font);
580         int dx = 0;
581
582         for (pos_type i = pos-1; i >= 0; --i) {
583                 c = p.row->par()->getChar(i);
584                 if (!Encodings::IsComposeChar_arabic(c)) {
585                         if (IsPrintableNonspace(c)) {
586                                 int const width2 =
587                                         singleWidth(p.bv, p.row->par(), i, c);
588                                 dx = (width2 - width) / 2;
589                         }
590                         break;
591                 }
592         }
593         // Draw nikud
594         p.pain->text(int(p.x) + dx, p.yo + p.row->baseline(), str, font);
595 }
596
597
598 void LyXText::drawChars(DrawRowParams & p, pos_type & vpos,
599                         bool hebrew, bool arabic)
600 {
601         pos_type pos = vis2log(vpos);
602         pos_type const last = rowLastPrintable(p.row);
603         LyXFont const & orig_font = getFont(p.bv->buffer(), p.row->par(), pos);
604
605         // first character
606         string str;
607         str += p.row->par()->getChar(pos);
608         if (arabic) {
609                 unsigned char c = str[0];
610                 str[0] = transformChar(c, p.row->par(), pos);
611         }
612         ++vpos;
613
614         // collect as much similar chars as we can
615         while (vpos <= last && (pos = vis2log(vpos)) >= 0) {
616                 char c = p.row->par()->getChar(pos);
617
618                 if (!IsPrintableNonspace(c))
619                         break;
620
621                 if (arabic && Encodings::IsComposeChar_arabic(c))
622                         break;
623                 if (hebrew && Encodings::IsComposeChar_hebrew(c))
624                         break;
625
626                 if (orig_font != getFont(p.bv->buffer(), p.row->par(), pos))
627                         break;
628
629                 str += c;
630                 ++vpos;
631         }
632
633         // Draw text and set the new x position
634         p.pain->text(int(p.x), p.yo + p.row->baseline(), str, orig_font);
635         p.x += lyxfont::width(str, orig_font);
636 }
637
638
639 bool LyXText::draw(DrawRowParams & p, pos_type & vpos)
640 {
641         pos_type const pos = vis2log(vpos);
642         Paragraph * par = p.row->par();
643
644         LyXFont const & orig_font = getFont(p.bv->buffer(), par, pos);
645
646         float const orig_x = p.x;
647
648         char const c = par->getChar(pos);
649
650         if (IsNewlineChar(c)) {
651                 ++vpos;
652                 drawNewline(p, pos);
653                 return true;
654         } else if (IsInsetChar(c)) {
655                 if (!drawInset(p, pos))
656                         return false;
657                 ++vpos;
658                 drawForeignMark(p, orig_x, orig_font);
659                 return true;
660         }
661
662         // usual characters, no insets
663
664         // special case languages
665         bool const hebrew = (orig_font.language()->lang() == "hebrew");
666         bool const arabic =
667                 orig_font.language()->lang() == "arabic" &&
668                 (lyxrc.font_norm_type == LyXRC::ISO_8859_6_8 ||
669                 lyxrc.font_norm_type == LyXRC::ISO_10646_1);
670
671         // draw as many chars as we can
672         if ((!hebrew && !arabic)
673                 || (hebrew && !Encodings::IsComposeChar_hebrew(c))
674                 || (arabic && !Encodings::IsComposeChar_arabic(c))) {
675                 drawChars(p, vpos, true, false);
676         } else if (hebrew) {
677                 drawHebrewComposeChar(p, vpos);
678         } else if (arabic) {
679                 drawArabicComposeChar(p, vpos);
680         }
681
682         drawForeignMark(p, orig_x, orig_font);
683
684 #ifdef INHERIT_LANGUAGE
685 #ifdef WITH_WARNINGS
686         if ((font.language() == inherit_language) ||
687                 (font.language() == ignore_language))
688                 lyxerr << "No this shouldn't happen!\n";
689 #endif
690 #endif
691         return true;
692 }
693
694
695 // Returns the left beginning of the text.
696 // This information cannot be taken from the layouts-objekt, because in
697 // LaTeX the beginning of the text fits in some cases (for example sections)
698 // exactly the label-width.
699 int LyXText::leftMargin(BufferView * bview, Row const * row) const
700 {
701         Inset * ins;
702         if ((row->par()->getChar(row->pos()) == Paragraph::META_INSET) &&
703                 (ins=row->par()->getInset(row->pos())) &&
704                 (ins->needFullRow() || ins->display()))
705                 return LYX_PAPER_MARGIN;
706
707         LyXTextClass const & tclass =
708                 textclasslist[bview->buffer()->params.textclass];
709         LyXLayout const & layout = tclass[row->par()->layout()];
710
711         string parindent = layout.parindent;
712
713         int x = LYX_PAPER_MARGIN;
714
715         x += lyxfont::signedWidth(tclass.leftmargin(), tclass.defaultfont());
716
717         // this is the way, LyX handles the LaTeX-Environments.
718         // I have had this idea very late, so it seems to be a
719         // later added hack and this is true
720         if (!row->par()->getDepth()) {
721                 if (row->par()->layout() == tclass.defaultLayoutName()) {
722                         // find the previous same level paragraph
723                         if (row->par()->previous()) {
724                                 Paragraph * newpar = row->par()
725                                         ->depthHook(row->par()->getDepth());
726                                 if (newpar &&
727                                     tclass[newpar->layout()].nextnoindent)
728                                         parindent.erase();
729                         }
730                 }
731         } else {
732                 // find the next level paragraph
733
734                 Paragraph * newpar =
735                         row->par()->outerHook();
736
737                 // make a corresponding row. Needed to call LeftMargin()
738
739                 // check wether it is a sufficent paragraph
740                 if (newpar && tclass[newpar->layout()].isEnvironment()) {
741                         Row dummyrow;
742                         dummyrow.par(newpar);
743                         dummyrow.pos(newpar->size());
744                         x = leftMargin(bview, &dummyrow);
745                 } else {
746                         // this is no longer an error, because this function
747                         // is used to clear impossible depths after changing
748                         // a layout. Since there is always a redo,
749                         // LeftMargin() is always called
750                         row->par()->params().depth(0);
751                 }
752
753                 if (newpar && row->par()->layout() == tclass.defaultLayoutName()) {
754                         if (newpar->params().noindent())
755                                 parindent.erase();
756                         else
757                                 parindent = tclass[newpar->layout()].parindent;
758                 }
759         }
760
761         LyXFont const labelfont = getLabelFont(bview->buffer(), row->par());
762         switch (layout.margintype) {
763         case MARGIN_DYNAMIC:
764                 if (!layout.leftmargin.empty()) {
765                         x += lyxfont::signedWidth(layout.leftmargin,
766                                                   tclass.defaultfont());
767                 }
768                 if (!row->par()->getLabelstring().empty()) {
769                         x += lyxfont::signedWidth(layout.labelindent,
770                                                   labelfont);
771                         x += lyxfont::width(row->par()->getLabelstring(),
772                                             labelfont);
773                         x += lyxfont::width(layout.labelsep, labelfont);
774                 }
775                 break;
776         case MARGIN_MANUAL:
777                 x += lyxfont::signedWidth(layout.labelindent, labelfont);
778                 if (row->pos() >= beginningOfMainBody(bview->buffer(), row->par())) {
779                         if (!row->par()->getLabelWidthString().empty()) {
780                                 x += lyxfont::width(row->par()->getLabelWidthString(),
781                                                labelfont);
782                                 x += lyxfont::width(layout.labelsep, labelfont);
783                         }
784                 }
785                 break;
786         case MARGIN_STATIC:
787                 x += lyxfont::signedWidth(layout.leftmargin, tclass.defaultfont()) * 4
788                         / (row->par()->getDepth() + 4);
789                 break;
790         case MARGIN_FIRST_DYNAMIC:
791                 if (layout.labeltype == LABEL_MANUAL) {
792                         if (row->pos() >= beginningOfMainBody(bview->buffer(), row->par())) {
793                                 x += lyxfont::signedWidth(layout.leftmargin,
794                                                           labelfont);
795                         } else {
796                                 x += lyxfont::signedWidth(layout.labelindent,
797                                                           labelfont);
798                         }
799                 } else if (row->pos()
800                            // Special case to fix problems with
801                            // theorems (JMarc)
802                            || (layout.labeltype == LABEL_STATIC
803                                && layout.latextype == LATEX_ENVIRONMENT
804                                && ! row->par()->isFirstInSequence())) {
805                         x += lyxfont::signedWidth(layout.leftmargin,
806                                                   labelfont);
807                 } else if (layout.labeltype != LABEL_TOP_ENVIRONMENT
808                            && layout.labeltype != LABEL_BIBLIO
809                            && layout.labeltype !=
810                            LABEL_CENTERED_TOP_ENVIRONMENT) {
811                         x += lyxfont::signedWidth(layout.labelindent,
812                                                   labelfont);
813                         x += lyxfont::width(layout.labelsep, labelfont);
814                         x += lyxfont::width(row->par()->getLabelstring(),
815                                             labelfont);
816                 }
817                 break;
818
819         case MARGIN_RIGHT_ADDRESS_BOX:
820         {
821                 // ok, a terrible hack. The left margin depends on the widest
822                 // row in this paragraph. Do not care about footnotes, they
823                 // are *NOT* allowed in the LaTeX realisation of this layout.
824
825                 // find the first row of this paragraph
826                 Row const * tmprow = row;
827                 while (tmprow->previous()
828                        && tmprow->previous()->par() == row->par())
829                         tmprow = tmprow->previous();
830
831                 int minfill = tmprow->fill();
832                 while (tmprow->next() && tmprow->next()->par() == row->par()) {
833                         tmprow = tmprow->next();
834                         if (tmprow->fill() < minfill)
835                                 minfill = tmprow->fill();
836                 }
837
838                 x += lyxfont::signedWidth(layout.leftmargin,
839                                           tclass.defaultfont());
840                 x += minfill;
841         }
842         break;
843         }
844
845         LyXAlignment align; // wrong type
846
847         if (row->par()->params().align() == LYX_ALIGN_LAYOUT)
848                 align = layout.align;
849         else
850                 align = row->par()->params().align();
851
852         // set the correct parindent
853         if (row->pos() == 0) {
854                 if ((layout.labeltype == LABEL_NO_LABEL
855                      || layout.labeltype == LABEL_TOP_ENVIRONMENT
856                      || layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
857                      || (layout.labeltype == LABEL_STATIC
858                          && layout.latextype == LATEX_ENVIRONMENT
859                          && ! row->par()->isFirstInSequence()))
860                     && align == LYX_ALIGN_BLOCK
861                     && !row->par()->params().noindent()
862                         // in tabulars and ert paragraphs are never indented!
863                         && (!row->par()->inInset() || !row->par()->inInset()->owner() ||
864                                 (row->par()->inInset()->owner()->lyxCode() != Inset::TABULAR_CODE &&
865                                  row->par()->inInset()->owner()->lyxCode() != Inset::ERT_CODE))
866                     && (row->par()->layout() != tclass.defaultLayoutName() ||
867                         bview->buffer()->params.paragraph_separation ==
868                         BufferParams::PARSEP_INDENT)) {
869                         x += lyxfont::signedWidth(parindent,
870                                                   tclass.defaultfont());
871                 } else if (layout.labeltype == LABEL_BIBLIO) {
872                         // ale970405 Right width for bibitems
873                         x += bibitemMaxWidth(bview, tclass.defaultfont());
874                 }
875         }
876
877         return x;
878 }
879
880
881 int LyXText::rightMargin(Buffer const * buf, Row const * row) const
882 {
883         Inset * ins;
884         if ((row->par()->getChar(row->pos()) == Paragraph::META_INSET) &&
885                 (ins=row->par()->getInset(row->pos())) &&
886                 (ins->needFullRow() || ins->display()))
887                 return LYX_PAPER_MARGIN;
888
889         LyXTextClass const & tclass = textclasslist[buf->params.textclass];
890         LyXLayout const & layout = tclass[row->par()->layout()];
891
892         int x = LYX_PAPER_MARGIN
893                 + lyxfont::signedWidth(tclass.rightmargin(),
894                                        tclass.defaultfont());
895
896         // this is the way, LyX handles the LaTeX-Environments.
897         // I have had this idea very late, so it seems to be a
898         // later added hack and this is true
899         if (row->par()->getDepth()) {
900                 // find the next level paragraph
901
902                 Paragraph * newpar = row->par();
903
904                 do {
905                         newpar = newpar->previous();
906                 } while (newpar
907                          && newpar->getDepth() >= row->par()->getDepth());
908
909                 // make a corresponding row. Needed to call LeftMargin()
910
911                 // check wether it is a sufficent paragraph
912                 if (newpar && tclass[newpar->layout()].isEnvironment()) {
913                         Row dummyrow;
914                         dummyrow.par(newpar);
915                         dummyrow.pos(0);
916                         x = rightMargin(buf, &dummyrow);
917                 } else {
918                         // this is no longer an error, because this function
919                         // is used to clear impossible depths after changing
920                         // a layout. Since there is always a redo,
921                         // LeftMargin() is always called
922                         row->par()->params().depth(0);
923                 }
924         }
925
926         //lyxerr << "rightmargin: " << layout->rightmargin << endl;
927         x += lyxfont::signedWidth(layout.rightmargin, tclass.defaultfont())
928                 * 4 / (row->par()->getDepth() + 4);
929         return x;
930 }
931
932
933 int LyXText::labelEnd(BufferView * bview, Row const * row) const
934 {
935         if (textclasslist[bview->buffer()->params.textclass][row->par()->layout()].margintype
936             == MARGIN_MANUAL) {
937                 Row tmprow;
938                 tmprow = *row;
939                 tmprow.pos(row->par()->size());
940                 return leftMargin(bview, &tmprow);  /* just the beginning
941                                                 of the main body */
942         } else
943                 return 0;  /* LabelEnd is only needed, if the
944                               layout fills a flushleft
945                               label. */
946 }
947
948
949 // get the next breakpoint in a given paragraph
950 pos_type
951 LyXText::nextBreakPoint(BufferView * bview, Row const * row, int width) const
952 {
953         Paragraph * par = row->par();
954
955         if (width < 0)
956                 return par->size();
957
958         pos_type const pos = row->pos();
959
960         // position of the last possible breakpoint
961         // -1 isn't a suitable value, but a flag
962         pos_type last_separator = -1;
963         width -= rightMargin(bview->buffer(), row);
964
965         pos_type const main_body =
966                 beginningOfMainBody(bview->buffer(), par);
967         LyXLayout const & layout =
968                 textclasslist[bview->buffer()->params.textclass][par->layout()];
969         pos_type i = pos;
970
971         if (layout.margintype == MARGIN_RIGHT_ADDRESS_BOX) {
972                 /* special code for right address boxes, only newlines count */
973                 while (i < par->size()) {
974                         if (par->isNewline(i)) {
975                                 last_separator = i;
976                                 i = par->size() - 1; // this means break
977                                 //x = width;
978                         } else if (par->isInset(i) && par->getInset(i)
979                                 && par->getInset(i)->display()) {
980                                 par->getInset(i)->display(false);
981                         }
982                         ++i;
983                 }
984         } else {
985                 // Last position is an invariant
986                 pos_type const last =
987                         par->size();
988                 // this is the usual handling
989                 int x = leftMargin(bview, row);
990                 bool doitonetime = true;
991                 while (doitonetime || ((x < width) && (i < last))) {
992                         doitonetime = false;
993                         char const c = par->getChar(i);
994                         Inset * in = 0;
995                         if (c == Paragraph::META_INSET)
996                                 in = par->getInset(i);
997                         if (IsNewlineChar(c)) {
998                                 last_separator = i;
999                                 x = width; // this means break
1000                         } else if (in && !in->isChar()) {
1001                                 // check wether a Display() inset is
1002                                 // valid here. if not, change it to
1003                                 // non-display
1004                                 if (in->display() &&
1005                                     (layout.isCommand() ||
1006                                      (layout.labeltype == LABEL_MANUAL
1007                                       && i < beginningOfMainBody(bview->buffer(), par))))
1008                                 {
1009                                         // display istn't allowd
1010                                         in->display(false);
1011                                         x += singleWidth(bview, par, i, c);
1012                                 } else if (in->display() || in->needFullRow()) {
1013                                         // So break the line here
1014                                         if (i == pos) {
1015                                                 if (pos < last-1) {
1016                                                         last_separator = i;
1017                                                         if (par->isLineSeparator(i+1))
1018                                                                 ++last_separator;
1019                                                 } else
1020                                                         last_separator = last; // to avoid extra rows
1021                                         } else
1022                                                 last_separator = i - 1;
1023                                         x = width;  // this means break
1024                                 } else {
1025                                         x += singleWidth(bview, par, i, c);
1026                                         // we have to check this separately as we could have a
1027                                         // lineseparator and then the algorithm below would prefer
1028                                         // that which IS wrong! We should always break on an inset
1029                                         // if it's too long and not on the last separator.
1030                                         // Maybe the only exeption is insets used as chars but
1031                                         // then we would have to have a special function inside
1032                                         // the inset to tell us this. Till then we leave it as
1033                                         // it is now. (Jug 20020106)
1034                                         if (pos < i && x >= width && last_separator >= 0)
1035                                                 last_separator = i - 1;
1036                                 }
1037                         } else  {
1038                                 if (par->isLineSeparator(i))
1039                                         last_separator = i;
1040                                 x += singleWidth(bview, par, i, c);
1041                         }
1042                         ++i;
1043                         if (i == main_body) {
1044                                 x += lyxfont::width(layout.labelsep,
1045                                                     getLabelFont(bview->buffer(), par));
1046                                 if (par->isLineSeparator(i - 1))
1047                                         x-= singleWidth(bview, par, i - 1);
1048                                 int left_margin = labelEnd(bview, row);
1049                                 if (x < left_margin)
1050                                         x = left_margin;
1051                         }
1052                 }
1053                 if ((pos+1 < i) && (last_separator < 0) && (x >= width))
1054                         last_separator = i - 2;
1055                 else if ((pos < i) && (last_separator < 0) && (x >= width))
1056                         last_separator = i - 1;
1057                 // end of paragraph is always a suitable separator
1058                 else if (i == last && x < width)
1059                         last_separator = i;
1060         }
1061
1062         // well, if last_separator is still 0, the line isn't breakable.
1063         // don't care and cut simply at the end
1064         if (last_separator < 0) {
1065                 last_separator = i;
1066         }
1067
1068         // manual labels cannot be broken in LaTeX, do not care
1069         if (main_body && last_separator < main_body)
1070                 last_separator = main_body - 1;
1071
1072         return last_separator;
1073 }
1074
1075
1076 // returns the minimum space a row needs on the screen in pixel
1077 int LyXText::fill(BufferView * bview, Row * row, int paper_width) const
1078 {
1079         if (paper_width < 0)
1080                 return 0;
1081
1082         int w;
1083         // get the pure distance
1084         pos_type const last = rowLastPrintable(row);
1085
1086         // special handling of the right address boxes
1087         if (textclasslist[bview->buffer()->params.textclass][row->par()->layout()].margintype
1088             == MARGIN_RIGHT_ADDRESS_BOX)
1089         {
1090                 int const tmpfill = row->fill();
1091                 row->fill(0); // the minfill in MarginLeft()
1092                 w = leftMargin(bview, row);
1093                 row->fill(tmpfill);
1094         } else
1095                 w = leftMargin(bview, row);
1096
1097         LyXLayout const & layout = textclasslist[bview->buffer()->params.textclass][row->par()->layout()];
1098         pos_type const main_body =
1099                 beginningOfMainBody(bview->buffer(), row->par());
1100         pos_type i = row->pos();
1101
1102         while (i <= last) {
1103                 if (main_body > 0 && i == main_body) {
1104                         w += lyxfont::width(layout.labelsep, getLabelFont(bview->buffer(), row->par()));
1105                         if (row->par()->isLineSeparator(i - 1))
1106                                 w -= singleWidth(bview, row->par(), i - 1);
1107                         int left_margin = labelEnd(bview, row);
1108                         if (w < left_margin)
1109                                 w = left_margin;
1110                 }
1111                 w += singleWidth(bview, row->par(), i);
1112                 ++i;
1113         }
1114         if (main_body > 0 && main_body > last) {
1115                 w += lyxfont::width(layout.labelsep, getLabelFont(bview->buffer(), row->par()));
1116                 if (last >= 0 && row->par()->isLineSeparator(last))
1117                         w -= singleWidth(bview, row->par(), last);
1118                 int const left_margin = labelEnd(bview, row);
1119                 if (w < left_margin)
1120                         w = left_margin;
1121         }
1122
1123         int const fill = paper_width - w - rightMargin(bview->buffer(), row);
1124         return fill;
1125 }
1126
1127
1128 // returns the minimum space a manual label needs on the screen in pixel
1129 int LyXText::labelFill(BufferView * bview, Row const * row) const
1130 {
1131         pos_type last = beginningOfMainBody(bview->buffer(), row->par()) - 1;
1132         // -1 because a label ends either with a space that is in the label,
1133         // or with the beginning of a footnote that is outside the label.
1134
1135         // I don't understand this code in depth, but sometimes "last" is
1136         // less than 0 and this causes a crash. This fix seems to work
1137         // correctly, but I bet the real error is elsewhere.  The bug is
1138         // triggered when you have an open footnote in a paragraph
1139         // environment with a manual label. (Asger)
1140         if (last < 0) last = 0;
1141
1142         if (row->par()->isLineSeparator(last)) /* a sepearator at this end
1143                                                 does not count */
1144                 --last;
1145
1146         int w = 0;
1147         pos_type i = row->pos();
1148         while (i <= last) {
1149                 w += singleWidth(bview, row->par(), i);
1150                 ++i;
1151         }
1152
1153         int fill = 0;
1154         if (!row->par()->params().labelWidthString().empty()) {
1155                 fill = max(lyxfont::width(row->par()->params().labelWidthString(),
1156                                           getLabelFont(bview->buffer(), row->par())) - w,
1157                            0);
1158         }
1159
1160         return fill;
1161 }
1162
1163
1164 // returns the number of separators in the specified row. The separator
1165 // on the very last column doesnt count
1166 int LyXText::numberOfSeparators(Buffer const * buf, Row const * row) const
1167 {
1168         pos_type last = rowLastPrintable(row);
1169         pos_type p = max(row->pos(), beginningOfMainBody(buf, row->par()));
1170
1171         int n = 0;
1172         for (; p <= last; ++p) {
1173                 if (row->par()->isSeparator(p)) {
1174                         ++n;
1175                 }
1176         }
1177         return n;
1178 }
1179
1180
1181 // returns the number of hfills in the specified row. The LyX-Hfill is
1182 // a LaTeX \hfill so that the hfills at the beginning and at the end were
1183 // ignored. This is *MUCH* more usefull than not to ignore!
1184 int LyXText::numberOfHfills(Buffer const * buf, Row const * row) const
1185 {
1186         pos_type const last = rowLast(row);
1187         pos_type first = row->pos();
1188
1189         if (first) { /* hfill *DO* count at the beginning
1190                       * of paragraphs! */
1191                 while (first <= last && row->par()->isHfill(first)) {
1192                         ++first;
1193                 }
1194         }
1195
1196         first = max(first, beginningOfMainBody(buf, row->par()));
1197         int n = 0;
1198         for (pos_type p = first; p <= last; ++p) {
1199                 // last, because the end is ignored!
1200
1201                 if (row->par()->isHfill(p)) {
1202                         ++n;
1203                 }
1204         }
1205         return n;
1206 }
1207
1208
1209 // like NumberOfHfills, but only those in the manual label!
1210 int LyXText::numberOfLabelHfills(Buffer const * buf, Row const * row) const
1211 {
1212         pos_type last = rowLast(row);
1213         pos_type first = row->pos();
1214         if (first) { /* hfill *DO* count at the beginning
1215                       * of paragraphs! */
1216                 while (first < last && row->par()->isHfill(first))
1217                         ++first;
1218         }
1219
1220         last = min(last, beginningOfMainBody(buf, row->par()));
1221         int n = 0;
1222         for (pos_type p = first; p < last; ++p) {
1223                 // last, because the end is ignored!
1224                 if (row->par()->isHfill(p)) {
1225                         ++n;
1226                 }
1227         }
1228         return n;
1229 }
1230
1231
1232 // returns true, if a expansion is needed.
1233 // Rules are given by LaTeX
1234 bool LyXText::hfillExpansion(Buffer const * buf, Row const * row_ptr,
1235                              pos_type pos) const
1236 {
1237         // by the way, is it a hfill?
1238         if (!row_ptr->par()->isHfill(pos))
1239                 return false;
1240
1241         // at the end of a row it does not count
1242         // unless another hfill exists on the line
1243         if (pos >= rowLast(row_ptr)) {
1244                 pos_type i = row_ptr->pos();
1245                 while (i < pos && !row_ptr->par()->isHfill(i)) {
1246                         ++i;
1247                 }
1248                 if (i == pos) {
1249                         return false;
1250                 }
1251         }
1252
1253         // at the beginning of a row it does not count, if it is not
1254         // the first row of a paragaph
1255         if (!row_ptr->pos())
1256                 return true;
1257
1258         // in some labels  it does not count
1259         if (textclasslist[buf->params.textclass][row_ptr->par()->layout()].margintype
1260             != MARGIN_MANUAL
1261             && pos < beginningOfMainBody(buf, row_ptr->par()))
1262                 return false;
1263
1264         // if there is anything between the first char of the row and
1265         // the sepcified position that is not a newline and not a hfill,
1266         // the hfill will count, otherwise not
1267         pos_type i = row_ptr->pos();
1268         while (i < pos && (row_ptr->par()->isNewline(i)
1269                            || row_ptr->par()->isHfill(i)))
1270                 ++i;
1271
1272         return i != pos;
1273 }
1274
1275
1276 LColor::color LyXText::backgroundColor()
1277 {
1278         if (inset_owner)
1279                 return inset_owner->backgroundColor();
1280         else
1281                 return LColor::background;
1282 }
1283
1284 void LyXText::setHeightOfRow(BufferView * bview, Row * row_ptr) const
1285 {
1286         /* get the maximum ascent and the maximum descent */
1287         int asc = 0;
1288         int desc = 0;
1289         float layoutasc = 0;
1290         float layoutdesc = 0;
1291         float tmptop = 0;
1292         LyXFont tmpfont;
1293         Inset * tmpinset = 0;
1294
1295         /* ok , let us initialize the maxasc and maxdesc value.
1296          * This depends in LaTeX of the font of the last character
1297          * in the paragraph. The hack below is necessary because
1298          * of the possibility of open footnotes */
1299
1300         /* Correction: only the fontsize count. The other properties
1301            are taken from the layoutfont. Nicer on the screen :) */
1302         Paragraph * par = row_ptr->par();
1303         Paragraph * firstpar = row_ptr->par();
1304
1305         LyXLayout const & layout = textclasslist[bview->buffer()->params.textclass][firstpar->layout()];
1306
1307         // as max get the first character of this row then it can increes but not
1308         // decrees the height. Just some point to start with so we don't have to
1309         // do the assignment below too often.
1310         LyXFont font = getFont(bview->buffer(), par, row_ptr->pos());
1311         LyXFont::FONT_SIZE const tmpsize = font.size();
1312         font = getLayoutFont(bview->buffer(), par);
1313         LyXFont::FONT_SIZE const size = font.size();
1314         font.setSize(tmpsize);
1315
1316         LyXFont labelfont = getLabelFont(bview->buffer(), par);
1317
1318         float spacing_val = 1.0;
1319         if (!row_ptr->par()->params().spacing().isDefault()) {
1320                 spacing_val = row_ptr->par()->params().spacing().getValue();
1321         } else {
1322                 spacing_val = bview->buffer()->params.spacing.getValue();
1323         }
1324         //lyxerr << "spacing_val = " << spacing_val << endl;
1325
1326         int maxasc = int(lyxfont::maxAscent(font) *
1327                          layout.spacing.getValue() *
1328                          spacing_val);
1329         int maxdesc = int(lyxfont::maxDescent(font) *
1330                           layout.spacing.getValue() *
1331                           spacing_val);
1332         pos_type const pos_end = rowLast(row_ptr);
1333         int labeladdon = 0;
1334         int maxwidth = 0;
1335
1336         // Check if any insets are larger
1337         for (pos_type pos = row_ptr->pos(); pos <= pos_end; ++pos) {
1338                 if (row_ptr->par()->isInset(pos)) {
1339                         tmpfont = getFont(bview->buffer(), row_ptr->par(), pos);
1340                         tmpinset = row_ptr->par()->getInset(pos);
1341                         if (tmpinset) {
1342 #if 1 // this is needed for deep update on initialitation
1343                                 tmpinset->update(bview, tmpfont);
1344 #endif
1345                                 asc = tmpinset->ascent(bview, tmpfont);
1346                                 desc = tmpinset->descent(bview, tmpfont);
1347                                 maxwidth += tmpinset->width(bview, tmpfont);
1348                                 maxasc = max(maxasc, asc);
1349                                 maxdesc = max(maxdesc, desc);
1350                         }
1351                 } else {
1352                         maxwidth += singleWidth(bview, row_ptr->par(), pos);
1353                 }
1354         }
1355
1356         // Check if any custom fonts are larger (Asger)
1357         // This is not completely correct, but we can live with the small,
1358         // cosmetic error for now.
1359         LyXFont::FONT_SIZE maxsize =
1360                 row_ptr->par()->highestFontInRange(row_ptr->pos(), pos_end, size);
1361         if (maxsize > font.size()) {
1362                 font.setSize(maxsize);
1363
1364                 asc = lyxfont::maxAscent(font);
1365                 desc = lyxfont::maxDescent(font);
1366                 if (asc > maxasc)
1367                         maxasc = asc;
1368                 if (desc > maxdesc)
1369                         maxdesc = desc;
1370         }
1371
1372         // This is nicer with box insets:
1373         ++maxasc;
1374         ++maxdesc;
1375
1376         row_ptr->ascent_of_text(maxasc);
1377
1378         // is it a top line?
1379         if (!row_ptr->pos() && (row_ptr->par() == firstpar)) {
1380
1381                 // some parksips VERY EASY IMPLEMENTATION
1382                 if (bview->buffer()->params.paragraph_separation ==
1383                         BufferParams::PARSEP_SKIP)
1384                 {
1385                         if (layout.isParagraph()
1386                                 && firstpar->getDepth() == 0
1387                                 && firstpar->previous())
1388                         {
1389                                 maxasc += bview->buffer()->params.getDefSkip().inPixels(bview);
1390                         } else if (firstpar->previous() &&
1391                                    textclasslist[bview->buffer()->params.textclass][firstpar->previous()->layout()].isParagraph() &&
1392                                    firstpar->previous()->getDepth() == 0)
1393                         {
1394                                 // is it right to use defskip here too? (AS)
1395                                 maxasc += bview->buffer()->params.getDefSkip().inPixels(bview);
1396                         }
1397                 }
1398
1399                 // the paper margins
1400                 if (!row_ptr->par()->previous() && bv_owner)
1401                         maxasc += LYX_PAPER_MARGIN;
1402
1403                 // add the vertical spaces, that the user added
1404                 maxasc += getLengthMarkerHeight(bview, firstpar->params().spaceTop());
1405
1406                 // do not forget the DTP-lines!
1407                 // there height depends on the font of the nearest character
1408                 if (firstpar->params().lineTop())
1409                         maxasc += 2 * lyxfont::ascent('x', getFont(bview->buffer(),
1410                                                                    firstpar, 0));
1411
1412                 // and now the pagebreaks
1413                 if (firstpar->params().pagebreakTop())
1414                         maxasc += 3 * defaultHeight();
1415
1416                 // This is special code for the chapter, since the label of this
1417                 // layout is printed in an extra row
1418                 if (layout.labeltype == LABEL_COUNTER_CHAPTER
1419                         && bview->buffer()->params.secnumdepth >= 0)
1420                 {
1421                         float spacing_val = 1.0;
1422                         if (!row_ptr->par()->params().spacing().isDefault()) {
1423                                 spacing_val = row_ptr->par()->params().spacing().getValue();
1424                         } else {
1425                                 spacing_val = bview->buffer()->params.spacing.getValue();
1426                         }
1427
1428                         labeladdon = int(lyxfont::maxDescent(labelfont) *
1429                                          layout.spacing.getValue() *
1430                                          spacing_val)
1431                                 + int(lyxfont::maxAscent(labelfont) *
1432                                       layout.spacing.getValue() *
1433                                       spacing_val);
1434                 }
1435
1436                 // special code for the top label
1437                 if ((layout.labeltype == LABEL_TOP_ENVIRONMENT
1438                      || layout.labeltype == LABEL_BIBLIO
1439                      || layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
1440                     && row_ptr->par()->isFirstInSequence()
1441                     && !row_ptr->par()->getLabelstring().empty())
1442                 {
1443                         float spacing_val = 1.0;
1444                         if (!row_ptr->par()->params().spacing().isDefault()) {
1445                                 spacing_val = row_ptr->par()->params().spacing().getValue();
1446                         } else {
1447                                 spacing_val = bview->buffer()->params.spacing.getValue();
1448                         }
1449
1450                         labeladdon = int(
1451                                 (lyxfont::maxAscent(labelfont) *
1452                                  layout.spacing.getValue() *
1453                                  spacing_val)
1454                                 +(lyxfont::maxDescent(labelfont) *
1455                                   layout.spacing.getValue() *
1456                                   spacing_val)
1457                                 + layout.topsep * defaultHeight()
1458                                 + layout.labelbottomsep *  defaultHeight());
1459                 }
1460
1461                 // and now the layout spaces, for example before and after a section,
1462                 // or between the items of a itemize or enumerate environment
1463
1464                 if (!firstpar->params().pagebreakTop()) {
1465                         Paragraph * prev = row_ptr->par()->previous();
1466                         if (prev)
1467                                 prev = row_ptr->par()->depthHook(row_ptr->par()->getDepth());
1468                         if (prev && prev->layout() == firstpar->layout() &&
1469                                 prev->getDepth() == firstpar->getDepth() &&
1470                                 prev->getLabelWidthString() == firstpar->getLabelWidthString())
1471                         {
1472                                 layoutasc = (layout.itemsep * defaultHeight());
1473                         } else if (row_ptr->previous()) {
1474                                 tmptop = layout.topsep;
1475
1476                                 if (row_ptr->previous()->par()->getDepth() >= row_ptr->par()->getDepth())
1477                                         tmptop -= textclasslist[bview->buffer()->params.textclass][row_ptr->previous()->par()->layout()].bottomsep;
1478
1479                                 if (tmptop > 0)
1480                                         layoutasc = (tmptop * defaultHeight());
1481                         } else if (row_ptr->par()->params().lineTop()) {
1482                                 tmptop = layout.topsep;
1483
1484                                 if (tmptop > 0)
1485                                         layoutasc = (tmptop * defaultHeight());
1486                         }
1487
1488                         prev = row_ptr->par()->outerHook();
1489                         if (prev)  {
1490                                 maxasc += int(textclasslist[bview->buffer()->params.textclass][prev->layout()].parsep * defaultHeight());
1491                         } else {
1492                                 if (firstpar->previous() &&
1493                                         firstpar->previous()->getDepth() == 0 &&
1494                                         firstpar->previous()->layout() !=
1495                                         firstpar->layout())
1496                                 {
1497                                         // avoid parsep
1498                                 } else if (firstpar->previous()) {
1499                                         maxasc += int(layout.parsep * defaultHeight());
1500                                 }
1501                         }
1502                 }
1503         }
1504
1505         // is it a bottom line?
1506         if (row_ptr->par() == par
1507                 && (!row_ptr->next() || row_ptr->next()->par() != row_ptr->par()))
1508         {
1509                 // the paper margins
1510                 if (!par->next() && bv_owner)
1511                         maxdesc += LYX_PAPER_MARGIN;
1512
1513                 // add the vertical spaces, that the user added
1514                 maxdesc += getLengthMarkerHeight(bview, firstpar->params().spaceBottom());
1515
1516                 // do not forget the DTP-lines!
1517                 // there height depends on the font of the nearest character
1518                 if (firstpar->params().lineBottom())
1519                         maxdesc += 2 * lyxfont::ascent('x',
1520                                                        getFont(bview->buffer(),
1521                                                                par,
1522                                                                max(pos_type(0), par->size() - 1)));
1523
1524                 // and now the pagebreaks
1525                 if (firstpar->params().pagebreakBottom())
1526                         maxdesc += 3 * defaultHeight();
1527
1528                 // and now the layout spaces, for example before and after
1529                 // a section, or between the items of a itemize or enumerate
1530                 // environment
1531                 if (!firstpar->params().pagebreakBottom()
1532                     && row_ptr->par()->next()) {
1533                         Paragraph * nextpar = row_ptr->par()->next();
1534                         Paragraph * comparepar = row_ptr->par();
1535                         float usual = 0;
1536                         float unusual = 0;
1537
1538                         if (comparepar->getDepth() > nextpar->getDepth()) {
1539                                 usual = (textclasslist[bview->buffer()->params.textclass][comparepar->layout()].bottomsep * defaultHeight());
1540                                 comparepar = comparepar->depthHook(nextpar->getDepth());
1541                                 if (comparepar->layout()!= nextpar->layout()
1542                                         || nextpar->getLabelWidthString() !=
1543                                         comparepar->getLabelWidthString())
1544                                 {
1545                                         unusual = (textclasslist[bview->buffer()->params.textclass][comparepar->layout()].bottomsep * defaultHeight());
1546                                 }
1547                                 if (unusual > usual)
1548                                         layoutdesc = unusual;
1549                                 else
1550                                         layoutdesc = usual;
1551                         } else if (comparepar->getDepth() ==  nextpar->getDepth()) {
1552
1553                                 if (comparepar->layout() != nextpar->layout()
1554                                         || nextpar->getLabelWidthString() !=
1555                                         comparepar->getLabelWidthString())
1556                                         layoutdesc = int(textclasslist[bview->buffer()->params.textclass][comparepar->layout()].bottomsep * defaultHeight());
1557                         }
1558                 }
1559         }
1560
1561         // incalculate the layout spaces
1562         maxasc += int(layoutasc * 2 / (2 + firstpar->getDepth()));
1563         maxdesc += int(layoutdesc * 2 / (2 + firstpar->getDepth()));
1564
1565         // calculate the new height of the text
1566         height -= row_ptr->height();
1567
1568         row_ptr->height(maxasc + maxdesc + labeladdon);
1569         row_ptr->baseline(maxasc + labeladdon);
1570
1571         height += row_ptr->height();
1572         float x = 0;
1573         if (layout.margintype != MARGIN_RIGHT_ADDRESS_BOX) {
1574                 float dummy;
1575                 // this IS needed
1576                 row_ptr->width(maxwidth);
1577                 prepareToPrint(bview, row_ptr, x, dummy, dummy, dummy, false);
1578         }
1579         row_ptr->width(int(maxwidth + x));
1580         if (inset_owner) {
1581                 Row * r = firstrow;
1582                 width = max(0,workWidth(bview));
1583                 while (r) {
1584                         if (r->width() > width)
1585                                 width = r->width();
1586                         r = r->next();
1587                 }
1588         }
1589 }
1590
1591
1592 /* Appends the implicit specified paragraph behind the specified row,
1593  * start at the implicit given position */
1594 void LyXText::appendParagraph(BufferView * bview, Row * row) const
1595 {
1596         bool not_ready = true;
1597
1598         // The last character position of a paragraph is an invariant so we can
1599         // safely get it here. (Asger)
1600         pos_type const lastposition = row->par()->size();
1601         do {
1602                 // Get the next breakpoint
1603                 pos_type z = nextBreakPoint(bview, row, workWidth(bview));
1604
1605                 Row * tmprow = row;
1606
1607                 // Insert the new row
1608                 if (z < lastposition) {
1609                         ++z;
1610                         insertRow(row, row->par(), z);
1611                         row = row->next();
1612
1613                         row->height(0);
1614                 } else
1615                         not_ready = false;
1616
1617                 // Set the dimensions of the row
1618                 // fixed fill setting now by calling inset->update() in
1619                 // SingleWidth when needed!
1620                 tmprow->fill(fill(bview, tmprow, workWidth(bview)));
1621                 setHeightOfRow(bview, tmprow);
1622
1623         } while (not_ready);
1624 }
1625
1626
1627 void LyXText::breakAgain(BufferView * bview, Row * row) const
1628 {
1629         bool not_ready = true;
1630
1631         do  {
1632                 // get the next breakpoint
1633                 pos_type z = nextBreakPoint(bview, row, workWidth(bview));
1634                 Row * tmprow = row;
1635
1636                 if (z < row->par()->size()) {
1637                         if (!row->next() || (row->next() && row->next()->par() != row->par())) {
1638                                 // insert a new row
1639                                 ++z;
1640                                 insertRow(row, row->par(), z);
1641                                 row = row->next();
1642                                 row->height(0);
1643                         } else  {
1644                                 row = row->next();
1645                                 ++z;
1646                                 if (row->pos() == z)
1647                                         not_ready = false;     // the rest will not change
1648                                 else {
1649                                         row->pos(z);
1650                                 }
1651                         }
1652                 } else {
1653                         /* if there are some rows too much, delete them */
1654                         /* only if you broke the whole paragraph! */
1655                         Row * tmprow2 = row;
1656                         while (tmprow2->next() && tmprow2->next()->par() == row->par()) {
1657                                 tmprow2 = tmprow2->next();
1658                         }
1659                         while (tmprow2 != row) {
1660                                 tmprow2 = tmprow2->previous();
1661                                 removeRow(tmprow2->next());
1662                         }
1663                         not_ready = false;
1664                 }
1665
1666                 /* set the dimensions of the row */
1667                 tmprow->fill(fill(bview, tmprow, workWidth(bview)));
1668                 setHeightOfRow(bview, tmprow);
1669         } while (not_ready);
1670 }
1671
1672
1673 // this is just a little changed version of break again
1674 void LyXText::breakAgainOneRow(BufferView * bview, Row * row)
1675 {
1676         // get the next breakpoint
1677         pos_type z = nextBreakPoint(bview, row, workWidth(bview));
1678         Row * tmprow = row;
1679
1680         if (z < row->par()->size()) {
1681                 if (!row->next()
1682                     || (row->next() && row->next()->par() != row->par())) {
1683                         /* insert a new row */
1684                         ++z;
1685                         insertRow(row, row->par(), z);
1686                         row = row->next();
1687                         row->height(0);
1688                 } else  {
1689                         row = row->next();
1690                         ++z;
1691                         if (row->pos() != z)
1692                                 row->pos(z);
1693                 }
1694         } else {
1695                 // if there are some rows too much, delete them
1696                 // only if you broke the whole paragraph!
1697                 Row * tmprow2 = row;
1698                 while (tmprow2->next()
1699                        && tmprow2->next()->par() == row->par()) {
1700                         tmprow2 = tmprow2->next();
1701                 }
1702                 while (tmprow2 != row) {
1703                         tmprow2 = tmprow2->previous();
1704                         removeRow(tmprow2->next());
1705                 }
1706         }
1707
1708         // set the dimensions of the row
1709         tmprow->fill(fill(bview, tmprow, workWidth(bview)));
1710         setHeightOfRow(bview, tmprow);
1711 }
1712
1713
1714 void LyXText::breakParagraph(BufferView * bview, char keep_layout)
1715 {
1716         LyXTextClass const & tclass =
1717                 textclasslist[bview->buffer()->params.textclass];
1718    LyXLayout const & layout = tclass[cursor.par()->layout()];
1719
1720    // this is only allowed, if the current paragraph is not empty or caption
1721    // and if it has not the keepempty flag aktive
1722    if ((cursor.par()->size() <= 0)
1723        && layout.labeltype != LABEL_SENSITIVE
1724            && !layout.keepempty)
1725            return;
1726
1727    setUndo(bview, Undo::FINISH, cursor.par(), cursor.par()->next());
1728
1729    // Always break behind a space
1730    //
1731    // It is better to erase the space (Dekel)
1732    if (cursor.pos() < cursor.par()->size()
1733        && cursor.par()->isLineSeparator(cursor.pos()))
1734            cursor.par()->erase(cursor.pos());
1735            // cursor.pos(cursor.pos() + 1);
1736
1737    // break the paragraph
1738    if (keep_layout)
1739      keep_layout = 2;
1740    else
1741      keep_layout = layout.isEnvironment();
1742    cursor.par()->breakParagraph(bview->buffer()->params, cursor.pos(),
1743                                 keep_layout);
1744
1745    // well this is the caption hack since one caption is really enough
1746    if (layout.labeltype == LABEL_SENSITIVE) {
1747      if (!cursor.pos())
1748              // set to standard-layout
1749              cursor.par()->applyLayout(tclass.defaultLayoutName());
1750      else
1751              // set to standard-layout
1752              cursor.par()->next()->applyLayout(tclass.defaultLayoutName());
1753    }
1754
1755    /* if the cursor is at the beginning of a row without prior newline,
1756     * move one row up!
1757     * This touches only the screen-update. Otherwise we would may have
1758     * an empty row on the screen */
1759    if (cursor.pos() && !cursor.row()->par()->isNewline(cursor.row()->pos() - 1)
1760        && cursor.row()->pos() == cursor.pos())
1761    {
1762            cursorLeft(bview);
1763    }
1764
1765    status(bview, LyXText::NEED_MORE_REFRESH);
1766    refresh_row = cursor.row();
1767    refresh_y = cursor.y() - cursor.row()->baseline();
1768
1769    // Do not forget the special right address boxes
1770    if (layout.margintype == MARGIN_RIGHT_ADDRESS_BOX) {
1771       while (refresh_row->previous() &&
1772              refresh_row->previous()->par() == refresh_row->par()) {
1773               refresh_row = refresh_row->previous();
1774               refresh_y -= refresh_row->height();
1775       }
1776    }
1777    removeParagraph(cursor.row());
1778
1779    // set the dimensions of the cursor row
1780    cursor.row()->fill(fill(bview, cursor.row(), workWidth(bview)));
1781
1782    setHeightOfRow(bview, cursor.row());
1783
1784    while (cursor.par()->next()->size()
1785           && cursor.par()->next()->isNewline(0))
1786            cursor.par()->next()->erase(0);
1787
1788    insertParagraph(bview, cursor.par()->next(), cursor.row());
1789
1790    updateCounters(bview, cursor.row()->previous());
1791
1792    /* This check is necessary. Otherwise the new empty paragraph will
1793     * be deleted automatically. And it is more friendly for the user! */
1794    if (cursor.pos() || layout.keepempty)
1795            setCursor(bview, cursor.par()->next(), 0);
1796    else
1797            setCursor(bview, cursor.par(), 0);
1798
1799    if (cursor.row()->next())
1800            breakAgain(bview, cursor.row()->next());
1801
1802    need_break_row = 0;
1803 }
1804
1805
1806 // Just a macro to make some thing easier.
1807 void LyXText::redoParagraph(BufferView * bview) const
1808 {
1809         clearSelection();
1810         redoParagraphs(bview, cursor, cursor.par()->next());
1811         setCursorIntern(bview, cursor.par(), cursor.pos());
1812 }
1813
1814
1815 /* insert a character, moves all the following breaks in the
1816  * same Paragraph one to the right and make a rebreak */
1817 void LyXText::insertChar(BufferView * bview, char c)
1818 {
1819         setUndo(bview, Undo::INSERT, cursor.par(), cursor.par()->next());
1820
1821         // When the free-spacing option is set for the current layout,
1822         // disable the double-space checking
1823
1824         bool const freeSpacing =
1825                 textclasslist[bview->buffer()->params.textclass][cursor.row()->par()->layout()].free_spacing ||
1826                 cursor.row()->par()->isFreeSpacing();
1827
1828         if (lyxrc.auto_number) {
1829                 static string const number_operators = "+-/*";
1830                 static string const number_unary_operators = "+-";
1831                 static string const number_seperators = ".,:";
1832
1833                 if (current_font.number() == LyXFont::ON) {
1834                         if (!IsDigit(c) && !contains(number_operators, c) &&
1835                             !(contains(number_seperators, c) &&
1836                               cursor.pos() >= 1 &&
1837                               cursor.pos() < cursor.par()->size() &&
1838                               getFont(bview->buffer(),
1839                                       cursor.par(),
1840                                       cursor.pos()).number() == LyXFont::ON &&
1841                               getFont(bview->buffer(),
1842                                       cursor.par(),
1843                                       cursor.pos() - 1).number() == LyXFont::ON)
1844                            )
1845                                 number(bview); // Set current_font.number to OFF
1846                 } else if (IsDigit(c) &&
1847                            real_current_font.isVisibleRightToLeft()) {
1848                         number(bview); // Set current_font.number to ON
1849
1850                         if (cursor.pos() > 0) {
1851                                 char const c = cursor.par()->getChar(cursor.pos() - 1);
1852                                 if (contains(number_unary_operators, c) &&
1853                                     (cursor.pos() == 1 ||
1854                                      cursor.par()->isSeparator(cursor.pos() - 2) ||
1855                                      cursor.par()->isNewline(cursor.pos() - 2))
1856                                   ) {
1857                                         setCharFont(bview->buffer(),
1858                                                     cursor.par(),
1859                                                     cursor.pos() - 1,
1860                                                     current_font);
1861                                 } else if (contains(number_seperators, c) &&
1862                                            cursor.pos() >= 2 &&
1863                                            getFont(bview->buffer(),
1864                                                    cursor.par(),
1865                                                    cursor.pos() - 2).number() == LyXFont::ON) {
1866                                         setCharFont(bview->buffer(),
1867                                                     cursor.par(),
1868                                                     cursor.pos() - 1,
1869                                                     current_font);
1870                                 }
1871                         }
1872                 }
1873         }
1874
1875
1876         /* First check, if there will be two blanks together or a blank at
1877           the beginning of a paragraph.
1878           I decided to handle blanks like normal characters, the main
1879           difference are the special checks when calculating the row.fill
1880           (blank does not count at the end of a row) and the check here */
1881
1882         // The bug is triggered when we type in a description environment:
1883         // The current_font is not changed when we go from label to main text
1884         // and it should (along with realtmpfont) when we type the space.
1885         // CHECK There is a bug here! (Asger)
1886
1887         LyXFont realtmpfont = real_current_font;
1888         LyXFont rawtmpfont = current_font;  /* store the current font.
1889                                      * This is because of the use
1890                                      * of cursor movements. The moving
1891                                      * cursor would refresh the
1892                                      * current font */
1893
1894         // Get the font that is used to calculate the baselineskip
1895         pos_type const lastpos = cursor.par()->size();
1896         LyXFont rawparfont =
1897                 cursor.par()->getFontSettings(bview->buffer()->params,
1898                                               lastpos - 1);
1899
1900         bool jumped_over_space = false;
1901
1902         if (!freeSpacing && IsLineSeparatorChar(c)) {
1903                 if ((cursor.pos() > 0
1904                      && cursor.par()->isLineSeparator(cursor.pos() - 1))
1905                     || (cursor.pos() > 0
1906                         && cursor.par()->isNewline(cursor.pos() - 1))
1907                     || (cursor.pos() == 0)) {
1908                         static bool sent_space_message = false;
1909                         if (!sent_space_message) {
1910                                 if (cursor.pos() == 0)
1911                                         bview->owner()->message(_("You cannot insert a space at the beginning of a paragraph.  Please read the Tutorial."));
1912                                 else
1913                                         bview->owner()->message(_("You cannot type two spaces this way.  Please read the Tutorial."));
1914                                 sent_space_message = true;
1915                         }
1916                         charInserted();
1917                         return;
1918                 }
1919         } else if (IsNewlineChar(c)) {
1920                 if (cursor.pos() <= beginningOfMainBody(bview->buffer(),
1921                                                         cursor.par()))
1922                 {
1923                         charInserted();
1924                         return;
1925                 }
1926                 /* No newline at first position
1927                  * of a paragraph or behind labels.
1928                  * TeX does not allow that */
1929
1930                 if (cursor.pos() < cursor.par()->size() &&
1931                     cursor.par()->isLineSeparator(cursor.pos()))
1932                         // newline always after a blank!
1933                         cursorRight(bview);
1934                 cursor.row()->fill(-1);        // to force a new break
1935         }
1936
1937         // the display inset stuff
1938         if (cursor.row()->par()->isInset(cursor.row()->pos())) {
1939                 Inset * inset = cursor.row()->par()->getInset(cursor.row()->pos());
1940                 if (inset && (inset->display() || inset->needFullRow())) {
1941                         // force a new break
1942                         cursor.row()->fill(-1); // to force a new break
1943                 }
1944         }
1945
1946         // get the cursor row fist
1947         Row * row = cursor.row();
1948         int y = cursor.y() - row->baseline();
1949         if (c != Paragraph::META_INSET) /* Here case LyXText::InsertInset
1950                                          * already insertet the character */
1951                 cursor.par()->insertChar(cursor.pos(), c);
1952         setCharFont(bview->buffer(), cursor.par(), cursor.pos(), rawtmpfont);
1953
1954         if (!jumped_over_space) {
1955                 // refresh the positions
1956                 Row * tmprow = row;
1957                 while (tmprow->next() && tmprow->next()->par() == row->par()) {
1958                         tmprow = tmprow->next();
1959                         tmprow->pos(tmprow->pos() + 1);
1960                 }
1961         }
1962
1963         // Is there a break one row above
1964         if (row->previous() && row->previous()->par() == row->par()
1965             && (cursor.par()->isLineSeparator(cursor.pos())
1966                 || cursor.par()->isNewline(cursor.pos())
1967                 || ((cursor.pos() < cursor.par()->size()) &&
1968                     cursor.par()->isInset(cursor.pos()+1))
1969                 || cursor.row()->fill() == -1))
1970         {
1971                 pos_type z = nextBreakPoint(bview,
1972                                                            row->previous(),
1973                                                            workWidth(bview));
1974                 if (z >= row->pos()) {
1975                         row->pos(z + 1);
1976
1977                         // set the dimensions of the row above
1978                         row->previous()->fill(fill(bview,
1979                                                    row->previous(),
1980                                                    workWidth(bview)));
1981
1982                         setHeightOfRow(bview, row->previous());
1983
1984                         y -= row->previous()->height();
1985                         refresh_y = y;
1986                         refresh_row = row->previous();
1987                         status(bview, LyXText::NEED_MORE_REFRESH);
1988
1989                         breakAgainOneRow(bview, row);
1990
1991                         current_font = rawtmpfont;
1992                         real_current_font = realtmpfont;
1993                         setCursor(bview, cursor.par(), cursor.pos() + 1,
1994                                   false, cursor.boundary());
1995                         // cursor MUST be in row now.
1996
1997                         if (row->next() && row->next()->par() == row->par())
1998                                 need_break_row = row->next();
1999                         else
2000                                 need_break_row = 0;
2001
2002                         // check, wether the last characters font has changed.
2003                         if (cursor.pos() && cursor.pos() == cursor.par()->size()
2004                             && rawparfont != rawtmpfont)
2005                                 redoHeightOfParagraph(bview, cursor);
2006
2007                         charInserted();
2008                         return;
2009                 }
2010         }
2011
2012         // recalculate the fill of the row
2013         if (row->fill() >= 0)  /* needed because a newline
2014                                 * will set fill to -1. Otherwise
2015                                 * we would not get a rebreak! */
2016                 row->fill(fill(bview, row, workWidth(bview)));
2017         if (c == Paragraph::META_INSET || row->fill() < 0) {
2018                 refresh_y = y;
2019                 refresh_row = row;
2020                 refresh_x = cursor.x();
2021                 refresh_pos = cursor.pos();
2022                 status(bview, LyXText::NEED_MORE_REFRESH);
2023                 breakAgainOneRow(bview, row);
2024                 // will the cursor be in another row now?
2025                 if (rowLast(row) <= cursor.pos() + 1 && row->next()) {
2026                         if (row->next() && row->next()->par() == row->par())
2027                                 // this should always be true
2028                                 row = row->next();
2029                         breakAgainOneRow(bview, row);
2030                 }
2031                 current_font = rawtmpfont;
2032                 real_current_font = realtmpfont;
2033
2034                 setCursor(bview, cursor.par(), cursor.pos() + 1, false,
2035                           cursor.boundary());
2036                 if (isBoundary(bview->buffer(), cursor.par(), cursor.pos())
2037                     != cursor.boundary())
2038                         setCursor(bview, cursor.par(), cursor.pos(), false,
2039                           !cursor.boundary());
2040                 if (row->next() && row->next()->par() == row->par())
2041                         need_break_row = row->next();
2042                 else
2043                         need_break_row = 0;
2044         } else {
2045                 refresh_y = y;
2046                 refresh_x = cursor.x();
2047                 refresh_row = row;
2048                 refresh_pos = cursor.pos();
2049
2050                 int const tmpheight = row->height();
2051                 setHeightOfRow(bview, row);
2052                 if (tmpheight == row->height())
2053                         status(bview, LyXText::NEED_VERY_LITTLE_REFRESH);
2054                 else
2055                         status(bview, LyXText::NEED_MORE_REFRESH);
2056
2057                 current_font = rawtmpfont;
2058                 real_current_font = realtmpfont;
2059                 setCursor(bview, cursor.par(), cursor.pos() + 1, false,
2060                           cursor.boundary());
2061         }
2062
2063         // check, wether the last characters font has changed.
2064         if (cursor.pos() && cursor.pos() == cursor.par()->size()
2065             && rawparfont != rawtmpfont) {
2066                 redoHeightOfParagraph(bview, cursor);
2067         } else {
2068                 // now the special right address boxes
2069                 if (textclasslist[bview->buffer()->params.textclass][cursor.par()->layout()].margintype
2070                     == MARGIN_RIGHT_ADDRESS_BOX) {
2071                         redoDrawingOfParagraph(bview, cursor);
2072                 }
2073         }
2074
2075         charInserted();
2076 }
2077
2078
2079 void LyXText::charInserted()
2080 {
2081         // Here we could call FinishUndo for every 20 characters inserted.
2082         // This is from my experience how emacs does it.
2083         static unsigned int counter;
2084         if (counter < 20) {
2085                 ++counter;
2086         } else {
2087                 finishUndo();
2088                 counter = 0;
2089         }
2090 }
2091
2092
2093 void LyXText::prepareToPrint(BufferView * bview,
2094                              Row * row, float & x,
2095                              float & fill_separator,
2096                              float & fill_hfill,
2097                              float & fill_label_hfill,
2098                              bool bidi) const
2099 {
2100         float nlh;
2101         float ns;
2102
2103         float w = row->fill();
2104         fill_hfill = 0;
2105         fill_label_hfill = 0;
2106         fill_separator = 0;
2107         fill_label_hfill = 0;
2108
2109         bool const is_rtl =
2110                 row->par()->isRightToLeftPar(bview->buffer()->params);
2111         if (is_rtl) {
2112                 x = (workWidth(bview) > 0)
2113                         ? rightMargin(bview->buffer(), row) : 0;
2114         } else
2115                 x = (workWidth(bview) > 0)
2116                         ? leftMargin(bview, row) : 0;
2117
2118         // is there a manual margin with a manual label
2119         LyXTextClass const & tclass = textclasslist[bview->buffer()->params.textclass];
2120         LyXLayout const & layout = tclass[row->par()->layout()];
2121
2122         if (layout.margintype == MARGIN_MANUAL
2123             && layout.labeltype == LABEL_MANUAL) {
2124                 // one more since labels are left aligned
2125                 nlh = numberOfLabelHfills(bview->buffer(), row) + 1;
2126                 if (nlh && !row->par()->getLabelWidthString().empty()) {
2127                         fill_label_hfill = labelFill(bview, row) / nlh;
2128                 }
2129         }
2130
2131         // are there any hfills in the row?
2132         float const nh = numberOfHfills(bview->buffer(), row);
2133
2134         if (nh) {
2135                 if (w > 0)
2136                         fill_hfill = w / nh;
2137         // we don't have to look at the alignment if it is ALIGN_LEFT and
2138         // if the row is already larger then the permitted width as then
2139         // we force the LEFT_ALIGN'edness!
2140         } else if (static_cast<int>(row->width()) < workWidth(bview)) {
2141                 // is it block, flushleft or flushright?
2142                 // set x how you need it
2143                 int align;
2144                 if (row->par()->params().align() == LYX_ALIGN_LAYOUT) {
2145                         align = layout.align;
2146                 } else {
2147                         align = row->par()->params().align();
2148                 }
2149
2150                 // center displayed insets
2151                 Inset * inset;
2152                 if (row->par()->isInset(row->pos())
2153                     && (inset=row->par()->getInset(row->pos()))
2154                     && (inset->display())) // || (inset->scroll() < 0)))
2155                     align = (inset->lyxCode() == Inset::MATHMACRO_CODE)
2156                         ? LYX_ALIGN_BLOCK : LYX_ALIGN_CENTER;
2157                 // ERT insets should always be LEFT ALIGNED on screen
2158                 inset = row->par()->inInset();
2159                 if (inset && inset->owner() &&
2160                         inset->owner()->lyxCode() == Inset::ERT_CODE)
2161                 {
2162                         align = LYX_ALIGN_LEFT;
2163                 }
2164
2165                 switch (align) {
2166             case LYX_ALIGN_BLOCK:
2167                         ns = numberOfSeparators(bview->buffer(), row);
2168                         if (ns && row->next() && row->next()->par() == row->par() &&
2169                             !(row->next()->par()->isNewline(row->next()->pos() - 1))
2170                             && !(row->next()->par()->isInset(row->next()->pos())
2171                                  && row->next()->par()->getInset(row->next()->pos())
2172                                  && row->next()->par()->getInset(row->next()->pos())->display())
2173                                 )
2174                         {
2175                                 fill_separator = w / ns;
2176                         } else if (is_rtl) {
2177                                 x += w;
2178                         }
2179                         break;
2180             case LYX_ALIGN_RIGHT:
2181                         x += w;
2182                         break;
2183             case LYX_ALIGN_CENTER:
2184                         x += w / 2;
2185                         break;
2186                 }
2187         }
2188         if (!bidi)
2189                 return;
2190
2191         computeBidiTables(bview->buffer(), row);
2192         if (is_rtl) {
2193                 pos_type main_body =
2194                         beginningOfMainBody(bview->buffer(), row->par());
2195                 pos_type last = rowLast(row);
2196
2197                 if (main_body > 0 &&
2198                     (main_body - 1 > last ||
2199                      !row->par()->isLineSeparator(main_body - 1))) {
2200                         x += lyxfont::width(layout.labelsep,
2201                                             getLabelFont(bview->buffer(), row->par()));
2202                         if (main_body - 1 <= last)
2203                                 x += fill_label_hfill;
2204                 }
2205         }
2206 }
2207
2208 /* important for the screen */
2209
2210
2211 /* the cursor set functions have a special mechanism. When they
2212 * realize, that you left an empty paragraph, they will delete it.
2213 * They also delete the corresponding row */
2214
2215 void LyXText::cursorRightOneWord(BufferView * bview) const
2216 {
2217         // treat floats, HFills and Insets as words
2218         LyXCursor tmpcursor = cursor;
2219         // CHECK See comment on top of text.C
2220
2221         if (tmpcursor.pos() == tmpcursor.par()->size()
2222             && tmpcursor.par()->next()) {
2223                         tmpcursor.par(tmpcursor.par()->next());
2224                         tmpcursor.pos(0);
2225         } else {
2226                 int steps = 0;
2227
2228                 // Skip through initial nonword stuff.
2229                 while (tmpcursor.pos() < tmpcursor.par()->size() &&
2230                        ! tmpcursor.par()->isWord(tmpcursor.pos())) {
2231                   //    printf("Current pos1 %d", tmpcursor.pos()) ;
2232                         tmpcursor.pos(tmpcursor.pos() + 1);
2233                         ++steps;
2234                 }
2235                 // Advance through word.
2236                 while (tmpcursor.pos() < tmpcursor.par()->size() &&
2237                         tmpcursor.par()->isWord(tmpcursor.pos())) {
2238                   //     printf("Current pos2 %d", tmpcursor.pos()) ;
2239                         tmpcursor.pos(tmpcursor.pos() + 1);
2240                         ++steps;
2241                 }
2242         }
2243         setCursor(bview, tmpcursor.par(), tmpcursor.pos());
2244 }
2245
2246
2247 void LyXText::cursorTab(BufferView * bview) const
2248 {
2249     LyXCursor tmpcursor = cursor;
2250     while (tmpcursor.pos() < tmpcursor.par()->size()
2251            && !tmpcursor.par()->isNewline(tmpcursor.pos()))
2252         tmpcursor.pos(tmpcursor.pos() + 1);
2253
2254     if (tmpcursor.pos() == tmpcursor.par()->size()) {
2255         if (tmpcursor.par()->next()) {
2256             tmpcursor.par(tmpcursor.par()->next());
2257             tmpcursor.pos(0);
2258         }
2259     } else
2260         tmpcursor.pos(tmpcursor.pos() + 1);
2261     setCursor(bview, tmpcursor.par(), tmpcursor.pos());
2262 }
2263
2264
2265 /* -------> Skip initial whitespace at end of word and move cursor to *start*
2266             of prior word, not to end of next prior word. */
2267
2268 void LyXText::cursorLeftOneWord(BufferView * bview)  const
2269 {
2270         LyXCursor tmpcursor = cursor;
2271         cursorLeftOneWord(tmpcursor);
2272         setCursor(bview, tmpcursor.par(), tmpcursor.pos());
2273 }
2274
2275 void LyXText::cursorLeftOneWord(LyXCursor  & cur)  const
2276 {
2277         // treat HFills, floats and Insets as words
2278         cur = cursor;
2279         while (cur.pos()
2280                && (cur.par()->isSeparator(cur.pos() - 1)
2281                    || cur.par()->isKomma(cur.pos() - 1))
2282                && !(cur.par()->isHfill(cur.pos() - 1)
2283                     || cur.par()->isInset(cur.pos() - 1)))
2284                 cur.pos(cur.pos() - 1);
2285
2286         if (cur.pos()
2287             && (cur.par()->isInset(cur.pos() - 1)
2288                 || cur.par()->isHfill(cur.pos() - 1))) {
2289                 cur.pos(cur.pos() - 1);
2290         } else if (!cur.pos()) {
2291                 if (cur.par()->previous()) {
2292                         cur.par(cur.par()->previous());
2293                         cur.pos(cur.par()->size());
2294                 }
2295         } else {                // Here, cur != 0
2296                 while (cur.pos() > 0 &&
2297                        cur.par()->isWord(cur.pos()-1))
2298                         cur.pos(cur.pos() - 1);
2299         }
2300 }
2301
2302 /* -------> Select current word. This depends on behaviour of
2303 CursorLeftOneWord(), so it is patched as well. */
2304 void LyXText::getWord(LyXCursor & from, LyXCursor & to,
2305                       word_location const loc) const
2306 {
2307         // first put the cursor where we wana start to select the word
2308         from = cursor;
2309         switch (loc) {
2310         case WHOLE_WORD_STRICT:
2311                 if (cursor.pos() == 0 || cursor.pos() == cursor.par()->size()
2312                     || cursor.par()->isSeparator(cursor.pos())
2313                     || cursor.par()->isKomma(cursor.pos())
2314                     || cursor.par()->isSeparator(cursor.pos() -1)
2315                     || cursor.par()->isKomma(cursor.pos() -1)) {
2316                         to = from;
2317                         return;
2318                 }
2319                 // no break here, we go to the next
2320
2321         case WHOLE_WORD:
2322                 // Move cursor to the beginning, when not already there.
2323                 if (from.pos() && !from.par()->isSeparator(from.pos() - 1)
2324                     && !from.par()->isKomma(from.pos() - 1))
2325                         cursorLeftOneWord(from);
2326                 break;
2327         case PREVIOUS_WORD:
2328                 // always move the cursor to the beginning of previous word
2329                 cursorLeftOneWord(from);
2330                 break;
2331         case NEXT_WORD:
2332                 lyxerr << "LyXText::getWord: NEXT_WORD not implemented yet\n";
2333                 break;
2334         case PARTIAL_WORD:
2335                 break;
2336         }
2337         to = from;
2338         while (to.pos() < to.par()->size()
2339                && !to.par()->isSeparator(to.pos())
2340                && !to.par()->isKomma(to.pos())
2341                && !to.par()->isHfill(to.pos()))
2342         {
2343                 to.pos(to.pos() + 1);
2344         }
2345 }
2346
2347
2348 void LyXText::selectWord(BufferView * bview, word_location const loc)
2349 {
2350         LyXCursor from;
2351         LyXCursor to;
2352         getWord(from, to, loc);
2353         if (cursor != from)
2354                 setCursor(bview, from.par(), from.pos());
2355         if (to == from)
2356                 return;
2357         selection.cursor = cursor;
2358         setCursor(bview, to.par(), to.pos());
2359         setSelection(bview);
2360 }
2361
2362
2363 /* -------> Select the word currently under the cursor when no
2364         selection is currently set */
2365 bool LyXText::selectWordWhenUnderCursor(BufferView * bview,
2366                                         word_location const loc)
2367 {
2368         if (!selection.set()) {
2369                 selectWord(bview, loc);
2370                 return selection.set();
2371         }
2372         return false;
2373 }
2374
2375
2376 // This function is only used by the spellchecker for NextWord().
2377 // It doesn't handle LYX_ACCENTs and probably never will.
2378 string const LyXText::selectNextWordToSpellcheck(BufferView * bview,
2379                                                  float & value) const
2380 {
2381         if (the_locking_inset) {
2382                 string str = the_locking_inset->selectNextWordToSpellcheck(bview, value);
2383                 if (!str.empty()) {
2384                         value += float(cursor.y())/float(height);
2385                         return str;
2386                 }
2387                 // we have to go on checking so move cusor to the next char
2388                 if (cursor.pos() == cursor.par()->size()) {
2389                         if (!cursor.par()->next())
2390                                 return str;
2391                         cursor.par(cursor.par()->next());
2392                         cursor.pos(0);
2393                 } else
2394                         cursor.pos(cursor.pos() + 1);
2395         }
2396         Paragraph * tmppar = cursor.par();
2397
2398         // If this is not the very first word, skip rest of
2399         // current word because we are probably in the middle
2400         // of a word if there is text here.
2401         if (cursor.pos() || cursor.par()->previous()) {
2402                 while (cursor.pos() < cursor.par()->size()
2403                        && cursor.par()->isLetter(cursor.pos()))
2404                         cursor.pos(cursor.pos() + 1);
2405         }
2406
2407         // Now, skip until we have real text (will jump paragraphs)
2408         while ((cursor.par()->size() > cursor.pos()
2409                && (!cursor.par()->isLetter(cursor.pos()))
2410                && (!cursor.par()->isInset(cursor.pos()) ||
2411                            !cursor.par()->getInset(cursor.pos())->allowSpellcheck()))
2412                || (cursor.par()->size() == cursor.pos()
2413                    && cursor.par()->next()))
2414         {
2415                 if (cursor.pos() == cursor.par()->size()) {
2416                         cursor.par(cursor.par()->next());
2417                         cursor.pos(0);
2418                 } else
2419                         cursor.pos(cursor.pos() + 1);
2420         }
2421
2422         // now check if we hit an inset so it has to be a inset containing text!
2423         if (cursor.pos() < cursor.par()->size() &&
2424             cursor.par()->isInset(cursor.pos()))
2425         {
2426                 // lock the inset!
2427                 cursor.par()->getInset(cursor.pos())->edit(bview);
2428                 // now call us again to do the above trick
2429                 // but obviously we have to start from down below ;)
2430                 return bview->text->selectNextWordToSpellcheck(bview, value);
2431         }
2432
2433         // Update the value if we changed paragraphs
2434         if (cursor.par() != tmppar) {
2435                 setCursor(bview, cursor.par(), cursor.pos());
2436                 value = float(cursor.y())/float(height);
2437         }
2438
2439         // Start the selection from here
2440         selection.cursor = cursor;
2441
2442         // and find the end of the word (insets like optional hyphens
2443         // and ligature break are part of a word)
2444         while (cursor.pos() < cursor.par()->size()
2445                && (cursor.par()->isLetter(cursor.pos())))
2446                 cursor.pos(cursor.pos() + 1);
2447
2448         // Finally, we copy the word to a string and return it
2449         string str;
2450         if (selection.cursor.pos() < cursor.pos()) {
2451                 pos_type i;
2452                 for (i = selection.cursor.pos(); i < cursor.pos(); ++i) {
2453                         if (!cursor.par()->isInset(i))
2454                                 str += cursor.par()->getChar(i);
2455                 }
2456         }
2457         return str;
2458 }
2459
2460
2461 // This one is also only for the spellchecker
2462 void LyXText::selectSelectedWord(BufferView * bview)
2463 {
2464         if (the_locking_inset) {
2465                 the_locking_inset->selectSelectedWord(bview);
2466                 return;
2467         }
2468         // move cursor to the beginning
2469         setCursor(bview, selection.cursor.par(), selection.cursor.pos());
2470
2471         // set the sel cursor
2472         selection.cursor = cursor;
2473
2474         // now find the end of the word
2475         while (cursor.pos() < cursor.par()->size()
2476                && (cursor.par()->isLetter(cursor.pos())))
2477                 cursor.pos(cursor.pos() + 1);
2478
2479         setCursor(bview, cursor.par(), cursor.pos());
2480
2481         // finally set the selection
2482         setSelection(bview);
2483 }
2484
2485
2486 /* -------> Delete from cursor up to the end of the current or next word. */
2487 void LyXText::deleteWordForward(BufferView * bview)
2488 {
2489         if (!cursor.par()->size())
2490                 cursorRight(bview);
2491         else {
2492                 LyXCursor tmpcursor = cursor;
2493                 tmpcursor.row(0); // ??
2494                 selection.set(true); // to avoid deletion
2495                 cursorRightOneWord(bview);
2496                 setCursor(bview, tmpcursor, tmpcursor.par(), tmpcursor.pos());
2497                 selection.cursor = cursor;
2498                 cursor = tmpcursor;
2499                 setSelection(bview);
2500
2501                 /* -----> Great, CutSelection() gets rid of multiple spaces. */
2502                 cutSelection(bview, true, false);
2503         }
2504 }
2505
2506
2507 /* -------> Delete from cursor to start of current or prior word. */
2508 void LyXText::deleteWordBackward(BufferView * bview)
2509 {
2510        if (!cursor.par()->size())
2511                cursorLeft(bview);
2512        else {
2513                LyXCursor tmpcursor = cursor;
2514                tmpcursor.row(0); // ??
2515                selection.set(true); // to avoid deletion
2516                cursorLeftOneWord(bview);
2517                setCursor(bview, tmpcursor, tmpcursor.par(), tmpcursor.pos());
2518                selection.cursor = cursor;
2519                cursor = tmpcursor;
2520                setSelection(bview);
2521                cutSelection(bview, true, false);
2522        }
2523 }
2524
2525
2526 /* -------> Kill to end of line. */
2527 void LyXText::deleteLineForward(BufferView * bview)
2528 {
2529         if (!cursor.par()->size())
2530                 // Paragraph is empty, so we just go to the right
2531                 cursorRight(bview);
2532         else {
2533                 LyXCursor tmpcursor = cursor;
2534                 // We can't store the row over a regular setCursor
2535                 // so we set it to 0 and reset it afterwards.
2536                 tmpcursor.row(0); // ??
2537                 selection.set(true); // to avoid deletion
2538                 cursorEnd(bview);
2539                 setCursor(bview, tmpcursor, tmpcursor.par(), tmpcursor.pos());
2540                 selection.cursor = cursor;
2541                 cursor = tmpcursor;
2542                 setSelection(bview);
2543                 // What is this test for ??? (JMarc)
2544                 if (!selection.set()) {
2545                         deleteWordForward(bview);
2546                 } else {
2547                         cutSelection(bview, true, false);
2548                 }
2549         }
2550 }
2551
2552
2553 // Change the case of a word at cursor position.
2554 // This function directly manipulates Paragraph::text because there
2555 // is no Paragraph::SetChar currently. I did what I could to ensure
2556 // that it is correct. I guess part of it should be moved to
2557 // Paragraph, but it will have to change for 1.1 anyway. At least
2558 // it does not access outside of the allocated array as the older
2559 // version did. (JMarc)
2560 void LyXText::changeCase(BufferView * bview, LyXText::TextCase action)
2561 {
2562         LyXCursor from;
2563         LyXCursor to;
2564
2565         if (selection.set()) {
2566                 from = selection.start;
2567                 to = selection.end;
2568         } else {
2569                 getWord(from, to, PARTIAL_WORD);
2570                 setCursor(bview, to.par(), to.pos() + 1);
2571         }
2572
2573         changeRegionCase(bview, from, to, action);
2574 }
2575
2576
2577 void LyXText::changeRegionCase(BufferView * bview,
2578                                LyXCursor const & from,
2579                                LyXCursor const & to,
2580                                LyXText::TextCase action)
2581 {
2582         lyx::Assert(from <= to);
2583
2584         setUndo(bview, Undo::FINISH, from.par(), to.par()->next());
2585
2586         pos_type pos = from.pos();
2587         Paragraph * par = from.par();
2588
2589         while (par && (pos != to.pos() || par != to.par())) {
2590                 unsigned char c = par->getChar(pos);
2591                 if (!IsInsetChar(c) && !IsHfillChar(c)) {
2592                         switch (action) {
2593                         case text_lowercase:
2594                                 c = lowercase(c);
2595                                 break;
2596                         case text_capitalization:
2597                                 c = uppercase(c);
2598                                 action = text_lowercase;
2599                                 break;
2600                         case text_uppercase:
2601                                 c = uppercase(c);
2602                                 break;
2603                         }
2604                 }
2605                 par->setChar(pos, c);
2606                 checkParagraph(bview, par, pos);
2607
2608                 ++pos;
2609                 if (pos == par->size()) {
2610                         par = par->next();
2611                         pos = 0;
2612                 }
2613         }
2614         if (to.row() != from.row()) {
2615                 refresh_y = from.y() - from.row()->baseline();
2616                 refresh_row = from.row();
2617                 status(bview, LyXText::NEED_MORE_REFRESH);
2618         }
2619 }
2620
2621
2622 void LyXText::transposeChars(BufferView & bview)
2623 {
2624         Paragraph * tmppar = cursor.par();
2625
2626         setUndo(&bview, Undo::FINISH, tmppar, tmppar->next());
2627
2628         pos_type tmppos = cursor.pos();
2629
2630         // First decide if it is possible to transpose at all
2631
2632         // We are at the beginning of a paragraph.
2633         if (tmppos == 0) return;
2634
2635         // We are at the end of a paragraph.
2636         if (tmppos == tmppar->size() - 1) return;
2637
2638         unsigned char c1 = tmppar->getChar(tmppos);
2639         unsigned char c2 = tmppar->getChar(tmppos - 1);
2640
2641         if (c1 != Paragraph::META_INSET
2642             && c2 != Paragraph::META_INSET) {
2643                 tmppar->setChar(tmppos, c2);
2644                 tmppar->setChar(tmppos - 1, c1);
2645         }
2646         // We should have an implementation that handles insets
2647         // as well, but that will have to come later. (Lgb)
2648         checkParagraph(const_cast<BufferView*>(&bview), tmppar, tmppos);
2649 }
2650
2651
2652 void LyXText::Delete(BufferView * bview)
2653 {
2654         // this is a very easy implementation
2655
2656         LyXCursor old_cursor = cursor;
2657         int const old_cur_par_id = old_cursor.par()->id();
2658         int const old_cur_par_prev_id = old_cursor.par()->previous() ?
2659                 old_cursor.par()->previous()->id() : 0;
2660
2661         // just move to the right
2662         cursorRight(bview);
2663
2664         // CHECK Look at the comment here.
2665         // This check is not very good...
2666         // The cursorRightIntern calls DeleteEmptyParagrapgMechanism
2667         // and that can very well delete the par or par->previous in
2668         // old_cursor. Will a solution where we compare paragraph id's
2669         //work better?
2670         if ((cursor.par()->previous() ? cursor.par()->previous()->id() : 0)
2671             == old_cur_par_prev_id
2672             && cursor.par()->id() != old_cur_par_id) {
2673                 // delete-empty-paragraph-mechanism has done it
2674                 return;
2675         }
2676
2677         // if you had success make a backspace
2678         if (old_cursor.par() != cursor.par() || old_cursor.pos() != cursor.pos()) {
2679                 LyXCursor tmpcursor = cursor;
2680                 // to make sure undo gets the right cursor position
2681                 cursor = old_cursor;
2682                 setUndo(bview, Undo::DELETE,
2683                         cursor.par(), cursor.par()->next());
2684                 cursor = tmpcursor;
2685                 backspace(bview);
2686         }
2687 }
2688
2689
2690 void LyXText::backspace(BufferView * bview)
2691 {
2692         // Get the font that is used to calculate the baselineskip
2693         pos_type lastpos = cursor.par()->size();
2694         LyXFont rawparfont =
2695                 cursor.par()->getFontSettings(bview->buffer()->params,
2696                                               lastpos - 1);
2697
2698         if (cursor.pos() == 0) {
2699                 // The cursor is at the beginning of a paragraph,
2700                 // so the the backspace will collapse two paragraphs into one.
2701
2702                 // we may paste some paragraphs
2703
2704                 // is it an empty paragraph?
2705
2706                 if ((lastpos == 0
2707                      || (lastpos == 1 && cursor.par()->isSeparator(0)))) {
2708                         // This is an empty paragraph and we delete it just by moving the cursor one step
2709                         // left and let the DeleteEmptyParagraphMechanism handle the actual deletion
2710                         // of the paragraph.
2711
2712                         if (cursor.par()->previous()) {
2713                                 Paragraph * tmppar = cursor.par()->previous();
2714                                 if (cursor.par()->layout() == tmppar->layout()
2715                                     && cursor.par()->getAlign() == tmppar->getAlign()) {
2716                                         // Inherit bottom DTD from the paragraph below.
2717                                         // (the one we are deleting)
2718                                         tmppar->params().lineBottom(cursor.par()->params().lineBottom());
2719                                         tmppar->params().spaceBottom(cursor.par()->params().spaceBottom());
2720                                         tmppar->params().pagebreakBottom(cursor.par()->params().pagebreakBottom());
2721                                 }
2722
2723                                 cursorLeft(bview);
2724
2725                                 // the layout things can change the height of a row !
2726                                 int const tmpheight = cursor.row()->height();
2727                                 setHeightOfRow(bview, cursor.row());
2728                                 if (cursor.row()->height() != tmpheight) {
2729                                         refresh_y = cursor.y() - cursor.row()->baseline();
2730                                         refresh_row = cursor.row();
2731                                         status(bview, LyXText::NEED_MORE_REFRESH);
2732                                 }
2733                                 return;
2734                         }
2735                 }
2736
2737                 if (cursor.par()->previous()) {
2738                         setUndo(bview, Undo::DELETE,
2739                                 cursor.par()->previous(), cursor.par()->next());
2740                 }
2741
2742                 Paragraph * tmppar = cursor.par();
2743                 Row * tmprow = cursor.row();
2744
2745                 // We used to do cursorLeftIntern() here, but it is
2746                 // not a good idea since it triggers the auto-delete
2747                 // mechanism. So we do a cursorLeftIntern()-lite,
2748                 // without the dreaded mechanism. (JMarc)
2749                 if (cursor.par()->previous()) {
2750                         // steps into the above paragraph.
2751                         setCursorIntern(bview, cursor.par()->previous(),
2752                                         cursor.par()->previous()->size(),
2753                                         false);
2754                 }
2755
2756                 /* Pasting is not allowed, if the paragraphs have different
2757                    layout. I think it is a real bug of all other
2758                    word processors to allow it. It confuses the user.
2759                    Even so with a footnote paragraph and a non-footnote
2760                    paragraph. I will not allow pasting in this case,
2761                    because the user would be confused if the footnote behaves
2762                    different wether it is open or closed.
2763
2764                    Correction: Pasting is always allowed with standard-layout
2765                 */
2766                 LyXTextClass const & tclass = textclasslist[bview->buffer()->params.textclass];
2767
2768                 if (cursor.par() != tmppar
2769                     && (cursor.par()->layout() == tmppar->layout()
2770                         || tmppar->layout() == tclass.defaultLayoutName())
2771                     && cursor.par()->getAlign() == tmppar->getAlign()) {
2772                         removeParagraph(tmprow);
2773                         removeRow(tmprow);
2774                         cursor.par()->pasteParagraph(bview->buffer()->params);
2775
2776                         if (!cursor.pos() || !cursor.par()->isSeparator(cursor.pos() - 1))
2777                                 ; //cursor.par()->insertChar(cursor.pos(), ' ');
2778                         // strangely enough it seems that commenting out the line above removes
2779                         // most or all of the segfaults. I will however also try to move the
2780                         // two Remove... lines in front of the PasteParagraph too.
2781                         else
2782                                 if (cursor.pos())
2783                                         cursor.pos(cursor.pos() - 1);
2784
2785                         status(bview, LyXText::NEED_MORE_REFRESH);
2786                         refresh_row = cursor.row();
2787                         refresh_y = cursor.y() - cursor.row()->baseline();
2788
2789                         // remove the lost paragraph
2790                         // This one is not safe, since the paragraph that the tmprow and the
2791                         // following rows belong to has been deleted by the PasteParagraph
2792                         // above. The question is... could this be moved in front of the
2793                         // PasteParagraph?
2794                         //RemoveParagraph(tmprow);
2795                         //RemoveRow(tmprow);
2796
2797                         // This rebuilds the rows.
2798                         appendParagraph(bview, cursor.row());
2799                         updateCounters(bview, cursor.row());
2800
2801                         // the row may have changed, block, hfills etc.
2802                         setCursor(bview, cursor.par(), cursor.pos(), false);
2803                 }
2804         } else {
2805                 /* this is the code for a normal backspace, not pasting
2806                  * any paragraphs */
2807                 setUndo(bview, Undo::DELETE,
2808                         cursor.par(), cursor.par()->next());
2809                 // We used to do cursorLeftIntern() here, but it is
2810                 // not a good idea since it triggers the auto-delete
2811                 // mechanism. So we do a cursorLeftIntern()-lite,
2812                 // without the dreaded mechanism. (JMarc)
2813                 setCursorIntern(bview, cursor.par(), cursor.pos()- 1,
2814                                 false, cursor.boundary());
2815
2816                 // some insets are undeletable here
2817                 if (cursor.par()->isInset(cursor.pos())) {
2818                         if (!cursor.par()->getInset(cursor.pos())->deletable())
2819                                 return;
2820                         // force complete redo when erasing display insets
2821                         // this is a cruel method but safe..... Matthias
2822                         if (cursor.par()->getInset(cursor.pos())->display() ||
2823                             cursor.par()->getInset(cursor.pos())->needFullRow()) {
2824                                 cursor.par()->erase(cursor.pos());
2825                                 redoParagraph(bview);
2826                                 return;
2827                         }
2828                 }
2829
2830                 Row * row = cursor.row();
2831                 int y = cursor.y() - row->baseline();
2832                 pos_type z;
2833                 /* remember that a space at the end of a row doesnt count
2834                  * when calculating the fill */
2835                 if (cursor.pos() < rowLast(row) ||
2836                     !cursor.par()->isLineSeparator(cursor.pos())) {
2837                         row->fill(row->fill() + singleWidth(bview,
2838                                                             cursor.par(),
2839                                                             cursor.pos()));
2840                 }
2841
2842                 /* some special code when deleting a newline. This is similar
2843                  * to the behavior when pasting paragraphs */
2844                 if (cursor.pos() && cursor.par()->isNewline(cursor.pos())) {
2845                         cursor.par()->erase(cursor.pos());
2846                         // refresh the positions
2847                         Row * tmprow = row;
2848                         while (tmprow->next() && tmprow->next()->par() == row->par()) {
2849                                 tmprow = tmprow->next();
2850                                 tmprow->pos(tmprow->pos() - 1);
2851                         }
2852                         if (cursor.par()->isLineSeparator(cursor.pos() - 1))
2853                                 cursor.pos(cursor.pos() - 1);
2854
2855                         if (cursor.pos() < cursor.par()->size()
2856                             && !cursor.par()->isSeparator(cursor.pos())) {
2857                                 cursor.par()->insertChar(cursor.pos(), ' ');
2858                                 setCharFont(bview->buffer(), cursor.par(),
2859                                             cursor.pos(), current_font);
2860                                 // refresh the positions
2861                                 tmprow = row;
2862                                 while (tmprow->next() && tmprow->next()->par() == row->par()) {
2863                                         tmprow = tmprow->next();
2864                                         tmprow->pos(tmprow->pos() + 1);
2865                                 }
2866                         }
2867                 } else {
2868                         cursor.par()->erase(cursor.pos());
2869
2870                         // refresh the positions
2871                         Row * tmprow = row;
2872                         while (tmprow->next()
2873                                && tmprow->next()->par() == row->par()) {
2874                                 tmprow = tmprow->next();
2875                                 tmprow->pos(tmprow->pos() - 1);
2876                         }
2877
2878                         // delete newlines at the beginning of paragraphs
2879                         while (cursor.par()->size() &&
2880                                cursor.par()->isNewline(cursor.pos()) &&
2881                                cursor.pos() == beginningOfMainBody(bview->buffer(),
2882                                                                    cursor.par())) {
2883                                 cursor.par()->erase(cursor.pos());
2884                                 // refresh the positions
2885                                 tmprow = row;
2886                                 while (tmprow->next() &&
2887                                        tmprow->next()->par() == row->par()) {
2888                                         tmprow = tmprow->next();
2889                                         tmprow->pos(tmprow->pos() - 1);
2890                                 }
2891                         }
2892                 }
2893
2894                 // is there a break one row above
2895                 if (row->previous() && row->previous()->par() == row->par()) {
2896                         z = nextBreakPoint(bview, row->previous(),
2897                                            workWidth(bview));
2898                         if (z >= row->pos()) {
2899                                 row->pos(z + 1);
2900
2901                                 Row * tmprow = row->previous();
2902
2903                                 // maybe the current row is now empty
2904                                 if (row->pos() >= row->par()->size()) {
2905                                         // remove it
2906                                         removeRow(row);
2907                                         need_break_row = 0;
2908                                 } else {
2909                                         breakAgainOneRow(bview, row);
2910                                         if (row->next() && row->next()->par() == row->par())
2911                                                 need_break_row = row->next();
2912                                         else
2913                                                 need_break_row = 0;
2914                                 }
2915
2916                                 // set the dimensions of the row above
2917                                 y -= tmprow->height();
2918                                 tmprow->fill(fill(bview, tmprow,
2919                                                   workWidth(bview)));
2920                                 setHeightOfRow(bview, tmprow);
2921
2922                                 refresh_y = y;
2923                                 refresh_row = tmprow;
2924                                 status(bview, LyXText::NEED_MORE_REFRESH);
2925                                 setCursor(bview, cursor.par(), cursor.pos(),
2926                                           false, cursor.boundary());
2927                                 //current_font = rawtmpfont;
2928                                 //real_current_font = realtmpfont;
2929                                 // check, whether the last character's font has changed.
2930                                 if (rawparfont !=
2931                                     cursor.par()->getFontSettings(bview->buffer()->params,
2932                                                                   cursor.par()->size() - 1))
2933                                         redoHeightOfParagraph(bview, cursor);
2934                                 return;
2935                         }
2936                 }
2937
2938                 // break the cursor row again
2939                 if (row->next() && row->next()->par() == row->par() &&
2940                     (rowLast(row) == row->par()->size() - 1 ||
2941                      nextBreakPoint(bview, row, workWidth(bview)) != rowLast(row))) {
2942
2943                         /* it can happen that a paragraph loses one row
2944                          * without a real breakup. This is when a word
2945                          * is to long to be broken. Well, I don t care this
2946                          * hack ;-) */
2947                         if (rowLast(row) == row->par()->size() - 1)
2948                                 removeRow(row->next());
2949
2950                         refresh_y = y;
2951                         refresh_row = row;
2952                         status(bview, LyXText::NEED_MORE_REFRESH);
2953
2954                         breakAgainOneRow(bview, row);
2955                         // will the cursor be in another row now?
2956                         if (row->next() && row->next()->par() == row->par() &&
2957                             rowLast(row) <= cursor.pos()) {
2958                                 row = row->next();
2959                                 breakAgainOneRow(bview, row);
2960                         }
2961
2962                         setCursor(bview, cursor.par(), cursor.pos(), false, cursor.boundary());
2963
2964                         if (row->next() && row->next()->par() == row->par())
2965                                 need_break_row = row->next();
2966                         else
2967                                 need_break_row = 0;
2968                 } else  {
2969                         // set the dimensions of the row
2970                         row->fill(fill(bview, row, workWidth(bview)));
2971                         int const tmpheight = row->height();
2972                         setHeightOfRow(bview, row);
2973                         if (tmpheight == row->height())
2974                                 status(bview, LyXText::NEED_VERY_LITTLE_REFRESH);
2975                         else
2976                                 status(bview, LyXText::NEED_MORE_REFRESH);
2977                         refresh_y = y;
2978                         refresh_row = row;
2979                         setCursor(bview, cursor.par(), cursor.pos(), false, cursor.boundary());
2980                 }
2981         }
2982
2983         // current_font = rawtmpfont;
2984         // real_current_font = realtmpfont;
2985
2986         if (isBoundary(bview->buffer(), cursor.par(), cursor.pos())
2987             != cursor.boundary())
2988                 setCursor(bview, cursor.par(), cursor.pos(), false,
2989                           !cursor.boundary());
2990
2991         lastpos = cursor.par()->size();
2992         if (cursor.pos() == lastpos)
2993                 setCurrentFont(bview);
2994
2995         // check, whether the last characters font has changed.
2996         if (rawparfont !=
2997             cursor.par()->getFontSettings(bview->buffer()->params, lastpos - 1)) {
2998                 redoHeightOfParagraph(bview, cursor);
2999         } else {
3000                 // now the special right address boxes
3001                 if (textclasslist
3002                     [bview->buffer()->params.textclass]
3003                     [cursor.par()->layout()].margintype == MARGIN_RIGHT_ADDRESS_BOX) {
3004                         redoDrawingOfParagraph(bview, cursor);
3005                 }
3006         }
3007 }
3008
3009
3010 bool LyXText::paintRowBackground(DrawRowParams & p)
3011 {
3012         bool clear_area = true;
3013         Inset * inset = 0;
3014         LyXFont font(LyXFont::ALL_SANE);
3015
3016         pos_type const last = rowLastPrintable(p.row);
3017
3018         if (!p.bv->screen()->forceClear() && last == p.row->pos()
3019                 && p.row->par()->isInset(p.row->pos())) {
3020                 inset = p.row->par()->getInset(p.row->pos());
3021                 if (inset) {
3022                         clear_area = inset->doClearArea();
3023                 }
3024         }
3025
3026         if (p.cleared) {
3027                 return true;
3028         }
3029
3030         if (clear_area) {
3031                 int const x = p.xo;
3032                 int const y = p.yo < 0 ? 0 : p.yo;
3033                 int const h = p.yo < 0 ? p.row->height() + p.yo : p.row->height();
3034                 p.pain->fillRectangle(x, y, p.width, h, backgroundColor());
3035                 return true;
3036         }
3037
3038         if (inset == 0)
3039                 return false;
3040
3041         int h = p.row->baseline() - inset->ascent(p.bv, font);
3042
3043         // first clear the whole row above the inset!
3044         if (h > 0) {
3045                 p.pain->fillRectangle(p.xo, p.yo, p.width, h, backgroundColor());
3046         }
3047
3048         // clear the space below the inset!
3049         h += inset->ascent(p.bv, font) + inset->descent(p.bv, font);
3050         if ((p.row->height() - h) > 0) {
3051                 p.pain->fillRectangle(p.xo, p.yo + h,
3052                         p.width, p.row->height() - h, backgroundColor());
3053         }
3054
3055         // clear the space behind the inset, if needed
3056         if (!inset->display() && !inset->needFullRow()) {
3057                 int const xp = int(p.x) + inset->width(p.bv, font);
3058                 if (p.width - xp > 0) {
3059                         p.pain->fillRectangle(xp, p.yo, p.width - xp,
3060                                 p.row->height(), backgroundColor());
3061                 }
3062         }
3063
3064         return false;
3065 }
3066
3067
3068 void LyXText::paintRowSelection(DrawRowParams & p)
3069 {
3070         bool const is_rtl = p.row->par()->isRightToLeftPar(p.bv->buffer()->params);
3071
3072         // the current selection
3073         int const startx = selection.start.x();
3074         int const endx = selection.end.x();
3075         int const starty = selection.start.y();
3076         int const endy = selection.end.y();
3077         Row const * startrow = selection.start.row();
3078         Row const * endrow = selection.end.row();
3079
3080         Row * row = p.row;
3081
3082         if (bidi_same_direction) {
3083                 int x;
3084                 int y = p.yo;
3085                 int w;
3086                 int h = row->height();
3087
3088                 if (startrow == row && endrow == row) {
3089                         if (startx < endx) {
3090                                 x = p.xo + startx;
3091                                 w = endx - startx;
3092                                 p.pain->fillRectangle(x, y, w, h, LColor::selection);
3093                         } else {
3094                                 x = p.xo + endx;
3095                                 w = startx - endx;
3096                                 p.pain->fillRectangle(x, y, w, h, LColor::selection);
3097                         }
3098                 } else if (startrow == row) {
3099                         int const x = (is_rtl) ? p.xo : (p.xo + startx);
3100                         int const w = (is_rtl) ? startx : (p.width - startx);
3101                         p.pain->fillRectangle(x, y, w, h, LColor::selection);
3102                 } else if (endrow == row) {
3103                         int const x = (is_rtl) ? (p.xo + endx) : p.xo;
3104                         int const w = (is_rtl) ? (p.width - endx) : endx;
3105                         p.pain->fillRectangle(x, y, w, h, LColor::selection);
3106                 } else if (p.y > starty && p.y < endy) {
3107                         p.pain->fillRectangle(p.xo, y, p.width, h, LColor::selection);
3108                 }
3109                 return;
3110         } else if (startrow != row && endrow != row) {
3111                 int w = p.width;
3112                 int h = row->height();
3113                 if (p.y > starty && p.y < endy) {
3114                         p.pain->fillRectangle(p.xo, p.yo, w, h, LColor::selection);
3115                 }
3116                 return;
3117         }
3118
3119         if (!((startrow != row && !is_rtl) || (endrow != row && is_rtl))) {
3120                 return;
3121         }
3122
3123         float tmpx = p.x;
3124
3125         p.pain->fillRectangle(p.xo, p.yo, int(p.x), row->height(), LColor::selection);
3126
3127         Buffer const * buffer = p.bv->buffer();
3128         Paragraph * par = row->par();
3129         pos_type main_body = beginningOfMainBody(buffer, par);
3130         pos_type const last = rowLastPrintable(row);
3131
3132         for (pos_type vpos = row->pos(); vpos <= last; ++vpos)  {
3133                 pos_type pos = vis2log(vpos);
3134                 float const old_tmpx = tmpx;
3135                 if (main_body > 0 && pos == main_body - 1) {
3136                         LyXLayout const & layout =
3137                                 textclasslist
3138                                 [buffer->params.textclass]
3139                                 [par->layout()];
3140                         LyXFont const lfont = getLabelFont(buffer, par);
3141
3142
3143                         tmpx += p.label_hfill + lyxfont::width(layout.labelsep, lfont);
3144
3145                         if (par->isLineSeparator(main_body - 1))
3146                                 tmpx -= singleWidth(p.bv, par, main_body - 1);
3147                 }
3148
3149                 if (hfillExpansion(buffer, row, pos)) {
3150                         tmpx += singleWidth(p.bv, par, pos);
3151                         if (pos >= main_body)
3152                                 tmpx += p.hfill;
3153                         else
3154                                 tmpx += p.label_hfill;
3155                 }
3156
3157                 else if (par->isSeparator(pos)) {
3158                         tmpx += singleWidth(p.bv, par, pos);
3159                         if (pos >= main_body)
3160                                 tmpx += p.separator;
3161                 } else {
3162                         tmpx += singleWidth(p.bv, par, pos);
3163                 }
3164
3165                 if ((startrow != row || selection.start.pos() <= pos) &&
3166                         (endrow != row || pos < selection.end.pos())) {
3167                         // Here we do not use p.x as p.xo was added to p.x.
3168                         p.pain->fillRectangle(int(old_tmpx), p.yo,
3169                                 int(tmpx - old_tmpx + 1),
3170                                 row->height(), LColor::selection);
3171                 }
3172
3173                 if ((startrow != row && is_rtl) || (endrow != row && !is_rtl)) {
3174                         p.pain->fillRectangle(p.xo + int(tmpx),
3175                                 p.yo, int(p.bv->workWidth() - tmpx),
3176                                 row->height(), LColor::selection);
3177                 }
3178         }
3179 }
3180
3181
3182 void LyXText::paintRowAppendix(DrawRowParams & p)
3183 {
3184         // FIXME: can be just p.width ?
3185         int const ww = p.bv->workWidth();
3186         Paragraph * firstpar = p.row->par();
3187
3188         if (firstpar->params().appendix()) {
3189                 p.pain->line(1, p.yo, 1, p.yo + p.row->height(), LColor::appendixline);
3190                 p.pain->line(ww - 2, p.yo, ww - 2, p.yo + p.row->height(), LColor::appendixline);
3191         }
3192 }
3193
3194
3195 void LyXText::paintRowDepthBar(DrawRowParams & p)
3196 {
3197         Paragraph::depth_type const depth = p.row->par()->getDepth();
3198
3199         if (depth <= 0)
3200                 return;
3201
3202         Paragraph::depth_type prev_depth = 0;
3203         if (p.row->previous())
3204                 prev_depth = p.row->previous()->par()->getDepth();
3205         Paragraph::depth_type next_depth = 0;
3206         if (p.row->next())
3207                 next_depth = p.row->next()->par()->getDepth();
3208
3209         for (Paragraph::depth_type i = 1; i <= depth; ++i) {
3210                 int const x = (LYX_PAPER_MARGIN / 5) * i + p.xo;
3211                 int const h = p.yo + p.row->height() - 1 - (i - next_depth - 1) * 3;
3212
3213                 p.pain->line(x, p.yo, x, h, LColor::depthbar);
3214
3215                 int const w = LYX_PAPER_MARGIN / 5;
3216
3217                 if (i > prev_depth) {
3218                         p.pain->fillRectangle(x, p.yo, w, 2, LColor::depthbar);
3219                 }
3220                 if (i > next_depth) {
3221                         p.pain->fillRectangle(x, h, w, 2, LColor::depthbar);
3222                 }
3223         }
3224 }
3225
3226
3227 int LyXText::getLengthMarkerHeight(BufferView * bv, VSpace const & vsp) const
3228 {
3229         int const arrow_size = 4;
3230         int const space_size = int(vsp.inPixels(bv));
3231
3232         if (vsp.kind() != VSpace::LENGTH) {
3233                 return space_size;
3234         }
3235
3236         LyXFont font;
3237         font.decSize();
3238         int const min_size = max(3 * arrow_size,
3239                                       lyxfont::maxAscent(font)
3240                                       + lyxfont::maxDescent(font));
3241
3242         if (vsp.length().len().value() < 0.0)
3243                 return min_size;
3244         else
3245                 return max(min_size, space_size);
3246 }
3247
3248
3249 int LyXText::drawLengthMarker(DrawRowParams & p, string const & prefix,
3250                               VSpace const & vsp, int start)
3251 {
3252         int const arrow_size = 4;
3253         int const size = getLengthMarkerHeight(p.bv, vsp);
3254         int const end = start + size;
3255
3256         // the label to display (if any)
3257         string str;
3258         // y-values for top arrow
3259         int ty1, ty2;
3260         // y-values for bottom arrow
3261         int by1, by2;
3262         switch (vsp.kind()) {
3263         case VSpace::LENGTH:
3264         {
3265                 str = prefix + " (" + vsp.asLyXCommand() + ")";
3266                 // adding or removing space
3267                 bool const added = !(vsp.length().len().value() < 0.0);
3268                 ty1 = added ? (start + arrow_size) : start;
3269                 ty2 = added ? start : (start + arrow_size);
3270                 by1 = added ? (end - arrow_size) : end;
3271                 by2 = added ? end : (end - arrow_size);
3272                 break;
3273         }
3274         case VSpace:: VFILL:
3275                 str = prefix + " (vertical fill)";
3276                 ty1 = ty2 = start;
3277                 by1 = by2 = end;
3278                 break;
3279         default:
3280                 // nothing to draw here
3281                 return size;
3282         }
3283
3284         int const leftx = p.xo + leftMargin(p.bv, p.row);
3285         int const midx = leftx + arrow_size;
3286         int const rightx = midx + arrow_size;
3287
3288         // first the string
3289         int w = 0;
3290         int a = 0;
3291         int d = 0;
3292
3293         LyXFont font;
3294         font.setColor(LColor::added_space).decSize();
3295         lyxfont::rectText(str, font, w, a, d);
3296
3297         p.pain->rectText(leftx + 2 * arrow_size + 5,
3298                          start + ((end - start) / 2) + d,
3299                          str, font,
3300                          backgroundColor(),
3301                          backgroundColor());
3302
3303         // top arrow
3304         p.pain->line(leftx, ty1, midx, ty2, LColor::added_space);
3305         p.pain->line(midx, ty2, rightx, ty1, LColor::added_space);
3306
3307         // bottom arrow
3308         p.pain->line(leftx, by1, midx, by2, LColor::added_space);
3309         p.pain->line(midx, by2, rightx, by1, LColor::added_space);
3310
3311         // joining line
3312         p.pain->line(midx, ty2, midx, by2, LColor::added_space);
3313
3314         return size;
3315 }
3316
3317
3318 void LyXText::paintFirstRow(DrawRowParams & p)
3319 {
3320         Paragraph * par = p.row->par();
3321         ParagraphParameters const & parparams = par->params();
3322
3323         // start of appendix?
3324         if (parparams.startOfAppendix()) {
3325                 p.pain->line(1, p.yo, p.width - 2, p.yo, LColor::appendixline);
3326         }
3327
3328         int y_top = 0;
3329
3330         // think about the margins
3331         if (!p.row->previous() && bv_owner)
3332                 y_top += LYX_PAPER_MARGIN;
3333
3334         // draw a top pagebreak
3335         if (parparams.pagebreakTop()) {
3336                 int const y = p.yo + y_top + 2*defaultHeight();
3337                 p.pain->line(p.xo, y, p.xo + p.width, y,
3338                         LColor::pagebreak, Painter::line_onoffdash);
3339
3340                 int w = 0;
3341                 int a = 0;
3342                 int d = 0;
3343
3344                 LyXFont pb_font;
3345                 pb_font.setColor(LColor::pagebreak).decSize();
3346                 lyxfont::rectText(_("Page Break (top)"), pb_font, w, a, d);
3347                 p.pain->rectText((p.width - w)/2, y + d,
3348                               _("Page Break (top)"), pb_font,
3349                               backgroundColor(),
3350                               backgroundColor());
3351                 y_top += 3 * defaultHeight();
3352         }
3353
3354         // draw the additional space if needed:
3355         y_top += drawLengthMarker(p, _("Space above"),
3356                                   parparams.spaceTop(), p.yo + y_top);
3357
3358         Buffer const * buffer = p.bv->buffer();
3359
3360         LyXTextClass const & tclass = textclasslist[buffer->params.textclass];
3361         LyXLayout const & layout = tclass[par->layout()];
3362
3363         // think about the parskip
3364         // some parskips VERY EASY IMPLEMENTATION
3365         if (buffer->params.paragraph_separation == BufferParams::PARSEP_SKIP) {
3366                 if (par->previous()) {
3367                         if (layout.latextype == LATEX_PARAGRAPH
3368                                 && !par->getDepth()) {
3369                                 y_top += buffer->params.getDefSkip().inPixels(p.bv);
3370                         } else {
3371                                 LyXLayout const & playout =
3372                                         tclass[par->previous()->layout()];
3373                                 if (playout.latextype == LATEX_PARAGRAPH
3374                                         && !par->previous()->getDepth()) {
3375                                         // is it right to use defskip here, too? (AS)
3376                                         y_top += buffer->params.getDefSkip().inPixels(p.bv);
3377                                 }
3378                         }
3379                 }
3380         }
3381
3382         int const ww = p.bv->workWidth();
3383
3384         // draw a top line
3385         if (parparams.lineTop()) {
3386                 LyXFont font(LyXFont::ALL_SANE);
3387                 int const asc = lyxfont::ascent('x', getFont(buffer, par, 0));
3388
3389                 y_top += asc;
3390
3391                 int const w = (inset_owner ?  inset_owner->width(p.bv, font) : ww);
3392                 int const xp = static_cast<int>(inset_owner ? p.xo : 0);
3393                 p.pain->line(xp, p.yo + y_top, xp + w, p.yo + y_top,
3394                         LColor::topline, Painter::line_solid,
3395                         Painter::line_thick);
3396
3397                 y_top += asc;
3398         }
3399
3400         bool const is_rtl = p.row->par()->isRightToLeftPar(p.bv->buffer()->params);
3401
3402         // should we print a label?
3403         if (layout.labeltype >= LABEL_STATIC
3404             && (layout.labeltype != LABEL_STATIC
3405                 || layout.latextype != LATEX_ENVIRONMENT
3406                 || par->isFirstInSequence())) {
3407
3408                 LyXFont font = getLabelFont(buffer, par);
3409                 if (!par->getLabelstring().empty()) {
3410                         float x = p.x;
3411                         string const str = par->getLabelstring();
3412
3413                         // this is special code for the chapter layout. This is
3414                         // printed in an extra row and has a pagebreak at
3415                         // the top.
3416                         if (layout.labeltype == LABEL_COUNTER_CHAPTER) {
3417                                 if (buffer->params.secnumdepth >= 0) {
3418                                         float spacing_val = 1.0;
3419                                         if (!parparams.spacing().isDefault()) {
3420                                                 spacing_val = parparams.spacing().getValue();
3421                                         } else {
3422                                                 spacing_val = buffer->params.spacing.getValue();
3423                                         }
3424
3425                                         int const maxdesc =
3426                                                 int(lyxfont::maxDescent(font) * layout.spacing.getValue() * spacing_val)
3427                                                 + int(layout.parsep) * defaultHeight();
3428
3429                                         if (is_rtl) {
3430                                                 x = ww - leftMargin(p.bv, p.row) -
3431                                                         lyxfont::width(str, font);
3432                                         }
3433
3434                                         p.pain->text(int(x),
3435                                                 p.yo + p.row->baseline() -
3436                                                 p.row->ascent_of_text() - maxdesc,
3437                                                 str, font);
3438                                 }
3439                         } else {
3440                                 if (is_rtl) {
3441                                         x = ww - leftMargin(p.bv, p.row)
3442                                                 + lyxfont::width(layout.labelsep, font);
3443                                 } else {
3444                                         x = p.x - lyxfont::width(layout.labelsep, font)
3445                                                 - lyxfont::width(str, font);
3446                                 }
3447
3448                                 p.pain->text(int(x), p.yo + p.row->baseline(), str, font);
3449                         }
3450                 }
3451         // the labels at the top of an environment.
3452         // More or less for bibliography
3453         } else if (par->isFirstInSequence() &&
3454                 (layout.labeltype == LABEL_TOP_ENVIRONMENT ||
3455                 layout.labeltype == LABEL_BIBLIO ||
3456                 layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)) {
3457                 LyXFont font = getLabelFont(buffer, par);
3458                 if (!par->getLabelstring().empty()) {
3459                         string const str = par->getLabelstring();
3460                         float spacing_val = 1.0;
3461                         if (!parparams.spacing().isDefault()) {
3462                                 spacing_val = parparams.spacing().getValue();
3463                         } else {
3464                                 spacing_val = buffer->params.spacing.getValue();
3465                         }
3466
3467                         int maxdesc =
3468                                 int(lyxfont::maxDescent(font) * layout.spacing.getValue() * spacing_val
3469                                 + (layout.labelbottomsep * defaultHeight()));
3470
3471                         float x = p.x;
3472                         if (layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT) {
3473                                 x = ((is_rtl ? leftMargin(p.bv, p.row) : p.x)
3474                                          + ww - rightMargin(buffer, p.row)) / 2;
3475                                 x -= lyxfont::width(str, font) / 2;
3476                         } else if (is_rtl) {
3477                                 x = ww - leftMargin(p.bv, p.row) -
3478                                         lyxfont::width(str, font);
3479                         }
3480                         p.pain->text(int(x), p.yo + p.row->baseline()
3481                                   - p.row->ascent_of_text() - maxdesc,
3482                                   str, font);
3483                 }
3484         }
3485
3486         if (layout.labeltype == LABEL_BIBLIO && par->bibkey) {
3487                 LyXFont font = getLayoutFont(buffer, par);
3488                 float x;
3489                 if (is_rtl) {
3490                         x = ww - leftMargin(p.bv, p.row)
3491                                 + lyxfont::width(layout.labelsep, font);
3492                 } else {
3493                         x = p.x - lyxfont::width(layout.labelsep, font)
3494                                 - par->bibkey->width(p.bv, font);
3495                 }
3496                 par->bibkey->draw(p.bv, font, p.yo + p.row->baseline(), x, p.cleared);
3497         }
3498 }
3499
3500
3501 void LyXText::paintLastRow(DrawRowParams & p)
3502 {
3503         Paragraph * par = p.row->par();
3504         ParagraphParameters const & parparams = par->params();
3505         int y_bottom = p.row->height() - 1;
3506
3507         // think about the margins
3508         if (!p.row->next() && bv_owner)
3509                 y_bottom -= LYX_PAPER_MARGIN;
3510
3511         int const ww = p.bv->workWidth();
3512
3513         // draw a bottom pagebreak
3514         if (parparams.pagebreakBottom()) {
3515                 LyXFont pb_font;
3516                 pb_font.setColor(LColor::pagebreak).decSize();
3517                 int const y = p.yo + y_bottom - 2 * defaultHeight();
3518
3519                 p.pain->line(p.xo, y, p.xo + p.width, y, LColor::pagebreak,
3520                              Painter::line_onoffdash);
3521
3522                 int w = 0;
3523                 int a = 0;
3524                 int d = 0;
3525                 lyxfont::rectText(_("Page Break (bottom)"), pb_font, w, a, d);
3526                 p.pain->rectText((ww - w) / 2, y + d,
3527                         _("Page Break (bottom)"),
3528                         pb_font, backgroundColor(), backgroundColor());
3529
3530                 y_bottom -= 3 * defaultHeight();
3531         }
3532
3533         // draw the additional space if needed:
3534         int const height =  getLengthMarkerHeight(p.bv,
3535                                                   parparams.spaceBottom());
3536         y_bottom -= drawLengthMarker(p, _("Space below"),
3537                                      parparams.spaceBottom(),
3538                                      p.yo + y_bottom - height);
3539
3540         Buffer const * buffer = p.bv->buffer();
3541
3542         // draw a bottom line
3543         if (parparams.lineBottom()) {
3544                 LyXFont font(LyXFont::ALL_SANE);
3545                 int const asc = lyxfont::ascent('x',
3546                         getFont(buffer, par,
3547                         max(pos_type(0), par->size() - 1)));
3548
3549                 y_bottom -= asc;
3550
3551                 int const w = (inset_owner ?  inset_owner->width(p.bv, font) : ww);
3552                 int const xp = static_cast<int>(inset_owner ? p.xo : 0);
3553                 int const y = p.yo + y_bottom;
3554                 p.pain->line(xp, y, xp + w, y, LColor::topline, Painter::line_solid,
3555                           Painter::line_thick);
3556
3557                 y_bottom -= asc;
3558         }
3559
3560         bool const is_rtl = p.row->par()->isRightToLeftPar(p.bv->buffer()->params);
3561         int const endlabel = par->getEndLabel(buffer->params);
3562
3563         // draw an endlabel
3564         switch (endlabel) {
3565         case END_LABEL_BOX:
3566         case END_LABEL_FILLED_BOX:
3567         {
3568                 LyXFont const font = getLabelFont(buffer, par);
3569                 int const size = int(0.75 * lyxfont::maxAscent(font));
3570                 int const y = (p.yo + p.row->baseline()) - size;
3571                 int x = is_rtl ? LYX_PAPER_MARGIN : ww - LYX_PAPER_MARGIN - size;
3572
3573                 if (p.row->fill() <= size)
3574                         x += (size - p.row->fill() + 1) * (is_rtl ? -1 : 1);
3575
3576                 if (endlabel == END_LABEL_BOX) {
3577                         p.pain->rectangle(x, y, size, size, LColor::eolmarker);
3578                 } else {
3579                         p.pain->fillRectangle(x, y, size, size,
3580                                               LColor::eolmarker);
3581                 }
3582                 break;
3583         }
3584         case END_LABEL_STATIC:
3585         {
3586                 LyXFont font(LyXFont::ALL_SANE);
3587                 string const & layout = par->layout();
3588                 string const str = textclasslist[buffer->params.textclass][layout].endlabelstring();
3589                 font = getLabelFont(buffer, par);
3590                 int const x = is_rtl ?
3591                         int(p.x) - lyxfont::width(str, font)
3592                         : ww - rightMargin(buffer, p.row) - p.row->fill();
3593                 p.pain->text(x, p.yo + p.row->baseline(), str, font);
3594                 break;
3595         }
3596         case END_LABEL_NO_LABEL:
3597                 break;
3598         }
3599 }
3600
3601 void LyXText::paintRowText(DrawRowParams & p)
3602 {
3603         Paragraph * par = p.row->par();
3604         Buffer const * buffer = p.bv->buffer();
3605
3606         pos_type const last = rowLastPrintable(p.row);
3607         pos_type main_body =
3608                 beginningOfMainBody(buffer, par);
3609         if (main_body > 0 &&
3610                 (main_body - 1 > last ||
3611                 !par->isLineSeparator(main_body - 1))) {
3612                 main_body = 0;
3613         }
3614
3615         LyXLayout const & layout =
3616                 textclasslist[buffer->params.textclass][par->layout()];
3617
3618         pos_type vpos = p.row->pos();
3619         while (vpos <= last) {
3620                 if (p.x > p.bv->workWidth())
3621                         break;
3622                 pos_type pos = vis2log(vpos);
3623                 if (p.x + singleWidth(p.bv, par, pos) < 0) {
3624                         p.x += singleWidth(p.bv, par, pos);
3625                         ++vpos;
3626                         continue;
3627                 }
3628                 if (main_body > 0 && pos == main_body - 1) {
3629                         int const lwidth = lyxfont::width(layout.labelsep,
3630                                 getLabelFont(buffer, par));
3631
3632                         p.x += p.label_hfill + lwidth
3633                                 - singleWidth(p.bv, par, main_body - 1);
3634                 }
3635
3636                 if (par->isHfill(pos)) {
3637                         p.x += 1;
3638
3639                         int const y0 = p.yo + p.row->baseline();
3640                         int const y1 = y0 - defaultHeight() / 2;
3641
3642                         p.pain->line(int(p.x), y1, int(p.x), y0,
3643                                      LColor::added_space);
3644
3645                         if (hfillExpansion(buffer, p.row, pos)) {
3646                                 int const y2 = (y0 + y1) / 2;
3647
3648                                 if (pos >= main_body) {
3649                                         p.pain->line(int(p.x), y2,
3650                                                   int(p.x + p.hfill), y2,
3651                                                   LColor::added_space,
3652                                                   Painter::line_onoffdash);
3653                                         p.x += p.hfill;
3654                                 } else {
3655                                         p.pain->line(int(p.x), y2,
3656                                                   int(p.x + p.label_hfill), y2,
3657                                                   LColor::added_space,
3658                                                   Painter::line_onoffdash);
3659                                         p.x += p.label_hfill;
3660                                 }
3661                                 p.pain->line(int(p.x), y1,
3662                                              int(p.x), y0,
3663                                              LColor::added_space);
3664                         }
3665                         p.x += 2;
3666                         ++vpos;
3667                 } else if (par->isSeparator(pos)) {
3668                         p.x += singleWidth(p.bv, par, pos);
3669                         if (pos >= main_body)
3670                                 p.x += p.separator;
3671                         ++vpos;
3672                 } else {
3673                         if (!draw(p, vpos))
3674                                 break;
3675                 }
3676         }
3677 }
3678
3679
3680 void LyXText::getVisibleRow(BufferView * bv, int y_offset, int x_offset,
3681                             Row * row, int y, bool cleared)
3682 {
3683         if (row->height() <= 0) {
3684                 lyxerr << "LYX_ERROR: row.height: "
3685                        << row->height() << endl;
3686                 return;
3687         }
3688
3689         DrawRowParams p;
3690
3691         // set up drawing parameters
3692         p.bv = bv;
3693         p.pain = &bv->painter();
3694         p.row = row;
3695         p.xo = x_offset;
3696         p.yo = y_offset;
3697         prepareToPrint(bv, row, p.x, p.separator, p.hfill, p.label_hfill);
3698         if (inset_owner && (p.x < 0))
3699                 p.x = 0;
3700         p.x += p.xo;
3701         p.y = y;
3702         p.width = inset_owner ? inset_owner->textWidth(bv, true) : bv->workWidth();
3703         p.cleared = cleared;
3704
3705         // start painting
3706
3707         // clear to background if necessary
3708         p.cleared = paintRowBackground(p);
3709
3710         // paint the selection background
3711         if (selection.set()) {
3712                 paintRowSelection(p);
3713         }
3714
3715         // vertical lines for appendix
3716         paintRowAppendix(p);
3717
3718         // environment depth brackets
3719         paintRowDepthBar(p);
3720
3721         // draw any stuff wanted for a first row of a paragraph
3722         if (!row->pos()) {
3723                 paintFirstRow(p);
3724         }
3725
3726         // draw any stuff wanted for the last row of a paragraph
3727         if (!row->next() || (row->next()->par() != row->par())) {
3728                 paintLastRow(p);
3729         }
3730
3731         // paint text
3732         paintRowText(p);
3733 }
3734
3735
3736 int LyXText::defaultHeight() const
3737 {
3738         LyXFont font(LyXFont::ALL_SANE);
3739         return int(lyxfont::maxAscent(font) + lyxfont::maxDescent(font) * 1.5);
3740 }
3741
3742
3743 /* returns the column near the specified x-coordinate of the row
3744 * x is set to the real beginning of this column  */
3745 pos_type
3746 LyXText::getColumnNearX(BufferView * bview, Row * row, int & x,
3747                         bool & boundary) const
3748 {
3749         float tmpx = 0.0;
3750         float fill_separator;
3751         float fill_hfill;
3752         float fill_label_hfill;
3753
3754         prepareToPrint(bview, row, tmpx, fill_separator,
3755                        fill_hfill, fill_label_hfill);
3756
3757         pos_type vc = row->pos();
3758         pos_type last = rowLastPrintable(row);
3759         pos_type c = 0;
3760         LyXLayout const & layout =
3761                 textclasslist[bview->buffer()->params.textclass][
3762                                     row->par()->layout()];
3763         bool left_side = false;
3764
3765         pos_type main_body = beginningOfMainBody(bview->buffer(), row->par());
3766         float last_tmpx = tmpx;
3767
3768         if (main_body > 0 &&
3769             (main_body - 1 > last ||
3770              !row->par()->isLineSeparator(main_body - 1)))
3771                 main_body = 0;
3772
3773         while (vc <= last && tmpx <= x) {
3774                 c = vis2log(vc);
3775                 last_tmpx = tmpx;
3776                 if (main_body > 0 && c == main_body-1) {
3777                         tmpx += fill_label_hfill +
3778                                 lyxfont::width(layout.labelsep,
3779                                                getLabelFont(bview->buffer(), row->par()));
3780                         if (row->par()->isLineSeparator(main_body - 1))
3781                                 tmpx -= singleWidth(bview, row->par(), main_body-1);
3782                 }
3783
3784                 if (hfillExpansion(bview->buffer(), row, c)) {
3785                         x += singleWidth(bview, row->par(), c);
3786                         if (c >= main_body)
3787                                 tmpx += fill_hfill;
3788                         else
3789                                 tmpx += fill_label_hfill;
3790                 }
3791                 else if (row->par()->isSeparator(c)) {
3792                         tmpx += singleWidth(bview, row->par(), c);
3793                         if (c >= main_body)
3794                                 tmpx+= fill_separator;
3795                 } else
3796                         tmpx += singleWidth(bview, row->par(), c);
3797                 ++vc;
3798         }
3799
3800         if ((tmpx + last_tmpx) / 2 > x) {
3801                 tmpx = last_tmpx;
3802                 left_side = true;
3803         }
3804
3805         if (vc > last + 1)  // This shouldn't happen.
3806                 vc = last + 1;
3807
3808         boundary = false;
3809         bool const lastrow = lyxrc.rtl_support // This is not needed, but gives
3810                                          // some speedup if rtl_support=false
3811                 && (!row->next() || row->next()->par() != row->par());
3812         bool const rtl = (lastrow)
3813                 ? row->par()->isRightToLeftPar(bview->buffer()->params)
3814                 : false; // If lastrow is false, we don't need to compute
3815                          // the value of rtl.
3816
3817         if (row->pos() > last)  // Row is empty?
3818                 c = row->pos();
3819         else if (lastrow &&
3820                  ((rtl &&  left_side && vc == row->pos() && x < tmpx - 5) ||
3821                    (!rtl && !left_side && vc == last + 1   && x > tmpx + 5)))
3822                 c = last + 1;
3823         else if (vc == row->pos()) {
3824                 c = vis2log(vc);
3825                 if (bidi_level(c) % 2 == 1)
3826                         ++c;
3827         } else {
3828                 c = vis2log(vc - 1);
3829                 bool const rtl = (bidi_level(c) % 2 == 1);
3830                 if (left_side == rtl) {
3831                         ++c;
3832                         boundary = isBoundary(bview->buffer(), row->par(), c);
3833                 }
3834         }
3835
3836         if (row->pos() <= last && c > last
3837             && row->par()->isNewline(last)) {
3838                 if (bidi_level(last) % 2 == 0)
3839                         tmpx -= singleWidth(bview, row->par(), last);
3840                 else
3841                         tmpx += singleWidth(bview, row->par(), last);
3842                 c = last;
3843         }
3844
3845         c -= row->pos();
3846         x = int(tmpx);
3847         return c;
3848 }
3849
3850
3851 // returns pointer to a specified row
3852 Row * LyXText::getRow(Paragraph * par, pos_type pos, int & y) const
3853 {
3854         if (!firstrow)
3855                 return 0;
3856
3857         Row * tmprow = firstrow;
3858         y = 0;
3859
3860         // find the first row of the specified paragraph
3861         while (tmprow->next() && tmprow->par() != par) {
3862                 y += tmprow->height();
3863                 tmprow = tmprow->next();
3864         }
3865
3866         // now find the wanted row
3867         while (tmprow->pos() < pos
3868                && tmprow->next()
3869                && tmprow->next()->par() == par
3870                && tmprow->next()->pos() <= pos) {
3871                 y += tmprow->height();
3872                 tmprow = tmprow->next();
3873         }
3874
3875         return tmprow;
3876 }
3877
3878
3879 Row * LyXText::getRowNearY(int & y) const
3880 {
3881 #if 1
3882         // If possible we should optimize this method. (Lgb)
3883         Row * tmprow = firstrow;
3884         int tmpy = 0;
3885
3886         while (tmprow->next() && tmpy + tmprow->height() <= y) {
3887                 tmpy += tmprow->height();
3888                 tmprow = tmprow->next();
3889         }
3890
3891         y = tmpy;   // return the real y
3892
3893         //lyxerr << "returned y = " << y << endl;
3894
3895         return tmprow;
3896 #else
3897         // Search from the current cursor position.
3898
3899         Row * tmprow = cursor.row();
3900         int tmpy = cursor.y() - tmprow->baseline();
3901
3902         lyxerr << "cursor.y() = " << tmpy << endl;
3903         lyxerr << "tmprow->height() = " << tmprow->height() << endl;
3904         lyxerr << "tmprow->baseline() = " << tmprow->baseline() << endl;
3905         lyxerr << "first = " << first << endl;
3906         lyxerr << "y = " << y << endl;
3907
3908         if (y < tmpy) {
3909                 lyxerr << "up" << endl;
3910 #if 0
3911                 while (tmprow && tmpy - tmprow->height() >= y) {
3912                         tmpy -= tmprow->height();
3913                         tmprow = tmprow->previous();
3914                 }
3915 #else
3916                 do {
3917                         tmpy -= tmprow->height();
3918                         tmprow = tmprow->previous();
3919                 } while (tmprow && tmpy - tmprow->height() >= y);
3920 #endif
3921         } else if (y > tmpy) {
3922                 lyxerr << "down" << endl;
3923
3924                 while (tmprow->next() && tmpy + tmprow->height() <= y) {
3925                         tmpy += tmprow->height();
3926                         tmprow = tmprow->next();
3927                 }
3928         } else {
3929                 lyxerr << "equal" << endl;
3930         }
3931
3932         y = tmpy; // return the real y
3933
3934         lyxerr << "returned y = " << y << endl;
3935
3936         return tmprow;
3937
3938 #endif
3939 }
3940
3941
3942 int LyXText::getDepth() const
3943 {
3944         return cursor.par()->getDepth();
3945 }