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