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