]> git.lyx.org Git - lyx.git/blob - src/text.C
Back out potentially buggy patch.
[lyx.git] / src / text.C
1 /* This file is part of
2  * ======================================================
3  *
4  *           LyX, The Document Processor
5  *
6  *           Copyright 1995 Matthias Ettrich
7  *           Copyright 1995-2001 The LyX Team.
8  *
9  * ====================================================== */
10
11 #include <config.h>
12
13 #include "lyxtext.h"
14 #include "lyxrow.h"
15 #include "lyxtextclasslist.h"
16 #include "paragraph.h"
17 #include "gettext.h"
18 #include "bufferparams.h"
19 #include "buffer.h"
20 #include "debug.h"
21 #include "lyxrc.h"
22 #include "LyXView.h"
23 #include "Painter.h"
24 #include "tracer.h"
25 #include "font.h"
26 #include "encoding.h"
27 #include "lyxscreen.h"
28 #include "bufferview_funcs.h"
29 #include "BufferView.h"
30 #include "language.h"
31 #include "ParagraphParameters.h"
32 #include "undo_funcs.h"
33 #include "font.h"
34
35 #include "insets/insetbib.h"
36 #include "insets/insettext.h"
37
38 #include "support/textutils.h"
39 #include "support/LAssert.h"
40 #include "support/lstrings.h"
41
42 #include <algorithm>
43
44 using std::max;
45 using std::min;
46 using std::endl;
47 using std::pair;
48 using lyx::pos_type;
49
50 namespace {
51
52 int const LYX_PAPER_MARGIN = 20;
53
54 } // namespace anon
55
56 extern int bibitemMaxWidth(BufferView *, LyXFont const &);
57
58
59 int LyXText::workWidth(BufferView * bview) const
60 {
61         if (inset_owner) {
62                 return inset_owner->textWidth(bview);
63         }
64         return bview->workWidth();
65 }
66
67
68 int LyXText::workWidth(BufferView * bview, Inset * inset) const
69 {
70         Paragraph * par = 0;
71         pos_type pos = -1;
72
73         par = inset->parOwner();
74         if (par)
75                 pos = par->getPositionOfInset(inset);
76
77         if (!par || pos == -1) {
78                 lyxerr << "LyXText::workWidth: something is wrong,"
79                         " fall back to the brute force method" << endl;
80                 Buffer::inset_iterator it = bview->buffer()->inset_iterator_begin();
81                 Buffer::inset_iterator end = bview->buffer()->inset_iterator_end();
82                 for (; it != end; ++it) {
83                         if (*it == inset) {
84                                 par = it.getPar();
85                                 pos = it.getPos();
86                                 break;
87                         }
88                 }
89         }
90
91         if (!par) {
92                 return workWidth(bview);
93         }
94
95         LyXLayout const & layout =
96                 textclasslist[bview->buffer()->params.textclass][par->layout()];
97
98         if (layout.margintype != MARGIN_RIGHT_ADDRESS_BOX) {
99                 // Optimization here: in most cases, the real row is
100                 // not needed, but only the par/pos values. So we just
101                 // construct a dummy row for leftMargin. (JMarc)
102                 Row dummyrow;
103                 dummyrow.par(par);
104                 dummyrow.pos(pos);
105                 return workWidth(bview) - leftMargin(bview, &dummyrow);
106         } else {
107                 int dummy_y;
108                 Row * row = getRow(par, pos, dummy_y);
109                 Row * frow = row;
110                 while (frow->previous() && frow->par() == frow->previous()->par())
111                         frow = frow->previous();
112                 unsigned int maxw = 0;
113                 while (frow->next() && frow->par() == frow->next()->par()) {
114                         if ((frow != row) && (maxw < frow->width()))
115                                 maxw = frow->width();
116                         frow = frow->next();
117                 }
118                 if (maxw)
119                         return maxw;
120         }
121         return workWidth(bview);
122 }
123
124
125 int LyXText::getRealCursorX(BufferView * bview) const
126 {
127         int x = cursor.x();
128         if (the_locking_inset && (the_locking_inset->getLyXText(bview)!=this))
129                 x = the_locking_inset->getLyXText(bview)->getRealCursorX(bview);
130         return x;
131 }
132
133
134 unsigned char LyXText::transformChar(unsigned char c, Paragraph * par,
135                         pos_type pos) const
136 {
137         if (!Encodings::is_arabic(c))
138                 if (lyxrc.font_norm_type == LyXRC::ISO_8859_6_8 && IsDigit(c))
139                         return c + (0xb0 - '0');
140                 else
141                         return c;
142
143         unsigned char const prev_char = pos > 0 ? par->getChar(pos-1) : ' ';
144         unsigned char next_char = ' ';
145
146         for (pos_type i = pos+1; i < par->size(); ++i)
147                 if (!Encodings::IsComposeChar_arabic(par->getChar(i))) {
148                         next_char = par->getChar(i);
149                         break;
150                 }
151
152         if (Encodings::is_arabic(next_char)) {
153                 if (Encodings::is_arabic(prev_char))
154                         return Encodings::TransformChar(c, Encodings::FORM_MEDIAL);
155                 else
156                         return Encodings::TransformChar(c, Encodings::FORM_INITIAL);
157         } else {
158                 if (Encodings::is_arabic(prev_char))
159                         return Encodings::TransformChar(c, Encodings::FORM_FINAL);
160                 else
161                         return Encodings::TransformChar(c, Encodings::FORM_ISOLATED);
162         }
163 }
164
165 // This is the comments that some of the warnings below refers to.
166 // There are some issues in this file and I don't think they are
167 // really related to the FIX_DOUBLE_SPACE patch. I'd rather think that
168 // this is a problem that has been here almost from day one and that a
169 // larger userbase with differenct access patters triggers the bad
170 // behaviour. (segfaults.) What I think happen is: In several places
171 // we store the paragraph in the current cursor and then moves the
172 // cursor. This movement of the cursor will delete paragraph at the
173 // old position if it is now empty. This will make the temporary
174 // pointer to the old cursor paragraph invalid and dangerous to use.
175 // And is some cases this will trigger a segfault. I have marked some
176 // of the cases where this happens with a warning, but I am sure there
177 // are others in this file and in text2.C. There is also a note in
178 // Delete() that you should read. In Delete I store the paragraph->id
179 // instead of a pointer to the paragraph. I am pretty sure this faulty
180 // use of temporary pointers to paragraphs that might have gotten
181 // invalidated (through a cursor movement) before they are used, are
182 // the cause of the strange crashes we get reported often.
183 //
184 // It is very tiresom to change this code, especially when it is as
185 // hard to read as it is. Help to fix all the cases where this is done
186 // would be greately appreciated.
187 //
188 // Lgb
189
190 int LyXText::singleWidth(BufferView * bview, Paragraph * par,
191                          pos_type pos) const
192 {
193         char const c = par->getChar(pos);
194         return singleWidth(bview, par, pos, c);
195 }
196
197
198 int LyXText::singleWidth(BufferView * bview, Paragraph * par,
199                          pos_type pos, char c) const
200 {
201         LyXFont const font = getFont(bview->buffer(), par, pos);
202
203         // The most common case is handled first (Asger)
204         if (IsPrintable(c)) {
205                 if (font.language()->RightToLeft()) {
206                         if (font.language()->lang() == "arabic" &&
207                             (lyxrc.font_norm_type == LyXRC::ISO_8859_6_8 ||
208                              lyxrc.font_norm_type == LyXRC::ISO_10646_1))
209                                 if (Encodings::IsComposeChar_arabic(c))
210                                         return 0;
211                                 else
212                                         c = transformChar(c, par, pos);
213                         else if (font.language()->lang() == "hebrew" &&
214                                  Encodings::IsComposeChar_hebrew(c))
215                                 return 0;
216                 }
217                 return lyxfont::width(c, font);
218
219         } else if (IsHfillChar(c)) {
220                 return 3;       /* Because of the representation
221                                  * as vertical lines */
222         } else if (c == Paragraph::META_INSET) {
223                 Inset * tmpinset = par->getInset(pos);
224                 if (tmpinset) {
225 #if 1
226                         // this IS needed otherwise on initialitation we don't get the fill
227                         // of the row right (ONLY on initialization if we read a file!)
228                         // should be changed! (Jug 20011204)
229                         tmpinset->update(bview, font);
230 #endif
231                         return tmpinset->width(bview, font);
232                 } else
233                         return 0;
234
235         } else if (IsSeparatorChar(c))
236                 c = ' ';
237         else if (IsNewlineChar(c))
238                 c = 'n';
239         return lyxfont::width(c, font);
240 }
241
242
243 // Returns the paragraph position of the last character in the specified row
244 pos_type LyXText::rowLast(Row const * row) const
245 {
246         if (!row->next() || row->next()->par() != row->par()) {
247                 return row->par()->size() - 1;
248         } else {
249                 return row->next()->pos() - 1;
250         }
251 }
252
253
254 pos_type LyXText::rowLastPrintable(Row const * row) const
255 {
256         pos_type const last = rowLast(row);
257         bool ignore_the_space_on_the_last_position = true;
258         Inset * ins;
259         // we have to consider a space on the last position in this case!
260         if (row->next() && row->par() == row->next()->par() &&
261             row->next()->par()->getChar(last+1) == Paragraph::META_INSET &&
262             (ins=row->next()->par()->getInset(last+1)) &&
263             (ins->needFullRow() || ins->display()))
264         {
265                 ignore_the_space_on_the_last_position = false;
266         }
267         if (last >= row->pos()
268             && row->next()
269             && row->next()->par() == row->par()
270             && row->par()->isSeparator(last)
271                 && ignore_the_space_on_the_last_position)
272                 return last - 1;
273         else
274                 return last;
275 }
276
277
278 void LyXText::computeBidiTables(Buffer const * buf, Row * row) const
279 {
280         bidi_same_direction = true;
281         if (!lyxrc.rtl_support) {
282                 bidi_start = -1;
283                 return;
284         }
285
286         Inset * inset = row->par()->inInset();
287         if (inset && inset->owner() &&
288             inset->owner()->lyxCode() == Inset::ERT_CODE) {
289                 bidi_start = -1;
290                 return;
291         }
292
293         bidi_start = row->pos();
294         bidi_end = rowLastPrintable(row);
295
296         if (bidi_start > bidi_end) {
297                 bidi_start = -1;
298                 return;
299         }
300
301         if (bidi_end + 2 - bidi_start >
302             static_cast<pos_type>(log2vis_list.size())) {
303                 pos_type new_size =
304                         (bidi_end + 2 - bidi_start < 500) ?
305                         500 : 2 * (bidi_end + 2 - bidi_start);
306                 log2vis_list.resize(new_size);
307                 vis2log_list.resize(new_size);
308                 bidi_levels.resize(new_size);
309         }
310
311         vis2log_list[bidi_end + 1 - bidi_start] = -1;
312         log2vis_list[bidi_end + 1 - bidi_start] = -1;
313
314         pos_type stack[2];
315         bool const rtl_par =
316                 row->par()->isRightToLeftPar(buf->params);
317         int level = 0;
318         bool rtl = false;
319         bool rtl0 = false;
320         pos_type const main_body = beginningOfMainBody(buf, row->par());
321
322         for (pos_type lpos = bidi_start;
323              lpos <= bidi_end; ++lpos) {
324                 bool is_space = row->par()->isLineSeparator(lpos);
325                 pos_type const pos =
326                         (is_space && lpos + 1 <= bidi_end &&
327                          !row->par()->isLineSeparator(lpos + 1) &&
328                          !row->par()->isNewline(lpos + 1))
329                         ? lpos + 1 : lpos;
330                 LyXFont font = row->par()->getFontSettings(buf->params, pos);
331                 if (pos != lpos && 0 < lpos && rtl0 && font.isRightToLeft() &&
332                     font.number() == LyXFont::ON &&
333                     row->par()->getFontSettings(buf->params, lpos - 1).number()
334                     == LyXFont::ON) {
335                         font = row->par()->getFontSettings(buf->params, lpos);
336                         is_space = false;
337                 }
338
339
340                 bool new_rtl = font.isVisibleRightToLeft();
341                 bool new_rtl0 = font.isRightToLeft();
342                 int new_level;
343
344                 if (lpos == main_body - 1
345                     && row->pos() < main_body - 1
346                     && is_space) {
347                         new_level = (rtl_par) ? 1 : 0;
348                         new_rtl = new_rtl0 = rtl_par;
349                 } else if (new_rtl0)
350                         new_level = (new_rtl) ? 1 : 2;
351                 else
352                         new_level = (rtl_par) ? 2 : 0;
353
354                 if (is_space && new_level >= level) {
355                         new_level = level;
356                         new_rtl = rtl;
357                         new_rtl0 = rtl0;
358                 }
359
360                 int new_level2 = new_level;
361
362                 if (level == new_level && rtl0 != new_rtl0) {
363                         --new_level2;
364                         log2vis_list[lpos - bidi_start] = (rtl) ? 1 : -1;
365                 } else if (level < new_level) {
366                         log2vis_list[lpos - bidi_start] =  (rtl) ? -1 : 1;
367                         if (new_level > rtl_par)
368                                 bidi_same_direction = false;
369                 } else
370                         log2vis_list[lpos - bidi_start] = (new_rtl) ? -1 : 1;
371                 rtl = new_rtl;
372                 rtl0 = new_rtl0;
373                 bidi_levels[lpos - bidi_start] = new_level;
374
375                 while (level > new_level2) {
376                         pos_type old_lpos = stack[--level];
377                         int delta = lpos - old_lpos - 1;
378                         if (level % 2)
379                                 delta = -delta;
380                         log2vis_list[lpos - bidi_start] += delta;
381                         log2vis_list[old_lpos - bidi_start] += delta;
382                 }
383                 while (level < new_level)
384                         stack[level++] = lpos;
385         }
386
387         while (level > 0) {
388                 pos_type const old_lpos = stack[--level];
389                 int delta = bidi_end - old_lpos;
390                 if (level % 2)
391                         delta = -delta;
392                 log2vis_list[old_lpos - bidi_start] += delta;
393         }
394
395         pos_type vpos = bidi_start - 1;
396         for (pos_type lpos = bidi_start;
397              lpos <= bidi_end; ++lpos) {
398                 vpos += log2vis_list[lpos - bidi_start];
399                 vis2log_list[vpos - bidi_start] = lpos;
400                 log2vis_list[lpos - bidi_start] = vpos;
401         }
402 }
403
404
405 // This method requires a previous call to ComputeBidiTables()
406 bool LyXText::isBoundary(Buffer const * buf, Paragraph * par,
407                          pos_type pos) const
408 {
409         if (!lyxrc.rtl_support || pos == 0)
410                 return false;
411
412         if (!bidi_InRange(pos - 1)) {
413                 /// This can happen if pos is the first char of a row.
414                 /// Returning false in this case is incorrect!
415                 return false;
416         }
417
418         bool const rtl = bidi_level(pos - 1) % 2;
419         bool const rtl2 = bidi_InRange(pos)
420                 ? bidi_level(pos) % 2
421                 : par->isRightToLeftPar(buf->params);
422         return rtl != rtl2;
423 }
424
425
426 bool LyXText::isBoundary(Buffer const * buf, Paragraph * par,
427                          pos_type pos, LyXFont const & font) const
428 {
429         if (!lyxrc.rtl_support)
430                 return false;    // This is just for speedup
431
432         bool const rtl = font.isVisibleRightToLeft();
433         bool const rtl2 = bidi_InRange(pos)
434                 ? bidi_level(pos) % 2
435                 : par->isRightToLeftPar(buf->params);
436         return rtl != rtl2;
437 }
438
439 void LyXText::drawNewline(DrawRowParams & p, pos_type const pos)
440 {
441         // Draw end-of-line marker
442         LyXFont const font = getFont(p.bv->buffer(), p.row->par(), pos);
443         int const wid = lyxfont::width('n', font);
444         int const asc = lyxfont::maxAscent(font);
445         int const y = p.yo + p.row->baseline();
446         int xp[3];
447         int yp[3];
448
449         yp[0] = int(y - 0.875 * asc * 0.75);
450         yp[1] = int(y - 0.500 * asc * 0.75);
451         yp[2] = int(y - 0.125 * asc * 0.75);
452
453         if (bidi_level(pos) % 2 == 0) {
454                 xp[0] = int(p.x + wid * 0.375);
455                 xp[1] = int(p.x);
456                 xp[2] = int(p.x + wid * 0.375);
457         } else {
458                 xp[0] = int(p.x + wid * 0.625);
459                 xp[1] = int(p.x + wid);
460                 xp[2] = int(p.x + wid * 0.625);
461         }
462
463         p.pain->lines(xp, yp, 3, LColor::eolmarker);
464
465         yp[0] = int(y - 0.500 * asc * 0.75);
466         yp[1] = int(y - 0.500 * asc * 0.75);
467         yp[2] = int(y - asc * 0.75);
468
469         if (bidi_level(pos) % 2 == 0) {
470                 xp[0] = int(p.x);
471                 xp[1] = int(p.x + wid);
472                 xp[2] = int(p.x + wid);
473         } else {
474                 xp[0] = int(p.x + wid);
475                 xp[1] = int(p.x);
476                 xp[2] = int(p.x);
477         }
478
479         p.pain->lines(xp, yp, 3, LColor::eolmarker);
480
481         p.x += wid;
482 }
483
484
485 bool LyXText::drawInset(DrawRowParams & p, pos_type const pos)
486 {
487         Inset * inset = p.row->par()->getInset(pos);
488
489         // FIXME: shouldn't happen
490         if (!inset) {
491                 return true;
492         }
493
494         LyXFont const & font = getFont(p.bv->buffer(), p.row->par(), pos);
495         // we need this here as the row pointer may be illegal
496         // at a later time (Jug20020502)
497         Row * prev = p.row->previous();
498
499         inset->update(p.bv, font, false);
500         inset->draw(p.bv, font, p.yo + p.row->baseline(), p.x, p.cleared);
501
502         if (!need_break_row && !inset_owner
503             && p.bv->text->status() == CHANGED_IN_DRAW) {
504                 if (prev && prev->par() == p.row->par()) {
505                         breakAgainOneRow(p.bv, prev);
506                         if (prev->next() != p.row) {
507                                 // breakAgainOneRow() has removed p.row
508                                 p.row = 0;  // see what this breaks
509                                 need_break_row = prev;
510                         } else {
511                                 need_break_row = p.row;
512                         }
513                 } else if (!prev) {
514                         need_break_row = firstrow;
515                 } else {
516                         need_break_row = prev->next();
517                 }
518                 setCursor(p.bv, cursor.par(), cursor.pos());
519                 return false;
520         }
521         return true;
522 }
523
524
525 void LyXText::drawForeignMark(DrawRowParams & p, float const orig_x, LyXFont const & orig_font)
526 {
527         if (!lyxrc.mark_foreign_language)
528                 return;
529         if (orig_font.language() == latex_language)
530                 return;
531         if (orig_font.language() == p.bv->buffer()->params.language)
532                 return;
533
534         int const y = p.yo + p.row->height() - 1;
535         p.pain->line(int(orig_x), y, int(p.x), y, LColor::language);
536 }
537
538
539 void LyXText::drawHebrewComposeChar(DrawRowParams & p, pos_type & vpos)
540 {
541         pos_type pos = vis2log(vpos);
542
543         string str;
544
545         // first char
546         char c = p.row->par()->getChar(pos);
547         str += c;
548         ++vpos;
549
550         LyXFont const & font = getFont(p.bv->buffer(), p.row->par(), pos);
551         int const width = lyxfont::width(c, font);
552         int dx = 0;
553
554         for (pos_type i = pos-1; i >= 0; --i) {
555                 c = p.row->par()->getChar(i);
556                 if (!Encodings::IsComposeChar_hebrew(c)) {
557                         if (IsPrintableNonspace(c)) {
558                                 int const width2 =
559                                         singleWidth(p.bv, p.row->par(), i, c);
560                                 // dalet / resh
561                                 dx = (c == 'ø' || c == 'ã')
562                                         ? width2 - width
563                                         : (width2 - width) / 2;
564                         }
565                         break;
566                 }
567         }
568
569         // Draw nikud
570         p.pain->text(int(p.x) + dx, p.yo + p.row->baseline(), str, font);
571 }
572
573
574 void LyXText::drawArabicComposeChar(DrawRowParams & p, pos_type & vpos)
575 {
576         pos_type pos = vis2log(vpos);
577         string str;
578
579         // first char
580         char c = p.row->par()->getChar(pos);
581         c = transformChar(c, p.row->par(), pos);
582         str +=c;
583         ++vpos;
584
585         LyXFont const & font = getFont(p.bv->buffer(), p.row->par(), pos);
586         int const width = lyxfont::width(c, font);
587         int dx = 0;
588
589         for (pos_type i = pos-1; i >= 0; --i) {
590                 c = p.row->par()->getChar(i);
591                 if (!Encodings::IsComposeChar_arabic(c)) {
592                         if (IsPrintableNonspace(c)) {
593                                 int const width2 =
594                                         singleWidth(p.bv, p.row->par(), i, c);
595                                 dx = (width2 - width) / 2;
596                         }
597                         break;
598                 }
599         }
600         // Draw nikud
601         p.pain->text(int(p.x) + dx, p.yo + p.row->baseline(), str, font);
602 }
603
604
605 void LyXText::drawChars(DrawRowParams & p, pos_type & vpos,
606                         bool hebrew, bool arabic)
607 {
608         pos_type pos = vis2log(vpos);
609         pos_type const last = rowLastPrintable(p.row);
610         LyXFont const & orig_font = getFont(p.bv->buffer(), p.row->par(), pos);
611
612         // first character
613         string str;
614         str += p.row->par()->getChar(pos);
615         if (arabic) {
616                 unsigned char c = str[0];
617                 str[0] = transformChar(c, p.row->par(), pos);
618         }
619         ++vpos;
620
621         // collect as much similar chars as we can
622         while (vpos <= last && (pos = vis2log(vpos)) >= 0) {
623                 char c = p.row->par()->getChar(pos);
624
625                 if (!IsPrintableNonspace(c))
626                         break;
627
628                 if (arabic && Encodings::IsComposeChar_arabic(c))
629                         break;
630                 if (hebrew && Encodings::IsComposeChar_hebrew(c))
631                         break;
632
633                 if (orig_font != getFont(p.bv->buffer(), p.row->par(), pos))
634                         break;
635
636                 str += c;
637                 ++vpos;
638         }
639
640         // Draw text and set the new x position
641         p.pain->text(int(p.x), p.yo + p.row->baseline(), str, orig_font);
642         p.x += lyxfont::width(str, orig_font);
643 }
644
645
646 bool LyXText::draw(DrawRowParams & p, pos_type & vpos)
647 {
648         pos_type const pos = vis2log(vpos);
649         Paragraph * par = p.row->par();
650
651         LyXFont const & orig_font = getFont(p.bv->buffer(), par, pos);
652
653         float const orig_x = p.x;
654
655         char const c = par->getChar(pos);
656
657         if (IsNewlineChar(c)) {
658                 ++vpos;
659                 drawNewline(p, pos);
660                 return true;
661         } else if (IsInsetChar(c)) {
662                 if (!drawInset(p, pos))
663                         return false;
664                 ++vpos;
665                 drawForeignMark(p, orig_x, orig_font);
666                 return true;
667         }
668
669         // usual characters, no insets
670
671         // special case languages
672         bool const hebrew = (orig_font.language()->lang() == "hebrew");
673         bool const arabic =
674                 orig_font.language()->lang() == "arabic" &&
675                 (lyxrc.font_norm_type == LyXRC::ISO_8859_6_8 ||
676                 lyxrc.font_norm_type == LyXRC::ISO_10646_1);
677
678         // draw as many chars as we can
679         if ((!hebrew && !arabic)
680                 || (hebrew && !Encodings::IsComposeChar_hebrew(c))
681                 || (arabic && !Encodings::IsComposeChar_arabic(c))) {
682                 drawChars(p, vpos, true, false);
683         } else if (hebrew) {
684                 drawHebrewComposeChar(p, vpos);
685         } else if (arabic) {
686                 drawArabicComposeChar(p, vpos);
687         }
688
689         drawForeignMark(p, orig_x, orig_font);
690
691 #ifdef INHERIT_LANGUAGE
692 #ifdef WITH_WARNINGS
693         if ((font.language() == inherit_language) ||
694                 (font.language() == ignore_language))
695                 lyxerr << "No this shouldn't happen!\n";
696 #endif
697 #endif
698         return true;
699 }
700
701
702 // Returns the left beginning of the text.
703 // This information cannot be taken from the layouts-objekt, because in
704 // LaTeX the beginning of the text fits in some cases (for example sections)
705 // exactly the label-width.
706 int LyXText::leftMargin(BufferView * bview, Row const * row) const
707 {
708         Inset * ins;
709         if ((row->par()->getChar(row->pos()) == Paragraph::META_INSET) &&
710                 (ins=row->par()->getInset(row->pos())) &&
711                 (ins->needFullRow() || ins->display()))
712                 return LYX_PAPER_MARGIN;
713
714         LyXTextClass const & tclass =
715                 textclasslist[bview->buffer()->params.textclass];
716         LyXLayout const & layout = tclass[row->par()->layout()];
717
718         string parindent = layout.parindent;
719
720         int x = LYX_PAPER_MARGIN;
721
722         x += lyxfont::signedWidth(tclass.leftmargin(), tclass.defaultfont());
723
724         // this is the way, LyX handles the LaTeX-Environments.
725         // I have had this idea very late, so it seems to be a
726         // later added hack and this is true
727         if (!row->par()->getDepth()) {
728                 if (row->par()->layout() == tclass.defaultLayoutName()) {
729                         // find the previous same level paragraph
730                         if (row->par()->previous()) {
731                                 Paragraph * newpar = row->par()
732                                         ->depthHook(row->par()->getDepth());
733                                 if (newpar &&
734                                     tclass[newpar->layout()].nextnoindent)
735                                         parindent.erase();
736                         }
737                 }
738         } else {
739                 // find the next level paragraph
740
741                 Paragraph * newpar =
742                         row->par()->outerHook();
743
744                 // make a corresponding row. Needed to call LeftMargin()
745
746                 // check wether it is a sufficent paragraph
747                 if (newpar && tclass[newpar->layout()].isEnvironment()) {
748                         Row dummyrow;
749                         dummyrow.par(newpar);
750                         dummyrow.pos(newpar->size());
751                         x = leftMargin(bview, &dummyrow);
752                 } else {
753                         // this is no longer an error, because this function
754                         // is used to clear impossible depths after changing
755                         // a layout. Since there is always a redo,
756                         // LeftMargin() is always called
757                         row->par()->params().depth(0);
758                 }
759
760                 if (newpar && row->par()->layout() == tclass.defaultLayoutName()) {
761                         if (newpar->params().noindent())
762                                 parindent.erase();
763                         else
764                                 parindent = tclass[newpar->layout()].parindent;
765                 }
766         }
767
768         LyXFont const labelfont = getLabelFont(bview->buffer(), row->par());
769         switch (layout.margintype) {
770         case MARGIN_DYNAMIC:
771                 if (!layout.leftmargin.empty()) {
772                         x += lyxfont::signedWidth(layout.leftmargin,
773                                                   tclass.defaultfont());
774                 }
775                 if (!row->par()->getLabelstring().empty()) {
776                         x += lyxfont::signedWidth(layout.labelindent,
777                                                   labelfont);
778                         x += lyxfont::width(row->par()->getLabelstring(),
779                                             labelfont);
780                         x += lyxfont::width(layout.labelsep, labelfont);
781                 }
782                 break;
783         case MARGIN_MANUAL:
784                 x += lyxfont::signedWidth(layout.labelindent, labelfont);
785                 if (row->pos() >= beginningOfMainBody(bview->buffer(), row->par())) {
786                         if (!row->par()->getLabelWidthString().empty()) {
787                                 x += lyxfont::width(row->par()->getLabelWidthString(),
788                                                labelfont);
789                                 x += lyxfont::width(layout.labelsep, labelfont);
790                         }
791                 }
792                 break;
793         case MARGIN_STATIC:
794                 x += lyxfont::signedWidth(layout.leftmargin, tclass.defaultfont()) * 4
795                         / (row->par()->getDepth() + 4);
796                 break;
797         case MARGIN_FIRST_DYNAMIC:
798                 if (layout.labeltype == LABEL_MANUAL) {
799                         if (row->pos() >= beginningOfMainBody(bview->buffer(), row->par())) {
800                                 x += lyxfont::signedWidth(layout.leftmargin,
801                                                           labelfont);
802                         } else {
803                                 x += lyxfont::signedWidth(layout.labelindent,
804                                                           labelfont);
805                         }
806                 } else if (row->pos()
807                            // Special case to fix problems with
808                            // theorems (JMarc)
809                            || (layout.labeltype == LABEL_STATIC
810                                && layout.latextype == LATEX_ENVIRONMENT
811                                && ! row->par()->isFirstInSequence())) {
812                         x += lyxfont::signedWidth(layout.leftmargin,
813                                                   labelfont);
814                 } else if (layout.labeltype != LABEL_TOP_ENVIRONMENT
815                            && layout.labeltype != LABEL_BIBLIO
816                            && layout.labeltype !=
817                            LABEL_CENTERED_TOP_ENVIRONMENT) {
818                         x += lyxfont::signedWidth(layout.labelindent,
819                                                   labelfont);
820                         x += lyxfont::width(layout.labelsep, labelfont);
821                         x += lyxfont::width(row->par()->getLabelstring(),
822                                             labelfont);
823                 }
824                 break;
825
826         case MARGIN_RIGHT_ADDRESS_BOX:
827         {
828                 // ok, a terrible hack. The left margin depends on the widest
829                 // row in this paragraph. Do not care about footnotes, they
830                 // are *NOT* allowed in the LaTeX realisation of this layout.
831
832                 // find the first row of this paragraph
833                 Row const * tmprow = row;
834                 while (tmprow->previous()
835                        && tmprow->previous()->par() == row->par())
836                         tmprow = tmprow->previous();
837
838                 int minfill = tmprow->fill();
839                 while (tmprow->next() && tmprow->next()->par() == row->par()) {
840                         tmprow = tmprow->next();
841                         if (tmprow->fill() < minfill)
842                                 minfill = tmprow->fill();
843                 }
844
845                 x += lyxfont::signedWidth(layout.leftmargin,
846                                           tclass.defaultfont());
847                 x += minfill;
848         }
849         break;
850         }
851
852         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    cursor.par()->breakParagraph(bview->buffer()->params, cursor.pos(),
1759                                 keep_layout);
1760
1761    // well this is the caption hack since one caption is really enough
1762    if (layout.labeltype == LABEL_SENSITIVE) {
1763      if (!cursor.pos())
1764              // set to standard-layout
1765              cursor.par()->applyLayout(tclass.defaultLayoutName());
1766      else
1767              // set to standard-layout
1768              cursor.par()->next()->applyLayout(tclass.defaultLayoutName());
1769    }
1770
1771    /* if the cursor is at the beginning of a row without prior newline,
1772     * move one row up!
1773     * This touches only the screen-update. Otherwise we would may have
1774     * an empty row on the screen */
1775    if (cursor.pos() && !cursor.row()->par()->isNewline(cursor.row()->pos() - 1)
1776        && cursor.row()->pos() == cursor.pos())
1777    {
1778            cursorLeft(bview);
1779    }
1780
1781    status(bview, LyXText::NEED_MORE_REFRESH);
1782    refresh_row = cursor.row();
1783    refresh_y = cursor.y() - cursor.row()->baseline();
1784
1785    // Do not forget the special right address boxes
1786    if (layout.margintype == MARGIN_RIGHT_ADDRESS_BOX) {
1787       while (refresh_row->previous() &&
1788              refresh_row->previous()->par() == refresh_row->par()) {
1789               refresh_row = refresh_row->previous();
1790               refresh_y -= refresh_row->height();
1791       }
1792    }
1793    removeParagraph(cursor.row());
1794
1795    // set the dimensions of the cursor row
1796    cursor.row()->fill(fill(bview, cursor.row(), workWidth(bview)));
1797
1798    setHeightOfRow(bview, cursor.row());
1799
1800    while (cursor.par()->next()->size()
1801           && cursor.par()->next()->isNewline(0))
1802            cursor.par()->next()->erase(0);
1803
1804    insertParagraph(bview, cursor.par()->next(), cursor.row());
1805
1806    updateCounters(bview, cursor.row()->previous());
1807
1808    /* This check is necessary. Otherwise the new empty paragraph will
1809     * be deleted automatically. And it is more friendly for the user! */
1810    if (cursor.pos() || layout.keepempty)
1811            setCursor(bview, cursor.par()->next(), 0);
1812    else
1813            setCursor(bview, cursor.par(), 0);
1814
1815    if (cursor.row()->next())
1816            breakAgain(bview, cursor.row()->next());
1817
1818    need_break_row = 0;
1819 }
1820
1821
1822 // Just a macro to make some thing easier.
1823 void LyXText::redoParagraph(BufferView * bview) const
1824 {
1825         clearSelection();
1826         redoParagraphs(bview, cursor, cursor.par()->next());
1827         setCursorIntern(bview, cursor.par(), cursor.pos());
1828 }
1829
1830
1831 /* insert a character, moves all the following breaks in the
1832  * same Paragraph one to the right and make a rebreak */
1833 void LyXText::insertChar(BufferView * bview, char c)
1834 {
1835         setUndo(bview, Undo::INSERT, cursor.par(), cursor.par()->next());
1836
1837         // When the free-spacing option is set for the current layout,
1838         // disable the double-space checking
1839
1840         bool const freeSpacing =
1841                 textclasslist[bview->buffer()->params.textclass][cursor.row()->par()->layout()].free_spacing ||
1842                 cursor.row()->par()->isFreeSpacing();
1843
1844         if (lyxrc.auto_number) {
1845                 static string const number_operators = "+-/*";
1846                 static string const number_unary_operators = "+-";
1847                 static string const number_seperators = ".,:";
1848
1849                 if (current_font.number() == LyXFont::ON) {
1850                         if (!IsDigit(c) && !contains(number_operators, c) &&
1851                             !(contains(number_seperators, c) &&
1852                               cursor.pos() >= 1 &&
1853                               cursor.pos() < cursor.par()->size() &&
1854                               getFont(bview->buffer(),
1855                                       cursor.par(),
1856                                       cursor.pos()).number() == LyXFont::ON &&
1857                               getFont(bview->buffer(),
1858                                       cursor.par(),
1859                                       cursor.pos() - 1).number() == LyXFont::ON)
1860                            )
1861                                 number(bview); // Set current_font.number to OFF
1862                 } else if (IsDigit(c) &&
1863                            real_current_font.isVisibleRightToLeft()) {
1864                         number(bview); // Set current_font.number to ON
1865
1866                         if (cursor.pos() > 0) {
1867                                 char const c = cursor.par()->getChar(cursor.pos() - 1);
1868                                 if (contains(number_unary_operators, c) &&
1869                                     (cursor.pos() == 1 ||
1870                                      cursor.par()->isSeparator(cursor.pos() - 2) ||
1871                                      cursor.par()->isNewline(cursor.pos() - 2))
1872                                   ) {
1873                                         setCharFont(bview->buffer(),
1874                                                     cursor.par(),
1875                                                     cursor.pos() - 1,
1876                                                     current_font);
1877                                 } else if (contains(number_seperators, c) &&
1878                                            cursor.pos() >= 2 &&
1879                                            getFont(bview->buffer(),
1880                                                    cursor.par(),
1881                                                    cursor.pos() - 2).number() == LyXFont::ON) {
1882                                         setCharFont(bview->buffer(),
1883                                                     cursor.par(),
1884                                                     cursor.pos() - 1,
1885                                                     current_font);
1886                                 }
1887                         }
1888                 }
1889         }
1890
1891
1892         /* First check, if there will be two blanks together or a blank at
1893           the beginning of a paragraph.
1894           I decided to handle blanks like normal characters, the main
1895           difference are the special checks when calculating the row.fill
1896           (blank does not count at the end of a row) and the check here */
1897
1898         // The bug is triggered when we type in a description environment:
1899         // The current_font is not changed when we go from label to main text
1900         // and it should (along with realtmpfont) when we type the space.
1901         // CHECK There is a bug here! (Asger)
1902
1903         LyXFont realtmpfont = real_current_font;
1904         LyXFont rawtmpfont = current_font;  /* store the current font.
1905                                      * This is because of the use
1906                                      * of cursor movements. The moving
1907                                      * cursor would refresh the
1908                                      * current font */
1909
1910         // Get the font that is used to calculate the baselineskip
1911         pos_type const lastpos = cursor.par()->size();
1912         LyXFont rawparfont =
1913                 cursor.par()->getFontSettings(bview->buffer()->params,
1914                                               lastpos - 1);
1915
1916         bool jumped_over_space = false;
1917
1918         if (!freeSpacing && IsLineSeparatorChar(c)) {
1919                 if ((cursor.pos() > 0
1920                      && cursor.par()->isLineSeparator(cursor.pos() - 1))
1921                     || (cursor.pos() > 0
1922                         && cursor.par()->isNewline(cursor.pos() - 1))
1923                     || (cursor.pos() == 0)) {
1924                         static bool sent_space_message = false;
1925                         if (!sent_space_message) {
1926                                 if (cursor.pos() == 0)
1927                                         bview->owner()->message(_("You cannot insert a space at the beginning of a paragraph.  Please read the Tutorial."));
1928                                 else
1929                                         bview->owner()->message(_("You cannot type two spaces this way.  Please read the Tutorial."));
1930                                 sent_space_message = true;
1931                         }
1932                         charInserted();
1933                         return;
1934                 }
1935         } else if (IsNewlineChar(c)) {
1936                 if (cursor.pos() <= beginningOfMainBody(bview->buffer(),
1937                                                         cursor.par()))
1938                 {
1939                         charInserted();
1940                         return;
1941                 }
1942                 /* No newline at first position
1943                  * of a paragraph or behind labels.
1944                  * TeX does not allow that */
1945
1946                 if (cursor.pos() < cursor.par()->size() &&
1947                     cursor.par()->isLineSeparator(cursor.pos()))
1948                         // newline always after a blank!
1949                         cursorRight(bview);
1950                 cursor.row()->fill(-1);        // to force a new break
1951         }
1952
1953         // the display inset stuff
1954         if (cursor.row()->par()->isInset(cursor.row()->pos())) {
1955                 Inset * inset = cursor.row()->par()->getInset(cursor.row()->pos());
1956                 if (inset && (inset->display() || inset->needFullRow())) {
1957                         // force a new break
1958                         cursor.row()->fill(-1); // to force a new break
1959                 }
1960         }
1961
1962         // get the cursor row fist
1963         Row * row = cursor.row();
1964         int y = cursor.y() - row->baseline();
1965         if (c != Paragraph::META_INSET) /* Here case LyXText::InsertInset
1966                                          * already insertet the character */
1967                 cursor.par()->insertChar(cursor.pos(), c);
1968         setCharFont(bview->buffer(), cursor.par(), cursor.pos(), rawtmpfont);
1969
1970         if (!jumped_over_space) {
1971                 // refresh the positions
1972                 Row * tmprow = row;
1973                 while (tmprow->next() && tmprow->next()->par() == row->par()) {
1974                         tmprow = tmprow->next();
1975                         tmprow->pos(tmprow->pos() + 1);
1976                 }
1977         }
1978
1979         // Is there a break one row above
1980         if (row->previous() && row->previous()->par() == row->par()
1981             && (cursor.par()->isLineSeparator(cursor.pos())
1982                 || cursor.par()->isNewline(cursor.pos())
1983                 || ((cursor.pos() < cursor.par()->size()) &&
1984                     cursor.par()->isInset(cursor.pos()+1))
1985                 || cursor.row()->fill() == -1))
1986         {
1987                 pos_type z = nextBreakPoint(bview,
1988                                                            row->previous(),
1989                                                            workWidth(bview));
1990                 if (z >= row->pos()) {
1991                         row->pos(z + 1);
1992
1993                         // set the dimensions of the row above
1994                         row->previous()->fill(fill(bview,
1995                                                    row->previous(),
1996                                                    workWidth(bview)));
1997
1998                         setHeightOfRow(bview, row->previous());
1999
2000                         y -= row->previous()->height();
2001                         refresh_y = y;
2002                         refresh_row = row->previous();
2003                         status(bview, LyXText::NEED_MORE_REFRESH);
2004
2005                         breakAgainOneRow(bview, row);
2006
2007                         current_font = rawtmpfont;
2008                         real_current_font = realtmpfont;
2009                         setCursor(bview, cursor.par(), cursor.pos() + 1,
2010                                   false, cursor.boundary());
2011                         // cursor MUST be in row now.
2012
2013                         if (row->next() && row->next()->par() == row->par())
2014                                 need_break_row = row->next();
2015                         else
2016                                 need_break_row = 0;
2017
2018                         // check, wether the last characters font has changed.
2019                         if (cursor.pos() && cursor.pos() == cursor.par()->size()
2020                             && rawparfont != rawtmpfont)
2021                                 redoHeightOfParagraph(bview, cursor);
2022
2023                         charInserted();
2024                         return;
2025                 }
2026         }
2027
2028         // recalculate the fill of the row
2029         if (row->fill() >= 0)  /* needed because a newline
2030                                 * will set fill to -1. Otherwise
2031                                 * we would not get a rebreak! */
2032                 row->fill(fill(bview, row, workWidth(bview)));
2033         if (c == Paragraph::META_INSET || row->fill() < 0) {
2034                 refresh_y = y;
2035                 refresh_row = row;
2036                 refresh_x = cursor.x();
2037                 refresh_pos = cursor.pos();
2038                 status(bview, LyXText::NEED_MORE_REFRESH);
2039                 breakAgainOneRow(bview, row);
2040                 // will the cursor be in another row now?
2041                 if (rowLast(row) <= cursor.pos() + 1 && row->next()) {
2042                         if (row->next() && row->next()->par() == row->par())
2043                                 // this should always be true
2044                                 row = row->next();
2045                         breakAgainOneRow(bview, row);
2046                 }
2047                 current_font = rawtmpfont;
2048                 real_current_font = realtmpfont;
2049
2050                 setCursor(bview, cursor.par(), cursor.pos() + 1, false,
2051                           cursor.boundary());
2052                 if (isBoundary(bview->buffer(), cursor.par(), cursor.pos())
2053                     != cursor.boundary())
2054                         setCursor(bview, cursor.par(), cursor.pos(), false,
2055                           !cursor.boundary());
2056                 if (row->next() && row->next()->par() == row->par())
2057                         need_break_row = row->next();
2058                 else
2059                         need_break_row = 0;
2060         } else {
2061                 refresh_y = y;
2062                 refresh_x = cursor.x();
2063                 refresh_row = row;
2064                 refresh_pos = cursor.pos();
2065
2066                 int const tmpheight = row->height();
2067                 setHeightOfRow(bview, row);
2068                 if (tmpheight == row->height())
2069                         status(bview, LyXText::NEED_VERY_LITTLE_REFRESH);
2070                 else
2071                         status(bview, LyXText::NEED_MORE_REFRESH);
2072
2073                 current_font = rawtmpfont;
2074                 real_current_font = realtmpfont;
2075                 setCursor(bview, cursor.par(), cursor.pos() + 1, false,
2076                           cursor.boundary());
2077         }
2078
2079         // check, wether the last characters font has changed.
2080         if (cursor.pos() && cursor.pos() == cursor.par()->size()
2081             && rawparfont != rawtmpfont) {
2082                 redoHeightOfParagraph(bview, cursor);
2083         } else {
2084                 // now the special right address boxes
2085                 if (textclasslist[bview->buffer()->params.textclass][cursor.par()->layout()].margintype
2086                     == MARGIN_RIGHT_ADDRESS_BOX) {
2087                         redoDrawingOfParagraph(bview, cursor);
2088                 }
2089         }
2090
2091         charInserted();
2092 }
2093
2094
2095 void LyXText::charInserted()
2096 {
2097         // Here we could call FinishUndo for every 20 characters inserted.
2098         // This is from my experience how emacs does it.
2099         static unsigned int counter;
2100         if (counter < 20) {
2101                 ++counter;
2102         } else {
2103                 finishUndo();
2104                 counter = 0;
2105         }
2106 }
2107
2108
2109 void LyXText::prepareToPrint(BufferView * bview,
2110                              Row * row, float & x,
2111                              float & fill_separator,
2112                              float & fill_hfill,
2113                              float & fill_label_hfill,
2114                              bool bidi) const
2115 {
2116         float nlh;
2117         float ns;
2118
2119         float w = row->fill();
2120         fill_hfill = 0;
2121         fill_label_hfill = 0;
2122         fill_separator = 0;
2123         fill_label_hfill = 0;
2124
2125         bool const is_rtl =
2126                 row->par()->isRightToLeftPar(bview->buffer()->params);
2127         if (is_rtl) {
2128                 x = (workWidth(bview) > 0)
2129                         ? rightMargin(bview->buffer(), row) : 0;
2130         } else
2131                 x = (workWidth(bview) > 0)
2132                         ? leftMargin(bview, row) : 0;
2133
2134         // is there a manual margin with a manual label
2135         LyXTextClass const & tclass = textclasslist[bview->buffer()->params.textclass];
2136         LyXLayout const & layout = tclass[row->par()->layout()];
2137
2138         if (layout.margintype == MARGIN_MANUAL
2139             && layout.labeltype == LABEL_MANUAL) {
2140                 // one more since labels are left aligned
2141                 nlh = numberOfLabelHfills(bview->buffer(), row) + 1;
2142                 if (nlh && !row->par()->getLabelWidthString().empty()) {
2143                         fill_label_hfill = labelFill(bview, row) / nlh;
2144                 }
2145         }
2146
2147         // are there any hfills in the row?
2148         float const nh = numberOfHfills(bview->buffer(), row);
2149
2150         if (nh) {
2151                 if (w > 0)
2152                         fill_hfill = w / nh;
2153         // we don't have to look at the alignment if it is ALIGN_LEFT and
2154         // if the row is already larger then the permitted width as then
2155         // we force the LEFT_ALIGN'edness!
2156         } else if (static_cast<int>(row->width()) < workWidth(bview)) {
2157                 // is it block, flushleft or flushright?
2158                 // set x how you need it
2159                 int align;
2160                 if (row->par()->params().align() == LYX_ALIGN_LAYOUT) {
2161                         align = layout.align;
2162                 } else {
2163                         align = row->par()->params().align();
2164                 }
2165
2166                 // center displayed insets
2167                 Inset * inset;
2168                 if (row->par()->isInset(row->pos())
2169                     && (inset=row->par()->getInset(row->pos()))
2170                     && (inset->display())) // || (inset->scroll() < 0)))
2171                     align = (inset->lyxCode() == Inset::MATHMACRO_CODE)
2172                         ? LYX_ALIGN_BLOCK : LYX_ALIGN_CENTER;
2173                 // ERT insets should always be LEFT ALIGNED on screen
2174                 inset = row->par()->inInset();
2175                 if (inset && inset->owner() &&
2176                         inset->owner()->lyxCode() == Inset::ERT_CODE)
2177                 {
2178                         align = LYX_ALIGN_LEFT;
2179                 }
2180
2181                 switch (align) {
2182             case LYX_ALIGN_BLOCK:
2183                         ns = numberOfSeparators(bview->buffer(), row);
2184                         if (ns && row->next() && row->next()->par() == row->par() &&
2185                             !(row->next()->par()->isNewline(row->next()->pos() - 1))
2186                             && !(row->next()->par()->isInset(row->next()->pos())
2187                                  && row->next()->par()->getInset(row->next()->pos())
2188                                  && row->next()->par()->getInset(row->next()->pos())->display())
2189                                 )
2190                         {
2191                                 fill_separator = w / ns;
2192                         } else if (is_rtl) {
2193                                 x += w;
2194                         }
2195                         break;
2196             case LYX_ALIGN_RIGHT:
2197                         x += w;
2198                         break;
2199             case LYX_ALIGN_CENTER:
2200                         x += w / 2;
2201                         break;
2202                 }
2203         }
2204         if (!bidi)
2205                 return;
2206
2207         computeBidiTables(bview->buffer(), row);
2208         if (is_rtl) {
2209                 pos_type main_body =
2210                         beginningOfMainBody(bview->buffer(), row->par());
2211                 pos_type last = rowLast(row);
2212
2213                 if (main_body > 0 &&
2214                     (main_body - 1 > last ||
2215                      !row->par()->isLineSeparator(main_body - 1))) {
2216                         x += lyxfont::width(layout.labelsep,
2217                                             getLabelFont(bview->buffer(), row->par()));
2218                         if (main_body - 1 <= last)
2219                                 x += fill_label_hfill;
2220                 }
2221         }
2222 }
2223
2224 /* important for the screen */
2225
2226
2227 /* the cursor set functions have a special mechanism. When they
2228 * realize, that you left an empty paragraph, they will delete it.
2229 * They also delete the corresponding row */
2230
2231 void LyXText::cursorRightOneWord(BufferView * bview) const
2232 {
2233         // treat floats, HFills and Insets as words
2234         LyXCursor tmpcursor = cursor;
2235         // CHECK See comment on top of text.C
2236
2237         if (tmpcursor.pos() == tmpcursor.par()->size()
2238             && tmpcursor.par()->next()) {
2239                         tmpcursor.par(tmpcursor.par()->next());
2240                         tmpcursor.pos(0);
2241         } else {
2242                 int steps = 0;
2243
2244                 // Skip through initial nonword stuff.
2245                 while (tmpcursor.pos() < tmpcursor.par()->size() &&
2246                        ! tmpcursor.par()->isWord(tmpcursor.pos())) {
2247                   //    printf("Current pos1 %d", tmpcursor.pos()) ;
2248                         tmpcursor.pos(tmpcursor.pos() + 1);
2249                         ++steps;
2250                 }
2251                 // Advance through word.
2252                 while (tmpcursor.pos() < tmpcursor.par()->size() &&
2253                         tmpcursor.par()->isWord(tmpcursor.pos())) {
2254                   //     printf("Current pos2 %d", tmpcursor.pos()) ;
2255                         tmpcursor.pos(tmpcursor.pos() + 1);
2256                         ++steps;
2257                 }
2258         }
2259         setCursor(bview, tmpcursor.par(), tmpcursor.pos());
2260 }
2261
2262
2263 void LyXText::cursorTab(BufferView * bview) const
2264 {
2265     LyXCursor tmpcursor = cursor;
2266     while (tmpcursor.pos() < tmpcursor.par()->size()
2267            && !tmpcursor.par()->isNewline(tmpcursor.pos()))
2268         tmpcursor.pos(tmpcursor.pos() + 1);
2269
2270     if (tmpcursor.pos() == tmpcursor.par()->size()) {
2271         if (tmpcursor.par()->next()) {
2272             tmpcursor.par(tmpcursor.par()->next());
2273             tmpcursor.pos(0);
2274         }
2275     } else
2276         tmpcursor.pos(tmpcursor.pos() + 1);
2277     setCursor(bview, tmpcursor.par(), tmpcursor.pos());
2278 }
2279
2280
2281 /* -------> Skip initial whitespace at end of word and move cursor to *start*
2282             of prior word, not to end of next prior word. */
2283
2284 void LyXText::cursorLeftOneWord(BufferView * bview)  const
2285 {
2286         LyXCursor tmpcursor = cursor;
2287         cursorLeftOneWord(tmpcursor);
2288         setCursor(bview, tmpcursor.par(), tmpcursor.pos());
2289 }
2290
2291 void LyXText::cursorLeftOneWord(LyXCursor  & cur)  const
2292 {
2293         // treat HFills, floats and Insets as words
2294         cur = cursor;
2295         while (cur.pos()
2296                && (cur.par()->isSeparator(cur.pos() - 1)
2297                    || cur.par()->isKomma(cur.pos() - 1))
2298                && !(cur.par()->isHfill(cur.pos() - 1)
2299                     || cur.par()->isInset(cur.pos() - 1)))
2300                 cur.pos(cur.pos() - 1);
2301
2302         if (cur.pos()
2303             && (cur.par()->isInset(cur.pos() - 1)
2304                 || cur.par()->isHfill(cur.pos() - 1))) {
2305                 cur.pos(cur.pos() - 1);
2306         } else if (!cur.pos()) {
2307                 if (cur.par()->previous()) {
2308                         cur.par(cur.par()->previous());
2309                         cur.pos(cur.par()->size());
2310                 }
2311         } else {                // Here, cur != 0
2312                 while (cur.pos() > 0 &&
2313                        cur.par()->isWord(cur.pos()-1))
2314                         cur.pos(cur.pos() - 1);
2315         }
2316 }
2317
2318 /* -------> Select current word. This depends on behaviour of
2319 CursorLeftOneWord(), so it is patched as well. */
2320 void LyXText::getWord(LyXCursor & from, LyXCursor & to,
2321                       word_location const loc) const
2322 {
2323         // first put the cursor where we wana start to select the word
2324         from = cursor;
2325         switch (loc) {
2326         case WHOLE_WORD_STRICT:
2327                 if (cursor.pos() == 0 || cursor.pos() == cursor.par()->size()
2328                     || cursor.par()->isSeparator(cursor.pos())
2329                     || cursor.par()->isKomma(cursor.pos())
2330                     || cursor.par()->isSeparator(cursor.pos() -1)
2331                     || cursor.par()->isKomma(cursor.pos() -1)) {
2332                         to = from;
2333                         return;
2334                 }
2335                 // no break here, we go to the next
2336
2337         case WHOLE_WORD:
2338                 // Move cursor to the beginning, when not already there.
2339                 if (from.pos() && !from.par()->isSeparator(from.pos() - 1)
2340                     && !from.par()->isKomma(from.pos() - 1))
2341                         cursorLeftOneWord(from);
2342                 break;
2343         case PREVIOUS_WORD:
2344                 // always move the cursor to the beginning of previous word
2345                 cursorLeftOneWord(from);
2346                 break;
2347         case NEXT_WORD:
2348                 lyxerr << "LyXText::getWord: NEXT_WORD not implemented yet\n";
2349                 break;
2350         case PARTIAL_WORD:
2351                 break;
2352         }
2353         to = from;
2354         while (to.pos() < to.par()->size()
2355                && !to.par()->isSeparator(to.pos())
2356                && !to.par()->isKomma(to.pos())
2357                && !to.par()->isHfill(to.pos()))
2358         {
2359                 to.pos(to.pos() + 1);
2360         }
2361 }
2362
2363
2364 void LyXText::selectWord(BufferView * bview, word_location const loc)
2365 {
2366         LyXCursor from;
2367         LyXCursor to;
2368         getWord(from, to, loc);
2369         if (cursor != from)
2370                 setCursor(bview, from.par(), from.pos());
2371         if (to == from)
2372                 return;
2373         selection.cursor = cursor;
2374         setCursor(bview, to.par(), to.pos());
2375         setSelection(bview);
2376 }
2377
2378
2379 /* -------> Select the word currently under the cursor when no
2380         selection is currently set */
2381 bool LyXText::selectWordWhenUnderCursor(BufferView * bview,
2382                                         word_location const loc)
2383 {
2384         if (!selection.set()) {
2385                 selectWord(bview, loc);
2386                 return selection.set();
2387         }
2388         return false;
2389 }
2390
2391
2392 // This function is only used by the spellchecker for NextWord().
2393 // It doesn't handle LYX_ACCENTs and probably never will.
2394 string const LyXText::selectNextWordToSpellcheck(BufferView * bview,
2395                                                  float & value) const
2396 {
2397         if (the_locking_inset) {
2398                 string str = the_locking_inset->selectNextWordToSpellcheck(bview, value);
2399                 if (!str.empty()) {
2400                         value += float(cursor.y())/float(height);
2401                         return str;
2402                 }
2403                 // we have to go on checking so move cusor to the next char
2404                 if (cursor.pos() == cursor.par()->size()) {
2405                         if (!cursor.par()->next())
2406                                 return str;
2407                         cursor.par(cursor.par()->next());
2408                         cursor.pos(0);
2409                 } else
2410                         cursor.pos(cursor.pos() + 1);
2411         }
2412         Paragraph * tmppar = cursor.par();
2413
2414         // If this is not the very first word, skip rest of
2415         // current word because we are probably in the middle
2416         // of a word if there is text here.
2417         if (cursor.pos() || cursor.par()->previous()) {
2418                 while (cursor.pos() < cursor.par()->size()
2419                        && cursor.par()->isLetter(cursor.pos()))
2420                         cursor.pos(cursor.pos() + 1);
2421         }
2422
2423         // Now, skip until we have real text (will jump paragraphs)
2424         while ((cursor.par()->size() > cursor.pos()
2425                && (!cursor.par()->isLetter(cursor.pos()))
2426                && (!cursor.par()->isInset(cursor.pos()) ||
2427                            !cursor.par()->getInset(cursor.pos())->allowSpellcheck()))
2428                || (cursor.par()->size() == cursor.pos()
2429                    && cursor.par()->next()))
2430         {
2431                 if (cursor.pos() == cursor.par()->size()) {
2432                         cursor.par(cursor.par()->next());
2433                         cursor.pos(0);
2434                 } else
2435                         cursor.pos(cursor.pos() + 1);
2436         }
2437
2438         // now check if we hit an inset so it has to be a inset containing text!
2439         if (cursor.pos() < cursor.par()->size() &&
2440             cursor.par()->isInset(cursor.pos()))
2441         {
2442                 // lock the inset!
2443                 cursor.par()->getInset(cursor.pos())->edit(bview);
2444                 // now call us again to do the above trick
2445                 // but obviously we have to start from down below ;)
2446                 return bview->text->selectNextWordToSpellcheck(bview, value);
2447         }
2448
2449         // Update the value if we changed paragraphs
2450         if (cursor.par() != tmppar) {
2451                 setCursor(bview, cursor.par(), cursor.pos());
2452                 value = float(cursor.y())/float(height);
2453         }
2454
2455         // Start the selection from here
2456         selection.cursor = cursor;
2457
2458         // and find the end of the word (insets like optional hyphens
2459         // and ligature break are part of a word)
2460         while (cursor.pos() < cursor.par()->size()
2461                && (cursor.par()->isLetter(cursor.pos())))
2462                 cursor.pos(cursor.pos() + 1);
2463
2464         // Finally, we copy the word to a string and return it
2465         string str;
2466         if (selection.cursor.pos() < cursor.pos()) {
2467                 pos_type i;
2468                 for (i = selection.cursor.pos(); i < cursor.pos(); ++i) {
2469                         if (!cursor.par()->isInset(i))
2470                                 str += cursor.par()->getChar(i);
2471                 }
2472         }
2473         return str;
2474 }
2475
2476
2477 // This one is also only for the spellchecker
2478 void LyXText::selectSelectedWord(BufferView * bview)
2479 {
2480         if (the_locking_inset) {
2481                 the_locking_inset->selectSelectedWord(bview);
2482                 return;
2483         }
2484         // move cursor to the beginning
2485         setCursor(bview, selection.cursor.par(), selection.cursor.pos());
2486
2487         // set the sel cursor
2488         selection.cursor = cursor;
2489
2490         // now find the end of the word
2491         while (cursor.pos() < cursor.par()->size()
2492                && (cursor.par()->isLetter(cursor.pos())))
2493                 cursor.pos(cursor.pos() + 1);
2494
2495         setCursor(bview, cursor.par(), cursor.pos());
2496
2497         // finally set the selection
2498         setSelection(bview);
2499 }
2500
2501
2502 /* -------> Delete from cursor up to the end of the current or next word. */
2503 void LyXText::deleteWordForward(BufferView * bview)
2504 {
2505         if (!cursor.par()->size())
2506                 cursorRight(bview);
2507         else {
2508                 LyXCursor tmpcursor = cursor;
2509                 tmpcursor.row(0); // ??
2510                 selection.set(true); // to avoid deletion
2511                 cursorRightOneWord(bview);
2512                 setCursor(bview, tmpcursor, tmpcursor.par(), tmpcursor.pos());
2513                 selection.cursor = cursor;
2514                 cursor = tmpcursor;
2515                 setSelection(bview);
2516
2517                 /* -----> Great, CutSelection() gets rid of multiple spaces. */
2518                 cutSelection(bview, true, false);
2519         }
2520 }
2521
2522
2523 /* -------> Delete from cursor to start of current or prior word. */
2524 void LyXText::deleteWordBackward(BufferView * bview)
2525 {
2526        if (!cursor.par()->size())
2527                cursorLeft(bview);
2528        else {
2529                LyXCursor tmpcursor = cursor;
2530                tmpcursor.row(0); // ??
2531                selection.set(true); // to avoid deletion
2532                cursorLeftOneWord(bview);
2533                setCursor(bview, tmpcursor, tmpcursor.par(), tmpcursor.pos());
2534                selection.cursor = cursor;
2535                cursor = tmpcursor;
2536                setSelection(bview);
2537                cutSelection(bview, true, false);
2538        }
2539 }
2540
2541
2542 /* -------> Kill to end of line. */
2543 void LyXText::deleteLineForward(BufferView * bview)
2544 {
2545         if (!cursor.par()->size())
2546                 // Paragraph is empty, so we just go to the right
2547                 cursorRight(bview);
2548         else {
2549                 LyXCursor tmpcursor = cursor;
2550                 // We can't store the row over a regular setCursor
2551                 // so we set it to 0 and reset it afterwards.
2552                 tmpcursor.row(0); // ??
2553                 selection.set(true); // to avoid deletion
2554                 cursorEnd(bview);
2555                 setCursor(bview, tmpcursor, tmpcursor.par(), tmpcursor.pos());
2556                 selection.cursor = cursor;
2557                 cursor = tmpcursor;
2558                 setSelection(bview);
2559                 // What is this test for ??? (JMarc)
2560                 if (!selection.set()) {
2561                         deleteWordForward(bview);
2562                 } else {
2563                         cutSelection(bview, true, false);
2564                 }
2565         }
2566 }
2567
2568
2569 // Change the case of a word at cursor position.
2570 // This function directly manipulates Paragraph::text because there
2571 // is no Paragraph::SetChar currently. I did what I could to ensure
2572 // that it is correct. I guess part of it should be moved to
2573 // Paragraph, but it will have to change for 1.1 anyway. At least
2574 // it does not access outside of the allocated array as the older
2575 // version did. (JMarc)
2576 void LyXText::changeCase(BufferView * bview, LyXText::TextCase action)
2577 {
2578         LyXCursor from;
2579         LyXCursor to;
2580
2581         if (selection.set()) {
2582                 from = selection.start;
2583                 to = selection.end;
2584         } else {
2585                 getWord(from, to, PARTIAL_WORD);
2586                 setCursor(bview, to.par(), to.pos() + 1);
2587         }
2588
2589         changeRegionCase(bview, from, to, action);
2590 }
2591
2592
2593 void LyXText::changeRegionCase(BufferView * bview,
2594                                LyXCursor const & from,
2595                                LyXCursor const & to,
2596                                LyXText::TextCase action)
2597 {
2598         lyx::Assert(from <= to);
2599
2600         setUndo(bview, Undo::FINISH, from.par(), to.par()->next());
2601
2602         pos_type pos = from.pos();
2603         Paragraph * par = from.par();
2604
2605         while (par && (pos != to.pos() || par != to.par())) {
2606                 unsigned char c = par->getChar(pos);
2607                 if (!IsInsetChar(c) && !IsHfillChar(c)) {
2608                         switch (action) {
2609                         case text_lowercase:
2610                                 c = lowercase(c);
2611                                 break;
2612                         case text_capitalization:
2613                                 c = uppercase(c);
2614                                 action = text_lowercase;
2615                                 break;
2616                         case text_uppercase:
2617                                 c = uppercase(c);
2618                                 break;
2619                         }
2620                 }
2621                 par->setChar(pos, c);
2622                 checkParagraph(bview, par, pos);
2623
2624                 ++pos;
2625                 if (pos == par->size()) {
2626                         par = par->next();
2627                         pos = 0;
2628                 }
2629         }
2630         if (to.row() != from.row()) {
2631                 refresh_y = from.y() - from.row()->baseline();
2632                 refresh_row = from.row();
2633                 status(bview, LyXText::NEED_MORE_REFRESH);
2634         }
2635 }
2636
2637
2638 void LyXText::transposeChars(BufferView & bview)
2639 {
2640         Paragraph * tmppar = cursor.par();
2641
2642         setUndo(&bview, Undo::FINISH, tmppar, tmppar->next());
2643
2644         pos_type tmppos = cursor.pos();
2645
2646         // First decide if it is possible to transpose at all
2647
2648         // We are at the beginning of a paragraph.
2649         if (tmppos == 0) return;
2650
2651         // We are at the end of a paragraph.
2652         if (tmppos == tmppar->size() - 1) return;
2653
2654         unsigned char c1 = tmppar->getChar(tmppos);
2655         unsigned char c2 = tmppar->getChar(tmppos - 1);
2656
2657         if (c1 != Paragraph::META_INSET
2658             && c2 != Paragraph::META_INSET) {
2659                 tmppar->setChar(tmppos, c2);
2660                 tmppar->setChar(tmppos - 1, c1);
2661         }
2662         // We should have an implementation that handles insets
2663         // as well, but that will have to come later. (Lgb)
2664         checkParagraph(const_cast<BufferView*>(&bview), tmppar, tmppos);
2665 }
2666
2667
2668 void LyXText::Delete(BufferView * bview)
2669 {
2670         // this is a very easy implementation
2671
2672         LyXCursor old_cursor = cursor;
2673         int const old_cur_par_id = old_cursor.par()->id();
2674         int const old_cur_par_prev_id = old_cursor.par()->previous() ?
2675                 old_cursor.par()->previous()->id() : 0;
2676
2677         // just move to the right
2678         cursorRight(bview);
2679
2680         // CHECK Look at the comment here.
2681         // This check is not very good...
2682         // The cursorRightIntern calls DeleteEmptyParagrapgMechanism
2683         // and that can very well delete the par or par->previous in
2684         // old_cursor. Will a solution where we compare paragraph id's
2685         //work better?
2686         if ((cursor.par()->previous() ? cursor.par()->previous()->id() : 0)
2687             == old_cur_par_prev_id
2688             && cursor.par()->id() != old_cur_par_id) {
2689                 // delete-empty-paragraph-mechanism has done it
2690                 return;
2691         }
2692
2693         // if you had success make a backspace
2694         if (old_cursor.par() != cursor.par() || old_cursor.pos() != cursor.pos()) {
2695                 LyXCursor tmpcursor = cursor;
2696                 // to make sure undo gets the right cursor position
2697                 cursor = old_cursor;
2698                 setUndo(bview, Undo::DELETE,
2699                         cursor.par(), cursor.par()->next());
2700                 cursor = tmpcursor;
2701                 backspace(bview);
2702         }
2703 }
2704
2705
2706 void LyXText::backspace(BufferView * bview)
2707 {
2708         // Get the font that is used to calculate the baselineskip
2709         pos_type lastpos = cursor.par()->size();
2710         LyXFont rawparfont =
2711                 cursor.par()->getFontSettings(bview->buffer()->params,
2712                                               lastpos - 1);
2713
2714         if (cursor.pos() == 0) {
2715                 // The cursor is at the beginning of a paragraph,
2716                 // so the the backspace will collapse two paragraphs into one.
2717
2718                 // we may paste some paragraphs
2719
2720                 // is it an empty paragraph?
2721
2722                 if ((lastpos == 0
2723                      || (lastpos == 1 && cursor.par()->isSeparator(0)))) {
2724                         // This is an empty paragraph and we delete it just by moving the cursor one step
2725                         // left and let the DeleteEmptyParagraphMechanism handle the actual deletion
2726                         // of the paragraph.
2727
2728                         if (cursor.par()->previous()) {
2729                                 Paragraph * tmppar = cursor.par()->previous();
2730                                 if (cursor.par()->layout() == tmppar->layout()
2731                                     && cursor.par()->getAlign() == tmppar->getAlign()) {
2732                                         // Inherit bottom DTD from the paragraph below.
2733                                         // (the one we are deleting)
2734                                         tmppar->params().lineBottom(cursor.par()->params().lineBottom());
2735                                         tmppar->params().spaceBottom(cursor.par()->params().spaceBottom());
2736                                         tmppar->params().pagebreakBottom(cursor.par()->params().pagebreakBottom());
2737                                 }
2738
2739                                 cursorLeft(bview);
2740
2741                                 // the layout things can change the height of a row !
2742                                 int const tmpheight = cursor.row()->height();
2743                                 setHeightOfRow(bview, cursor.row());
2744                                 if (cursor.row()->height() != tmpheight) {
2745                                         refresh_y = cursor.y() - cursor.row()->baseline();
2746                                         refresh_row = cursor.row();
2747                                         status(bview, LyXText::NEED_MORE_REFRESH);
2748                                 }
2749                                 return;
2750                         }
2751                 }
2752
2753                 if (cursor.par()->previous()) {
2754                         setUndo(bview, Undo::DELETE,
2755                                 cursor.par()->previous(), cursor.par()->next());
2756                 }
2757
2758                 Paragraph * tmppar = cursor.par();
2759                 Row * tmprow = cursor.row();
2760
2761                 // We used to do cursorLeftIntern() here, but it is
2762                 // not a good idea since it triggers the auto-delete
2763                 // mechanism. So we do a cursorLeftIntern()-lite,
2764                 // without the dreaded mechanism. (JMarc)
2765                 if (cursor.par()->previous()) {
2766                         // steps into the above paragraph.
2767                         setCursorIntern(bview, cursor.par()->previous(),
2768                                         cursor.par()->previous()->size(),
2769                                         false);
2770                 }
2771
2772                 /* Pasting is not allowed, if the paragraphs have different
2773                    layout. I think it is a real bug of all other
2774                    word processors to allow it. It confuses the user.
2775                    Even so with a footnote paragraph and a non-footnote
2776                    paragraph. I will not allow pasting in this case,
2777                    because the user would be confused if the footnote behaves
2778                    different wether it is open or closed.
2779
2780                    Correction: Pasting is always allowed with standard-layout
2781                 */
2782                 LyXTextClass const & tclass = textclasslist[bview->buffer()->params.textclass];
2783
2784                 if (cursor.par() != tmppar
2785                     && (cursor.par()->layout() == tmppar->layout()
2786                         || tmppar->layout() == tclass.defaultLayoutName())
2787                     && cursor.par()->getAlign() == tmppar->getAlign()) {
2788                         removeParagraph(tmprow);
2789                         removeRow(tmprow);
2790                         cursor.par()->pasteParagraph(bview->buffer()->params);
2791
2792                         if (!cursor.pos() || !cursor.par()->isSeparator(cursor.pos() - 1))
2793                                 ; //cursor.par()->insertChar(cursor.pos(), ' ');
2794                         // strangely enough it seems that commenting out the line above removes
2795                         // most or all of the segfaults. I will however also try to move the
2796                         // two Remove... lines in front of the PasteParagraph too.
2797                         else
2798                                 if (cursor.pos())
2799                                         cursor.pos(cursor.pos() - 1);
2800
2801                         status(bview, LyXText::NEED_MORE_REFRESH);
2802                         refresh_row = cursor.row();
2803                         refresh_y = cursor.y() - cursor.row()->baseline();
2804
2805                         // remove the lost paragraph
2806                         // This one is not safe, since the paragraph that the tmprow and the
2807                         // following rows belong to has been deleted by the PasteParagraph
2808                         // above. The question is... could this be moved in front of the
2809                         // PasteParagraph?
2810                         //RemoveParagraph(tmprow);
2811                         //RemoveRow(tmprow);
2812
2813                         // This rebuilds the rows.
2814                         appendParagraph(bview, cursor.row());
2815                         updateCounters(bview, cursor.row());
2816
2817                         // the row may have changed, block, hfills etc.
2818                         setCursor(bview, cursor.par(), cursor.pos(), false);
2819                 }
2820         } else {
2821                 /* this is the code for a normal backspace, not pasting
2822                  * any paragraphs */
2823                 setUndo(bview, Undo::DELETE,
2824                         cursor.par(), cursor.par()->next());
2825                 // We used to do cursorLeftIntern() here, but it is
2826                 // not a good idea since it triggers the auto-delete
2827                 // mechanism. So we do a cursorLeftIntern()-lite,
2828                 // without the dreaded mechanism. (JMarc)
2829                 setCursorIntern(bview, cursor.par(), cursor.pos()- 1,
2830                                 false, cursor.boundary());
2831
2832                 // some insets are undeletable here
2833                 if (cursor.par()->isInset(cursor.pos())) {
2834                         if (!cursor.par()->getInset(cursor.pos())->deletable())
2835                                 return;
2836                         // force complete redo when erasing display insets
2837                         // this is a cruel method but safe..... Matthias
2838                         if (cursor.par()->getInset(cursor.pos())->display() ||
2839                             cursor.par()->getInset(cursor.pos())->needFullRow()) {
2840                                 cursor.par()->erase(cursor.pos());
2841                                 redoParagraph(bview);
2842                                 return;
2843                         }
2844                 }
2845
2846                 Row * row = cursor.row();
2847                 int y = cursor.y() - row->baseline();
2848                 pos_type z;
2849                 /* remember that a space at the end of a row doesnt count
2850                  * when calculating the fill */
2851                 if (cursor.pos() < rowLast(row) ||
2852                     !cursor.par()->isLineSeparator(cursor.pos())) {
2853                         row->fill(row->fill() + singleWidth(bview,
2854                                                             cursor.par(),
2855                                                             cursor.pos()));
2856                 }
2857
2858                 /* some special code when deleting a newline. This is similar
2859                  * to the behavior when pasting paragraphs */
2860                 if (cursor.pos() && cursor.par()->isNewline(cursor.pos())) {
2861                         cursor.par()->erase(cursor.pos());
2862                         // refresh the positions
2863                         Row * tmprow = row;
2864                         while (tmprow->next() && tmprow->next()->par() == row->par()) {
2865                                 tmprow = tmprow->next();
2866                                 tmprow->pos(tmprow->pos() - 1);
2867                         }
2868                         if (cursor.par()->isLineSeparator(cursor.pos() - 1))
2869                                 cursor.pos(cursor.pos() - 1);
2870
2871                         if (cursor.pos() < cursor.par()->size()
2872                             && !cursor.par()->isSeparator(cursor.pos())) {
2873                                 cursor.par()->insertChar(cursor.pos(), ' ');
2874                                 setCharFont(bview->buffer(), cursor.par(),
2875                                             cursor.pos(), current_font);
2876                                 // refresh the positions
2877                                 tmprow = row;
2878                                 while (tmprow->next() && tmprow->next()->par() == row->par()) {
2879                                         tmprow = tmprow->next();
2880                                         tmprow->pos(tmprow->pos() + 1);
2881                                 }
2882                         }
2883                 } else {
2884                         cursor.par()->erase(cursor.pos());
2885
2886                         // refresh the positions
2887                         Row * tmprow = row;
2888                         while (tmprow->next()
2889                                && tmprow->next()->par() == row->par()) {
2890                                 tmprow = tmprow->next();
2891                                 tmprow->pos(tmprow->pos() - 1);
2892                         }
2893
2894                         // delete newlines at the beginning of paragraphs
2895                         while (cursor.par()->size() &&
2896                                cursor.par()->isNewline(cursor.pos()) &&
2897                                cursor.pos() == beginningOfMainBody(bview->buffer(),
2898                                                                    cursor.par())) {
2899                                 cursor.par()->erase(cursor.pos());
2900                                 // refresh the positions
2901                                 tmprow = row;
2902                                 while (tmprow->next() &&
2903                                        tmprow->next()->par() == row->par()) {
2904                                         tmprow = tmprow->next();
2905                                         tmprow->pos(tmprow->pos() - 1);
2906                                 }
2907                         }
2908                 }
2909
2910                 // is there a break one row above
2911                 if (row->previous() && row->previous()->par() == row->par()) {
2912                         z = nextBreakPoint(bview, row->previous(),
2913                                            workWidth(bview));
2914                         if (z >= row->pos()) {
2915                                 row->pos(z + 1);
2916
2917                                 Row * tmprow = row->previous();
2918
2919                                 // maybe the current row is now empty
2920                                 if (row->pos() >= row->par()->size()) {
2921                                         // remove it
2922                                         removeRow(row);
2923                                         need_break_row = 0;
2924                                 } else {
2925                                         breakAgainOneRow(bview, row);
2926                                         if (row->next() && row->next()->par() == row->par())
2927                                                 need_break_row = row->next();
2928                                         else
2929                                                 need_break_row = 0;
2930                                 }
2931
2932                                 // set the dimensions of the row above
2933                                 y -= tmprow->height();
2934                                 tmprow->fill(fill(bview, tmprow,
2935                                                   workWidth(bview)));
2936                                 setHeightOfRow(bview, tmprow);
2937
2938                                 refresh_y = y;
2939                                 refresh_row = tmprow;
2940                                 status(bview, LyXText::NEED_MORE_REFRESH);
2941                                 setCursor(bview, cursor.par(), cursor.pos(),
2942                                           false, cursor.boundary());
2943                                 //current_font = rawtmpfont;
2944                                 //real_current_font = realtmpfont;
2945                                 // check, whether the last character's font has changed.
2946                                 if (rawparfont !=
2947                                     cursor.par()->getFontSettings(bview->buffer()->params,
2948                                                                   cursor.par()->size() - 1))
2949                                         redoHeightOfParagraph(bview, cursor);
2950                                 return;
2951                         }
2952                 }
2953
2954                 // break the cursor row again
2955                 if (row->next() && row->next()->par() == row->par() &&
2956                     (rowLast(row) == row->par()->size() - 1 ||
2957                      nextBreakPoint(bview, row, workWidth(bview)) != rowLast(row))) {
2958
2959                         /* it can happen that a paragraph loses one row
2960                          * without a real breakup. This is when a word
2961                          * is to long to be broken. Well, I don t care this
2962                          * hack ;-) */
2963                         if (rowLast(row) == row->par()->size() - 1)
2964                                 removeRow(row->next());
2965
2966                         refresh_y = y;
2967                         refresh_row = row;
2968                         status(bview, LyXText::NEED_MORE_REFRESH);
2969
2970                         breakAgainOneRow(bview, row);
2971                         // will the cursor be in another row now?
2972                         if (row->next() && row->next()->par() == row->par() &&
2973                             rowLast(row) <= cursor.pos()) {
2974                                 row = row->next();
2975                                 breakAgainOneRow(bview, row);
2976                         }
2977
2978                         setCursor(bview, cursor.par(), cursor.pos(), false, cursor.boundary());
2979
2980                         if (row->next() && row->next()->par() == row->par())
2981                                 need_break_row = row->next();
2982                         else
2983                                 need_break_row = 0;
2984                 } else  {
2985                         // set the dimensions of the row
2986                         row->fill(fill(bview, row, workWidth(bview)));
2987                         int const tmpheight = row->height();
2988                         setHeightOfRow(bview, row);
2989                         if (tmpheight == row->height())
2990                                 status(bview, LyXText::NEED_VERY_LITTLE_REFRESH);
2991                         else
2992                                 status(bview, LyXText::NEED_MORE_REFRESH);
2993                         refresh_y = y;
2994                         refresh_row = row;
2995                         setCursor(bview, cursor.par(), cursor.pos(), false, cursor.boundary());
2996                 }
2997         }
2998
2999         // current_font = rawtmpfont;
3000         // real_current_font = realtmpfont;
3001
3002         if (isBoundary(bview->buffer(), cursor.par(), cursor.pos())
3003             != cursor.boundary())
3004                 setCursor(bview, cursor.par(), cursor.pos(), false,
3005                           !cursor.boundary());
3006
3007         lastpos = cursor.par()->size();
3008         if (cursor.pos() == lastpos)
3009                 setCurrentFont(bview);
3010
3011         // check, whether the last characters font has changed.
3012         if (rawparfont !=
3013             cursor.par()->getFontSettings(bview->buffer()->params, lastpos - 1)) {
3014                 redoHeightOfParagraph(bview, cursor);
3015         } else {
3016                 // now the special right address boxes
3017                 if (textclasslist
3018                     [bview->buffer()->params.textclass]
3019                     [cursor.par()->layout()].margintype == MARGIN_RIGHT_ADDRESS_BOX) {
3020                         redoDrawingOfParagraph(bview, cursor);
3021                 }
3022         }
3023 }
3024
3025
3026 bool LyXText::paintRowBackground(DrawRowParams & p)
3027 {
3028         bool clear_area = true;
3029         Inset * inset = 0;
3030         LyXFont font(LyXFont::ALL_SANE);
3031
3032         pos_type const last = rowLastPrintable(p.row);
3033
3034         if (!p.bv->screen()->forceClear() && last == p.row->pos()
3035                 && p.row->par()->isInset(p.row->pos())) {
3036                 inset = p.row->par()->getInset(p.row->pos());
3037                 if (inset) {
3038                         clear_area = inset->doClearArea();
3039                 }
3040         }
3041
3042         if (p.cleared) {
3043                 return true;
3044         }
3045
3046         if (clear_area) {
3047                 int const x = p.xo;
3048                 int const y = p.yo < 0 ? 0 : p.yo;
3049                 int const h = p.yo < 0 ? p.row->height() + p.yo : p.row->height();
3050                 p.pain->fillRectangle(x, y, p.width, h, backgroundColor());
3051                 return true;
3052         }
3053
3054         if (inset == 0)
3055                 return false;
3056
3057         int h = p.row->baseline() - inset->ascent(p.bv, font);
3058
3059         // first clear the whole row above the inset!
3060         if (h > 0) {
3061                 p.pain->fillRectangle(p.xo, p.yo, p.width, h, backgroundColor());
3062         }
3063
3064         // clear the space below the inset!
3065         h += inset->ascent(p.bv, font) + inset->descent(p.bv, font);
3066         if ((p.row->height() - h) > 0) {
3067                 p.pain->fillRectangle(p.xo, p.yo + h,
3068                         p.width, p.row->height() - h, backgroundColor());
3069         }
3070
3071         // clear the space behind the inset, if needed
3072         if (!inset->display() && !inset->needFullRow()) {
3073                 int const xp = int(p.x) + inset->width(p.bv, font);
3074                 if (p.width - xp > 0) {
3075                         p.pain->fillRectangle(xp, p.yo, p.width - xp,
3076                                 p.row->height(), backgroundColor());
3077                 }
3078         }
3079
3080         return false;
3081 }
3082
3083
3084 void LyXText::paintRowSelection(DrawRowParams & p)
3085 {
3086         bool const is_rtl = p.row->par()->isRightToLeftPar(p.bv->buffer()->params);
3087
3088         // the current selection
3089         int const startx = selection.start.x();
3090         int const endx = selection.end.x();
3091         int const starty = selection.start.y();
3092         int const endy = selection.end.y();
3093         Row const * startrow = selection.start.row();
3094         Row const * endrow = selection.end.row();
3095
3096         Row * row = p.row;
3097
3098         if (bidi_same_direction) {
3099                 int x;
3100                 int y = p.yo;
3101                 int w;
3102                 int h = row->height();
3103
3104                 if (startrow == row && endrow == row) {
3105                         if (startx < endx) {
3106                                 x = p.xo + startx;
3107                                 w = endx - startx;
3108                                 p.pain->fillRectangle(x, y, w, h, LColor::selection);
3109                         } else {
3110                                 x = p.xo + endx;
3111                                 w = startx - endx;
3112                                 p.pain->fillRectangle(x, y, w, h, LColor::selection);
3113                         }
3114                 } else if (startrow == row) {
3115                         int const x = (is_rtl) ? p.xo : (p.xo + startx);
3116                         int const w = (is_rtl) ? startx : (p.width - startx);
3117                         p.pain->fillRectangle(x, y, w, h, LColor::selection);
3118                 } else if (endrow == row) {
3119                         int const x = (is_rtl) ? (p.xo + endx) : p.xo;
3120                         int const w = (is_rtl) ? (p.width - endx) : endx;
3121                         p.pain->fillRectangle(x, y, w, h, LColor::selection);
3122                 } else if (p.y > starty && p.y < endy) {
3123                         p.pain->fillRectangle(p.xo, y, p.width, h, LColor::selection);
3124                 }
3125                 return;
3126         } else if (startrow != row && endrow != row) {
3127                 int w = p.width;
3128                 int h = row->height();
3129                 if (p.y > starty && p.y < endy) {
3130                         p.pain->fillRectangle(p.xo, p.yo, w, h, LColor::selection);
3131                 }
3132                 return;
3133         }
3134
3135         if (!((startrow != row && !is_rtl) || (endrow != row && is_rtl))) {
3136                 return;
3137         }
3138
3139         float tmpx = p.x;
3140
3141         p.pain->fillRectangle(p.xo, p.yo, int(p.x), row->height(), LColor::selection);
3142
3143         Buffer const * buffer = p.bv->buffer();
3144         Paragraph * par = row->par();
3145         pos_type main_body = beginningOfMainBody(buffer, par);
3146         pos_type const last = rowLastPrintable(row);
3147
3148         for (pos_type vpos = row->pos(); vpos <= last; ++vpos)  {
3149                 pos_type pos = vis2log(vpos);
3150                 float const old_tmpx = tmpx;
3151                 if (main_body > 0 && pos == main_body - 1) {
3152                         LyXLayout const & layout =
3153                                 textclasslist
3154                                 [buffer->params.textclass]
3155                                 [par->layout()];
3156                         LyXFont const lfont = getLabelFont(buffer, par);
3157
3158
3159                         tmpx += p.label_hfill + lyxfont::width(layout.labelsep, lfont);
3160
3161                         if (par->isLineSeparator(main_body - 1))
3162                                 tmpx -= singleWidth(p.bv, par, main_body - 1);
3163                 }
3164
3165                 if (hfillExpansion(buffer, row, pos)) {
3166                         tmpx += singleWidth(p.bv, par, pos);
3167                         if (pos >= main_body)
3168                                 tmpx += p.hfill;
3169                         else
3170                                 tmpx += p.label_hfill;
3171                 }
3172
3173                 else if (par->isSeparator(pos)) {
3174                         tmpx += singleWidth(p.bv, par, pos);
3175                         if (pos >= main_body)
3176                                 tmpx += p.separator;
3177                 } else {
3178                         tmpx += singleWidth(p.bv, par, pos);
3179                 }
3180
3181                 if ((startrow != row || selection.start.pos() <= pos) &&
3182                         (endrow != row || pos < selection.end.pos())) {
3183                         // Here we do not use p.x as p.xo was added to p.x.
3184                         p.pain->fillRectangle(int(old_tmpx), p.yo,
3185                                 int(tmpx - old_tmpx + 1),
3186                                 row->height(), LColor::selection);
3187                 }
3188
3189                 if ((startrow != row && is_rtl) || (endrow != row && !is_rtl)) {
3190                         p.pain->fillRectangle(p.xo + int(tmpx),
3191                                 p.yo, int(p.bv->workWidth() - tmpx),
3192                                 row->height(), LColor::selection);
3193                 }
3194         }
3195 }
3196
3197
3198 void LyXText::paintRowAppendix(DrawRowParams & p)
3199 {
3200         // FIXME: can be just p.width ?
3201         int const ww = p.bv->workWidth();
3202         Paragraph * firstpar = p.row->par();
3203
3204         if (firstpar->params().appendix()) {
3205                 p.pain->line(1, p.yo, 1, p.yo + p.row->height(), LColor::appendixline);
3206                 p.pain->line(ww - 2, p.yo, ww - 2, p.yo + p.row->height(), LColor::appendixline);
3207         }
3208 }
3209
3210
3211 void LyXText::paintRowDepthBar(DrawRowParams & p)
3212 {
3213         Paragraph::depth_type const depth = p.row->par()->getDepth();
3214
3215         if (depth <= 0)
3216                 return;
3217
3218         Paragraph::depth_type prev_depth = 0;
3219         if (p.row->previous())
3220                 prev_depth = p.row->previous()->par()->getDepth();
3221         Paragraph::depth_type next_depth = 0;
3222         if (p.row->next())
3223                 next_depth = p.row->next()->par()->getDepth();
3224
3225         for (Paragraph::depth_type i = 1; i <= depth; ++i) {
3226                 int const x = (LYX_PAPER_MARGIN / 5) * i + p.xo;
3227                 int const h = p.yo + p.row->height() - 1 - (i - next_depth - 1) * 3;
3228
3229                 p.pain->line(x, p.yo, x, h, LColor::depthbar);
3230
3231                 int const w = LYX_PAPER_MARGIN / 5;
3232
3233                 if (i > prev_depth) {
3234                         p.pain->fillRectangle(x, p.yo, w, 2, LColor::depthbar);
3235                 }
3236                 if (i > next_depth) {
3237                         p.pain->fillRectangle(x, h, w, 2, LColor::depthbar);
3238                 }
3239         }
3240 }
3241
3242
3243 int LyXText::getLengthMarkerHeight(BufferView * bv, VSpace const & vsp) const
3244 {
3245         int const arrow_size = 4;
3246         int const space_size = int(vsp.inPixels(bv));
3247
3248         if (vsp.kind() != VSpace::LENGTH) {
3249                 return space_size;
3250         }
3251
3252         LyXFont font;
3253         font.decSize();
3254         int const min_size = max(3 * arrow_size,
3255                                       lyxfont::maxAscent(font)
3256                                       + lyxfont::maxDescent(font));
3257
3258         if (vsp.length().len().value() < 0.0)
3259                 return min_size;
3260         else
3261                 return max(min_size, space_size);
3262 }
3263
3264
3265 int LyXText::drawLengthMarker(DrawRowParams & p, string const & prefix,
3266                               VSpace const & vsp, int start)
3267 {
3268         int const arrow_size = 4;
3269         int const size = getLengthMarkerHeight(p.bv, vsp);
3270         int const end = start + size;
3271
3272         // the label to display (if any)
3273         string str;
3274         // y-values for top arrow
3275         int ty1, ty2;
3276         // y-values for bottom arrow
3277         int by1, by2;
3278         switch (vsp.kind()) {
3279         case VSpace::LENGTH:
3280         {
3281                 str = prefix + " (" + vsp.asLyXCommand() + ")";
3282                 // adding or removing space
3283                 bool const added = !(vsp.length().len().value() < 0.0);
3284                 ty1 = added ? (start + arrow_size) : start;
3285                 ty2 = added ? start : (start + arrow_size);
3286                 by1 = added ? (end - arrow_size) : end;
3287                 by2 = added ? end : (end - arrow_size);
3288                 break;
3289         }
3290         case VSpace:: VFILL:
3291                 str = prefix + " (vertical fill)";
3292                 ty1 = ty2 = start;
3293                 by1 = by2 = end;
3294                 break;
3295         default:
3296                 // nothing to draw here
3297                 return size;
3298         }
3299
3300         int const leftx = p.xo + leftMargin(p.bv, p.row);
3301         int const midx = leftx + arrow_size;
3302         int const rightx = midx + arrow_size;
3303
3304         // first the string
3305         int w = 0;
3306         int a = 0;
3307         int d = 0;
3308
3309         LyXFont font;
3310         font.setColor(LColor::added_space).decSize();
3311         lyxfont::rectText(str, font, w, a, d);
3312
3313         p.pain->rectText(leftx + 2 * arrow_size + 5,
3314                          start + ((end - start) / 2) + d,
3315                          str, font,
3316                          backgroundColor(),
3317                          backgroundColor());
3318
3319         // top arrow
3320         p.pain->line(leftx, ty1, midx, ty2, LColor::added_space);
3321         p.pain->line(midx, ty2, rightx, ty1, LColor::added_space);
3322
3323         // bottom arrow
3324         p.pain->line(leftx, by1, midx, by2, LColor::added_space);
3325         p.pain->line(midx, by2, rightx, by1, LColor::added_space);
3326
3327         // joining line
3328         p.pain->line(midx, ty2, midx, by2, LColor::added_space);
3329
3330         return size;
3331 }
3332
3333
3334 void LyXText::paintFirstRow(DrawRowParams & p)
3335 {
3336         Paragraph * par = p.row->par();
3337         ParagraphParameters const & parparams = par->params();
3338
3339         // start of appendix?
3340         if (parparams.startOfAppendix()) {
3341                 p.pain->line(1, p.yo, p.width - 2, p.yo, LColor::appendixline);
3342         }
3343
3344         int y_top = 0;
3345
3346         // think about the margins
3347         if (!p.row->previous() && bv_owner)
3348                 y_top += LYX_PAPER_MARGIN;
3349
3350         // draw a top pagebreak
3351         if (parparams.pagebreakTop()) {
3352                 int const y = p.yo + y_top + 2*defaultHeight();
3353                 p.pain->line(p.xo, y, p.xo + p.width, y,
3354                         LColor::pagebreak, Painter::line_onoffdash);
3355
3356                 int w = 0;
3357                 int a = 0;
3358                 int d = 0;
3359
3360                 LyXFont pb_font;
3361                 pb_font.setColor(LColor::pagebreak).decSize();
3362                 lyxfont::rectText(_("Page Break (top)"), pb_font, w, a, d);
3363                 p.pain->rectText((p.width - w)/2, y + d,
3364                               _("Page Break (top)"), pb_font,
3365                               backgroundColor(),
3366                               backgroundColor());
3367                 y_top += 3 * defaultHeight();
3368         }
3369
3370         // draw the additional space if needed:
3371         y_top += drawLengthMarker(p, _("Space above"),
3372                                   parparams.spaceTop(), p.yo + y_top);
3373
3374         Buffer const * buffer = p.bv->buffer();
3375
3376         LyXTextClass const & tclass = textclasslist[buffer->params.textclass];
3377         LyXLayout const & layout = tclass[par->layout()];
3378
3379         // think about the parskip
3380         // some parskips VERY EASY IMPLEMENTATION
3381         if (buffer->params.paragraph_separation == BufferParams::PARSEP_SKIP) {
3382                 if (par->previous()) {
3383                         if (layout.latextype == LATEX_PARAGRAPH
3384                                 && !par->getDepth()) {
3385                                 y_top += buffer->params.getDefSkip().inPixels(p.bv);
3386                         } else {
3387                                 LyXLayout const & playout =
3388                                         tclass[par->previous()->layout()];
3389                                 if (playout.latextype == LATEX_PARAGRAPH
3390                                         && !par->previous()->getDepth()) {
3391                                         // is it right to use defskip here, too? (AS)
3392                                         y_top += buffer->params.getDefSkip().inPixels(p.bv);
3393                                 }
3394                         }
3395                 }
3396         }
3397
3398         int const ww = p.bv->workWidth();
3399
3400         // draw a top line
3401         if (parparams.lineTop()) {
3402                 LyXFont font(LyXFont::ALL_SANE);
3403                 int const asc = lyxfont::ascent('x', getFont(buffer, par, 0));
3404
3405                 y_top += asc;
3406
3407                 int const w = (inset_owner ?  inset_owner->width(p.bv, font) : ww);
3408                 int const xp = static_cast<int>(inset_owner ? p.xo : 0);
3409                 p.pain->line(xp, p.yo + y_top, xp + w, p.yo + y_top,
3410                         LColor::topline, Painter::line_solid,
3411                         Painter::line_thick);
3412
3413                 y_top += asc;
3414         }
3415
3416         bool const is_rtl = p.row->par()->isRightToLeftPar(p.bv->buffer()->params);
3417
3418         // should we print a label?
3419         if (layout.labeltype >= LABEL_STATIC
3420             && (layout.labeltype != LABEL_STATIC
3421                 || layout.latextype != LATEX_ENVIRONMENT
3422                 || par->isFirstInSequence())) {
3423
3424                 LyXFont font = getLabelFont(buffer, par);
3425                 if (!par->getLabelstring().empty()) {
3426                         float x = p.x;
3427                         string const str = par->getLabelstring();
3428
3429                         // this is special code for the chapter layout. This is
3430                         // printed in an extra row and has a pagebreak at
3431                         // the top.
3432                         if (layout.labeltype == LABEL_COUNTER_CHAPTER) {
3433                                 if (buffer->params.secnumdepth >= 0) {
3434                                         float spacing_val = 1.0;
3435                                         if (!parparams.spacing().isDefault()) {
3436                                                 spacing_val = parparams.spacing().getValue();
3437                                         } else {
3438                                                 spacing_val = buffer->params.spacing.getValue();
3439                                         }
3440
3441                                         int const maxdesc =
3442                                                 int(lyxfont::maxDescent(font) * layout.spacing.getValue() * spacing_val)
3443                                                 + int(layout.parsep) * defaultHeight();
3444
3445                                         if (is_rtl) {
3446                                                 x = ww - leftMargin(p.bv, p.row) -
3447                                                         lyxfont::width(str, font);
3448                                         }
3449
3450                                         p.pain->text(int(x),
3451                                                 p.yo + p.row->baseline() -
3452                                                 p.row->ascent_of_text() - maxdesc,
3453                                                 str, font);
3454                                 }
3455                         } else {
3456                                 if (is_rtl) {
3457                                         x = ww - leftMargin(p.bv, p.row)
3458                                                 + lyxfont::width(layout.labelsep, font);
3459                                 } else {
3460                                         x = p.x - lyxfont::width(layout.labelsep, font)
3461                                                 - lyxfont::width(str, font);
3462                                 }
3463
3464                                 p.pain->text(int(x), p.yo + p.row->baseline(), str, font);
3465                         }
3466                 }
3467         // the labels at the top of an environment.
3468         // More or less for bibliography
3469         } else if (par->isFirstInSequence() &&
3470                 (layout.labeltype == LABEL_TOP_ENVIRONMENT ||
3471                 layout.labeltype == LABEL_BIBLIO ||
3472                 layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)) {
3473                 LyXFont font = getLabelFont(buffer, par);
3474                 if (!par->getLabelstring().empty()) {
3475                         string const str = par->getLabelstring();
3476                         float spacing_val = 1.0;
3477                         if (!parparams.spacing().isDefault()) {
3478                                 spacing_val = parparams.spacing().getValue();
3479                         } else {
3480                                 spacing_val = buffer->params.spacing.getValue();
3481                         }
3482
3483                         int maxdesc =
3484                                 int(lyxfont::maxDescent(font) * layout.spacing.getValue() * spacing_val
3485                                 + (layout.labelbottomsep * defaultHeight()));
3486
3487                         float x = p.x;
3488                         if (layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT) {
3489                                 x = ((is_rtl ? leftMargin(p.bv, p.row) : p.x)
3490                                          + ww - rightMargin(buffer, p.row)) / 2;
3491                                 x -= lyxfont::width(str, font) / 2;
3492                         } else if (is_rtl) {
3493                                 x = ww - leftMargin(p.bv, p.row) -
3494                                         lyxfont::width(str, font);
3495                         }
3496                         p.pain->text(int(x), p.yo + p.row->baseline()
3497                                   - p.row->ascent_of_text() - maxdesc,
3498                                   str, font);
3499                 }
3500         }
3501
3502         if (layout.labeltype == LABEL_BIBLIO && par->bibkey) {
3503                 LyXFont font = getLayoutFont(buffer, par);
3504                 float x;
3505                 if (is_rtl) {
3506                         x = ww - leftMargin(p.bv, p.row)
3507                                 + lyxfont::width(layout.labelsep, font);
3508                 } else {
3509                         x = p.x - lyxfont::width(layout.labelsep, font)
3510                                 - par->bibkey->width(p.bv, font);
3511                 }
3512                 par->bibkey->draw(p.bv, font, p.yo + p.row->baseline(), x, p.cleared);
3513         }
3514 }
3515
3516
3517 void LyXText::paintLastRow(DrawRowParams & p)
3518 {
3519         Paragraph * par = p.row->par();
3520         ParagraphParameters const & parparams = par->params();
3521         int y_bottom = p.row->height() - 1;
3522
3523         // think about the margins
3524         if (!p.row->next() && bv_owner)
3525                 y_bottom -= LYX_PAPER_MARGIN;
3526
3527         int const ww = p.bv->workWidth();
3528
3529         // draw a bottom pagebreak
3530         if (parparams.pagebreakBottom()) {
3531                 LyXFont pb_font;
3532                 pb_font.setColor(LColor::pagebreak).decSize();
3533                 int const y = p.yo + y_bottom - 2 * defaultHeight();
3534
3535                 p.pain->line(p.xo, y, p.xo + p.width, y, LColor::pagebreak,
3536                              Painter::line_onoffdash);
3537
3538                 int w = 0;
3539                 int a = 0;
3540                 int d = 0;
3541                 lyxfont::rectText(_("Page Break (bottom)"), pb_font, w, a, d);
3542                 p.pain->rectText((ww - w) / 2, y + d,
3543                         _("Page Break (bottom)"),
3544                         pb_font, backgroundColor(), backgroundColor());
3545
3546                 y_bottom -= 3 * defaultHeight();
3547         }
3548
3549         // draw the additional space if needed:
3550         int const height =  getLengthMarkerHeight(p.bv,
3551                                                   parparams.spaceBottom());
3552         y_bottom -= drawLengthMarker(p, _("Space below"),
3553                                      parparams.spaceBottom(),
3554                                      p.yo + y_bottom - height);
3555
3556         Buffer const * buffer = p.bv->buffer();
3557
3558         // draw a bottom line
3559         if (parparams.lineBottom()) {
3560                 LyXFont font(LyXFont::ALL_SANE);
3561                 int const asc = lyxfont::ascent('x',
3562                         getFont(buffer, par,
3563                         max(pos_type(0), par->size() - 1)));
3564
3565                 y_bottom -= asc;
3566
3567                 int const w = (inset_owner ?  inset_owner->width(p.bv, font) : ww);
3568                 int const xp = static_cast<int>(inset_owner ? p.xo : 0);
3569                 int const y = p.yo + y_bottom;
3570                 p.pain->line(xp, y, xp + w, y, LColor::topline, Painter::line_solid,
3571                           Painter::line_thick);
3572
3573                 y_bottom -= asc;
3574         }
3575
3576         bool const is_rtl = p.row->par()->isRightToLeftPar(p.bv->buffer()->params);
3577         int const endlabel = par->getEndLabel(buffer->params);
3578
3579         // draw an endlabel
3580         switch (endlabel) {
3581         case END_LABEL_BOX:
3582         case END_LABEL_FILLED_BOX:
3583         {
3584                 LyXFont const font = getLabelFont(buffer, par);
3585                 int const size = int(0.75 * lyxfont::maxAscent(font));
3586                 int const y = (p.yo + p.row->baseline()) - size;
3587                 int x = is_rtl ? LYX_PAPER_MARGIN : ww - LYX_PAPER_MARGIN - size;
3588
3589                 if (p.row->fill() <= size)
3590                         x += (size - p.row->fill() + 1) * (is_rtl ? -1 : 1);
3591
3592                 if (endlabel == END_LABEL_BOX) {
3593                         p.pain->rectangle(x, y, size, size, LColor::eolmarker);
3594                 } else {
3595                         p.pain->fillRectangle(x, y, size, size,
3596                                               LColor::eolmarker);
3597                 }
3598                 break;
3599         }
3600         case END_LABEL_STATIC:
3601         {
3602                 LyXFont font(LyXFont::ALL_SANE);
3603                 string const & layout = par->layout();
3604                 string const str = textclasslist[buffer->params.textclass][layout].endlabelstring();
3605                 font = getLabelFont(buffer, par);
3606                 int const x = is_rtl ?
3607                         int(p.x) - lyxfont::width(str, font)
3608                         : ww - rightMargin(buffer, p.row) - p.row->fill();
3609                 p.pain->text(x, p.yo + p.row->baseline(), str, font);
3610                 break;
3611         }
3612         case END_LABEL_NO_LABEL:
3613                 break;
3614         }
3615 }
3616
3617 void LyXText::paintRowText(DrawRowParams & p)
3618 {
3619         Paragraph * par = p.row->par();
3620         Buffer const * buffer = p.bv->buffer();
3621
3622         pos_type const last = rowLastPrintable(p.row);
3623         pos_type main_body =
3624                 beginningOfMainBody(buffer, par);
3625         if (main_body > 0 &&
3626                 (main_body - 1 > last ||
3627                 !par->isLineSeparator(main_body - 1))) {
3628                 main_body = 0;
3629         }
3630
3631         LyXLayout const & layout =
3632                 textclasslist[buffer->params.textclass][par->layout()];
3633
3634         pos_type vpos = p.row->pos();
3635         while (vpos <= last) {
3636                 if (p.x > p.bv->workWidth())
3637                         break;
3638                 pos_type pos = vis2log(vpos);
3639                 if (p.x + singleWidth(p.bv, par, pos) < 0) {
3640                         p.x += singleWidth(p.bv, par, pos);
3641                         ++vpos;
3642                         continue;
3643                 }
3644                 if (main_body > 0 && pos == main_body - 1) {
3645                         int const lwidth = lyxfont::width(layout.labelsep,
3646                                 getLabelFont(buffer, par));
3647
3648                         p.x += p.label_hfill + lwidth
3649                                 - singleWidth(p.bv, par, main_body - 1);
3650                 }
3651
3652                 if (par->isHfill(pos)) {
3653                         p.x += 1;
3654
3655                         int const y0 = p.yo + p.row->baseline();
3656                         int const y1 = y0 - defaultHeight() / 2;
3657
3658                         p.pain->line(int(p.x), y1, int(p.x), y0,
3659                                      LColor::added_space);
3660
3661                         if (hfillExpansion(buffer, p.row, pos)) {
3662                                 int const y2 = (y0 + y1) / 2;
3663
3664                                 if (pos >= main_body) {
3665                                         p.pain->line(int(p.x), y2,
3666                                                   int(p.x + p.hfill), y2,
3667                                                   LColor::added_space,
3668                                                   Painter::line_onoffdash);
3669                                         p.x += p.hfill;
3670                                 } else {
3671                                         p.pain->line(int(p.x), y2,
3672                                                   int(p.x + p.label_hfill), y2,
3673                                                   LColor::added_space,
3674                                                   Painter::line_onoffdash);
3675                                         p.x += p.label_hfill;
3676                                 }
3677                                 p.pain->line(int(p.x), y1,
3678                                              int(p.x), y0,
3679                                              LColor::added_space);
3680                         }
3681                         p.x += 2;
3682                         ++vpos;
3683                 } else if (par->isSeparator(pos)) {
3684                         p.x += singleWidth(p.bv, par, pos);
3685                         if (pos >= main_body)
3686                                 p.x += p.separator;
3687                         ++vpos;
3688                 } else {
3689                         if (!draw(p, vpos))
3690                                 break;
3691                 }
3692         }
3693 }
3694
3695
3696 void LyXText::getVisibleRow(BufferView * bv, int y_offset, int x_offset,
3697                             Row * row, int y, bool cleared)
3698 {
3699         if (row->height() <= 0) {
3700                 lyxerr << "LYX_ERROR: row.height: "
3701                        << row->height() << endl;
3702                 return;
3703         }
3704
3705         DrawRowParams p;
3706
3707         // set up drawing parameters
3708         p.bv = bv;
3709         p.pain = &bv->painter();
3710         p.row = row;
3711         p.xo = x_offset;
3712         p.yo = y_offset;
3713         prepareToPrint(bv, row, p.x, p.separator, p.hfill, p.label_hfill);
3714         if (inset_owner && (p.x < 0))
3715                 p.x = 0;
3716         p.x += p.xo;
3717         p.y = y;
3718         p.width = inset_owner ? inset_owner->textWidth(bv, true) : bv->workWidth();
3719         p.cleared = cleared;
3720
3721         // start painting
3722
3723         // clear to background if necessary
3724         p.cleared = paintRowBackground(p);
3725
3726         // paint the selection background
3727         if (selection.set()) {
3728                 paintRowSelection(p);
3729         }
3730
3731         // vertical lines for appendix
3732         paintRowAppendix(p);
3733
3734         // environment depth brackets
3735         paintRowDepthBar(p);
3736
3737         // draw any stuff wanted for a first row of a paragraph
3738         if (!row->pos()) {
3739                 paintFirstRow(p);
3740         }
3741
3742         // draw any stuff wanted for the last row of a paragraph
3743         if (!row->next() || (row->next()->par() != row->par())) {
3744                 paintLastRow(p);
3745         }
3746
3747         // paint text
3748         paintRowText(p);
3749 }
3750
3751
3752 int LyXText::defaultHeight() const
3753 {
3754         LyXFont font(LyXFont::ALL_SANE);
3755         return int(lyxfont::maxAscent(font) + lyxfont::maxDescent(font) * 1.5);
3756 }
3757
3758
3759 /* returns the column near the specified x-coordinate of the row
3760 * x is set to the real beginning of this column  */
3761 pos_type
3762 LyXText::getColumnNearX(BufferView * bview, Row * row, int & x,
3763                         bool & boundary) const
3764 {
3765         float tmpx = 0.0;
3766         float fill_separator;
3767         float fill_hfill;
3768         float fill_label_hfill;
3769
3770         prepareToPrint(bview, row, tmpx, fill_separator,
3771                        fill_hfill, fill_label_hfill);
3772
3773         pos_type vc = row->pos();
3774         pos_type last = rowLastPrintable(row);
3775         pos_type c = 0;
3776         LyXLayout const & layout =
3777                 textclasslist[bview->buffer()->params.textclass][
3778                                     row->par()->layout()];
3779         bool left_side = false;
3780
3781         pos_type main_body = beginningOfMainBody(bview->buffer(), row->par());
3782         float last_tmpx = tmpx;
3783
3784         if (main_body > 0 &&
3785             (main_body - 1 > last ||
3786              !row->par()->isLineSeparator(main_body - 1)))
3787                 main_body = 0;
3788
3789         while (vc <= last && tmpx <= x) {
3790                 c = vis2log(vc);
3791                 last_tmpx = tmpx;
3792                 if (main_body > 0 && c == main_body-1) {
3793                         tmpx += fill_label_hfill +
3794                                 lyxfont::width(layout.labelsep,
3795                                                getLabelFont(bview->buffer(), row->par()));
3796                         if (row->par()->isLineSeparator(main_body - 1))
3797                                 tmpx -= singleWidth(bview, row->par(), main_body-1);
3798                 }
3799
3800                 if (hfillExpansion(bview->buffer(), row, c)) {
3801                         x += singleWidth(bview, row->par(), c);
3802                         if (c >= main_body)
3803                                 tmpx += fill_hfill;
3804                         else
3805                                 tmpx += fill_label_hfill;
3806                 }
3807                 else if (row->par()->isSeparator(c)) {
3808                         tmpx += singleWidth(bview, row->par(), c);
3809                         if (c >= main_body)
3810                                 tmpx+= fill_separator;
3811                 } else
3812                         tmpx += singleWidth(bview, row->par(), c);
3813                 ++vc;
3814         }
3815
3816         if ((tmpx + last_tmpx) / 2 > x) {
3817                 tmpx = last_tmpx;
3818                 left_side = true;
3819         }
3820
3821         if (vc > last + 1)  // This shouldn't happen.
3822                 vc = last + 1;
3823
3824         boundary = false;
3825         bool const lastrow = lyxrc.rtl_support // This is not needed, but gives
3826                                          // some speedup if rtl_support=false
3827                 && (!row->next() || row->next()->par() != row->par());
3828         bool const rtl = (lastrow)
3829                 ? row->par()->isRightToLeftPar(bview->buffer()->params)
3830                 : false; // If lastrow is false, we don't need to compute
3831                          // the value of rtl.
3832
3833         if (row->pos() > last)  // Row is empty?
3834                 c = row->pos();
3835         else if (lastrow &&
3836                  ((rtl &&  left_side && vc == row->pos() && x < tmpx - 5) ||
3837                    (!rtl && !left_side && vc == last + 1   && x > tmpx + 5)))
3838                 c = last + 1;
3839         else if (vc == row->pos()) {
3840                 c = vis2log(vc);
3841                 if (bidi_level(c) % 2 == 1)
3842                         ++c;
3843         } else {
3844                 c = vis2log(vc - 1);
3845                 bool const rtl = (bidi_level(c) % 2 == 1);
3846                 if (left_side == rtl) {
3847                         ++c;
3848                         boundary = isBoundary(bview->buffer(), row->par(), c);
3849                 }
3850         }
3851
3852         if (row->pos() <= last && c > last
3853             && row->par()->isNewline(last)) {
3854                 if (bidi_level(last) % 2 == 0)
3855                         tmpx -= singleWidth(bview, row->par(), last);
3856                 else
3857                         tmpx += singleWidth(bview, row->par(), last);
3858                 c = last;
3859         }
3860
3861         c -= row->pos();
3862         x = int(tmpx);
3863         return c;
3864 }
3865
3866
3867 // returns pointer to a specified row
3868 Row * LyXText::getRow(Paragraph * par, pos_type pos, int & y) const
3869 {
3870         if (!firstrow)
3871                 return 0;
3872
3873         Row * tmprow = firstrow;
3874         y = 0;
3875
3876         // find the first row of the specified paragraph
3877         while (tmprow->next() && tmprow->par() != par) {
3878                 y += tmprow->height();
3879                 tmprow = tmprow->next();
3880         }
3881
3882         // now find the wanted row
3883         while (tmprow->pos() < pos
3884                && tmprow->next()
3885                && tmprow->next()->par() == par
3886                && tmprow->next()->pos() <= pos) {
3887                 y += tmprow->height();
3888                 tmprow = tmprow->next();
3889         }
3890
3891         return tmprow;
3892 }
3893
3894
3895 Row * LyXText::getRowNearY(int & y) const
3896 {
3897 #if 1
3898         // If possible we should optimize this method. (Lgb)
3899         Row * tmprow = firstrow;
3900         int tmpy = 0;
3901
3902         while (tmprow->next() && tmpy + tmprow->height() <= y) {
3903                 tmpy += tmprow->height();
3904                 tmprow = tmprow->next();
3905         }
3906
3907         y = tmpy;   // return the real y
3908
3909         //lyxerr << "returned y = " << y << endl;
3910
3911         return tmprow;
3912 #else
3913         // Search from the current cursor position.
3914
3915         Row * tmprow = cursor.row();
3916         int tmpy = cursor.y() - tmprow->baseline();
3917
3918         lyxerr << "cursor.y() = " << tmpy << endl;
3919         lyxerr << "tmprow->height() = " << tmprow->height() << endl;
3920         lyxerr << "tmprow->baseline() = " << tmprow->baseline() << endl;
3921         lyxerr << "first = " << first << endl;
3922         lyxerr << "y = " << y << endl;
3923
3924         if (y < tmpy) {
3925                 lyxerr << "up" << endl;
3926 #if 0
3927                 while (tmprow && tmpy - tmprow->height() >= y) {
3928                         tmpy -= tmprow->height();
3929                         tmprow = tmprow->previous();
3930                 }
3931 #else
3932                 do {
3933                         tmpy -= tmprow->height();
3934                         tmprow = tmprow->previous();
3935                 } while (tmprow && tmpy - tmprow->height() >= y);
3936 #endif
3937         } else if (y > tmpy) {
3938                 lyxerr << "down" << endl;
3939
3940                 while (tmprow->next() && tmpy + tmprow->height() <= y) {
3941                         tmpy += tmprow->height();
3942                         tmprow = tmprow->next();
3943                 }
3944         } else {
3945                 lyxerr << "equal" << endl;
3946         }
3947
3948         y = tmpy; // return the real y
3949
3950         lyxerr << "returned y = " << y << endl;
3951
3952         return tmprow;
3953
3954 #endif
3955 }
3956
3957
3958 int LyXText::getDepth() const
3959 {
3960         return cursor.par()->getDepth();
3961 }