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