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