]> git.lyx.org Git - lyx.git/blob - src/text.C
Hotfix to move cursor to the right when pressing M-m g x in text mode.
[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    // and if it has not the keepempty flag aktive
1714    if ((cursor.par()->size() <= 0)
1715        && layout.labeltype != LABEL_SENSITIVE
1716            && !layout.keepempty)
1717            return;
1718
1719    setUndo(bview, Undo::FINISH, cursor.par(), cursor.par()->next());
1720
1721    // Always break behind a space
1722    //
1723    // It is better to erase the space (Dekel)
1724    if (cursor.pos() < cursor.par()->size()
1725        && cursor.par()->isLineSeparator(cursor.pos()))
1726            cursor.par()->erase(cursor.pos());
1727            // cursor.pos(cursor.pos() + 1);
1728
1729    // break the paragraph
1730    if (keep_layout)
1731      keep_layout = 2;
1732    else
1733      keep_layout = layout.isEnvironment();
1734    cursor.par()->breakParagraph(bview->buffer()->params, cursor.pos(),
1735                                 keep_layout);
1736
1737    // well this is the caption hack since one caption is really enough
1738    if (layout.labeltype == LABEL_SENSITIVE) {
1739      if (!cursor.pos())
1740              // set to standard-layout
1741              cursor.par()->applyLayout(tclass.defaultLayoutName());
1742      else
1743              // set to standard-layout
1744              cursor.par()->next()->applyLayout(tclass.defaultLayoutName());
1745    }
1746
1747    /* if the cursor is at the beginning of a row without prior newline,
1748     * move one row up!
1749     * This touches only the screen-update. Otherwise we would may have
1750     * an empty row on the screen */
1751    if (cursor.pos() && !cursor.row()->par()->isNewline(cursor.row()->pos() - 1)
1752        && cursor.row()->pos() == cursor.pos())
1753    {
1754            cursorLeft(bview);
1755    }
1756
1757    status(bview, LyXText::NEED_MORE_REFRESH);
1758    refresh_row = cursor.row();
1759    refresh_y = cursor.y() - cursor.row()->baseline();
1760
1761    // Do not forget the special right address boxes
1762    if (layout.margintype == MARGIN_RIGHT_ADDRESS_BOX) {
1763       while (refresh_row->previous() &&
1764              refresh_row->previous()->par() == refresh_row->par()) {
1765               refresh_row = refresh_row->previous();
1766               refresh_y -= refresh_row->height();
1767       }
1768    }
1769    removeParagraph(cursor.row());
1770
1771    // set the dimensions of the cursor row
1772    cursor.row()->fill(fill(bview, cursor.row(), workWidth(bview)));
1773
1774    setHeightOfRow(bview, cursor.row());
1775
1776    while (cursor.par()->next()->size()
1777           && cursor.par()->next()->isNewline(0))
1778            cursor.par()->next()->erase(0);
1779
1780    insertParagraph(bview, cursor.par()->next(), cursor.row());
1781
1782    updateCounters(bview, cursor.row()->previous());
1783
1784    /* This check is necessary. Otherwise the new empty paragraph will
1785     * be deleted automatically. And it is more friendly for the user! */
1786    if (cursor.pos() || layout.keepempty)
1787            setCursor(bview, cursor.par()->next(), 0);
1788    else
1789            setCursor(bview, cursor.par(), 0);
1790
1791    if (cursor.row()->next())
1792            breakAgain(bview, cursor.row()->next());
1793
1794    need_break_row = 0;
1795 }
1796
1797
1798 // Just a macro to make some thing easier.
1799 void LyXText::redoParagraph(BufferView * bview) const
1800 {
1801         clearSelection();
1802         redoParagraphs(bview, cursor, cursor.par()->next());
1803         setCursorIntern(bview, cursor.par(), cursor.pos());
1804 }
1805
1806
1807 /* insert a character, moves all the following breaks in the
1808  * same Paragraph one to the right and make a rebreak */
1809 void LyXText::insertChar(BufferView * bview, char c)
1810 {
1811         setUndo(bview, Undo::INSERT, cursor.par(), cursor.par()->next());
1812
1813         // When the free-spacing option is set for the current layout,
1814         // disable the double-space checking
1815
1816         bool const freeSpacing =
1817                 textclasslist[bview->buffer()->params.textclass][cursor.row()->par()->layout()].free_spacing ||
1818                 cursor.row()->par()->isFreeSpacing();
1819
1820         if (lyxrc.auto_number) {
1821                 static string const number_operators = "+-/*";
1822                 static string const number_unary_operators = "+-";
1823                 static string const number_seperators = ".,:";
1824
1825                 if (current_font.number() == LyXFont::ON) {
1826                         if (!IsDigit(c) && !contains(number_operators, c) &&
1827                             !(contains(number_seperators, c) &&
1828                               cursor.pos() >= 1 &&
1829                               cursor.pos() < cursor.par()->size() &&
1830                               getFont(bview->buffer(),
1831                                       cursor.par(),
1832                                       cursor.pos()).number() == LyXFont::ON &&
1833                               getFont(bview->buffer(),
1834                                       cursor.par(),
1835                                       cursor.pos() - 1).number() == LyXFont::ON)
1836                            )
1837                                 number(bview); // Set current_font.number to OFF
1838                 } else if (IsDigit(c) &&
1839                            real_current_font.isVisibleRightToLeft()) {
1840                         number(bview); // Set current_font.number to ON
1841
1842                         if (cursor.pos() > 0) {
1843                                 char const c = cursor.par()->getChar(cursor.pos() - 1);
1844                                 if (contains(number_unary_operators, c) &&
1845                                     (cursor.pos() == 1 ||
1846                                      cursor.par()->isSeparator(cursor.pos() - 2) ||
1847                                      cursor.par()->isNewline(cursor.pos() - 2))
1848                                   ) {
1849                                         setCharFont(bview->buffer(),
1850                                                     cursor.par(),
1851                                                     cursor.pos() - 1,
1852                                                     current_font);
1853                                 } else if (contains(number_seperators, c) &&
1854                                            cursor.pos() >= 2 &&
1855                                            getFont(bview->buffer(),
1856                                                    cursor.par(),
1857                                                    cursor.pos() - 2).number() == LyXFont::ON) {
1858                                         setCharFont(bview->buffer(),
1859                                                     cursor.par(),
1860                                                     cursor.pos() - 1,
1861                                                     current_font);
1862                                 }
1863                         }
1864                 }
1865         }
1866
1867
1868         /* First check, if there will be two blanks together or a blank at
1869           the beginning of a paragraph.
1870           I decided to handle blanks like normal characters, the main
1871           difference are the special checks when calculating the row.fill
1872           (blank does not count at the end of a row) and the check here */
1873
1874         // The bug is triggered when we type in a description environment:
1875         // The current_font is not changed when we go from label to main text
1876         // and it should (along with realtmpfont) when we type the space.
1877         // CHECK There is a bug here! (Asger)
1878
1879         LyXFont realtmpfont = real_current_font;
1880         LyXFont rawtmpfont = current_font;  /* store the current font.
1881                                      * This is because of the use
1882                                      * of cursor movements. The moving
1883                                      * cursor would refresh the
1884                                      * current font */
1885
1886         // Get the font that is used to calculate the baselineskip
1887         pos_type const lastpos = cursor.par()->size();
1888         LyXFont rawparfont =
1889                 cursor.par()->getFontSettings(bview->buffer()->params,
1890                                               lastpos - 1);
1891
1892         bool jumped_over_space = false;
1893
1894         if (!freeSpacing && IsLineSeparatorChar(c)) {
1895                 if ((cursor.pos() > 0
1896                      && cursor.par()->isLineSeparator(cursor.pos() - 1))
1897                     || (cursor.pos() > 0
1898                         && cursor.par()->isNewline(cursor.pos() - 1))
1899                     || (cursor.pos() == 0)) {
1900                         static bool sent_space_message = false;
1901                         if (!sent_space_message) {
1902                                 if (cursor.pos() == 0)
1903                                         bview->owner()->message(_("You cannot insert a space at the beginning of a paragraph.  Please read the Tutorial."));
1904                                 else
1905                                         bview->owner()->message(_("You cannot type two spaces this way.  Please read the Tutorial."));
1906                                 sent_space_message = true;
1907                         }
1908                         charInserted();
1909                         return;
1910                 }
1911         } else if (IsNewlineChar(c)) {
1912                 if (cursor.pos() <= beginningOfMainBody(bview->buffer(),
1913                                                         cursor.par()))
1914                 {
1915                         charInserted();
1916                         return;
1917                 }
1918                 /* No newline at first position
1919                  * of a paragraph or behind labels.
1920                  * TeX does not allow that */
1921
1922                 if (cursor.pos() < cursor.par()->size() &&
1923                     cursor.par()->isLineSeparator(cursor.pos()))
1924                         // newline always after a blank!
1925                         cursorRight(bview);
1926                 cursor.row()->fill(-1);        // to force a new break
1927         }
1928
1929         // the display inset stuff
1930         if (cursor.row()->par()->isInset(cursor.row()->pos())) {
1931                 Inset * inset = cursor.row()->par()->getInset(cursor.row()->pos());
1932                 if (inset && (inset->display() || inset->needFullRow())) {
1933                         // force a new break
1934                         cursor.row()->fill(-1); // to force a new break
1935                 }
1936         }
1937
1938         // get the cursor row fist
1939         Row * row = cursor.row();
1940         int y = cursor.y() - row->baseline();
1941         if (c != Paragraph::META_INSET) /* Here case LyXText::InsertInset
1942                                          * already insertet the character */
1943                 cursor.par()->insertChar(cursor.pos(), c);
1944         setCharFont(bview->buffer(), cursor.par(), cursor.pos(), rawtmpfont);
1945
1946         if (!jumped_over_space) {
1947                 // refresh the positions
1948                 Row * tmprow = row;
1949                 while (tmprow->next() && tmprow->next()->par() == row->par()) {
1950                         tmprow = tmprow->next();
1951                         tmprow->pos(tmprow->pos() + 1);
1952                 }
1953         }
1954
1955         // Is there a break one row above
1956         if (row->previous() && row->previous()->par() == row->par()
1957             && (cursor.par()->isLineSeparator(cursor.pos())
1958                 || cursor.par()->isNewline(cursor.pos())
1959                 || ((cursor.pos() < cursor.par()->size()) &&
1960                     cursor.par()->isInset(cursor.pos()+1))
1961                 || cursor.row()->fill() == -1))
1962         {
1963                 pos_type z = nextBreakPoint(bview,
1964                                                            row->previous(),
1965                                                            workWidth(bview));
1966                 if (z >= row->pos()) {
1967                         row->pos(z + 1);
1968
1969                         // set the dimensions of the row above
1970                         row->previous()->fill(fill(bview,
1971                                                    row->previous(),
1972                                                    workWidth(bview)));
1973
1974                         setHeightOfRow(bview, row->previous());
1975
1976                         y -= row->previous()->height();
1977                         refresh_y = y;
1978                         refresh_row = row->previous();
1979                         status(bview, LyXText::NEED_MORE_REFRESH);
1980
1981                         breakAgainOneRow(bview, row);
1982
1983                         current_font = rawtmpfont;
1984                         real_current_font = realtmpfont;
1985                         setCursor(bview, cursor.par(), cursor.pos() + 1,
1986                                   false, cursor.boundary());
1987                         // cursor MUST be in row now.
1988
1989                         if (row->next() && row->next()->par() == row->par())
1990                                 need_break_row = row->next();
1991                         else
1992                                 need_break_row = 0;
1993
1994                         // check, wether the last characters font has changed.
1995                         if (cursor.pos() && cursor.pos() == cursor.par()->size()
1996                             && rawparfont != rawtmpfont)
1997                                 redoHeightOfParagraph(bview, cursor);
1998
1999                         charInserted();
2000                         return;
2001                 }
2002         }
2003
2004         // recalculate the fill of the row
2005         if (row->fill() >= 0)  /* needed because a newline
2006                                 * will set fill to -1. Otherwise
2007                                 * we would not get a rebreak! */
2008                 row->fill(fill(bview, row, workWidth(bview)));
2009         if (c == Paragraph::META_INSET || row->fill() < 0) {
2010                 refresh_y = y;
2011                 refresh_row = row;
2012                 refresh_x = cursor.x();
2013                 refresh_pos = cursor.pos();
2014                 status(bview, LyXText::NEED_MORE_REFRESH);
2015                 breakAgainOneRow(bview, row);
2016                 // will the cursor be in another row now?
2017                 if (rowLast(row) <= cursor.pos() + 1 && row->next()) {
2018                         if (row->next() && row->next()->par() == row->par())
2019                                 // this should always be true
2020                                 row = row->next();
2021                         breakAgainOneRow(bview, row);
2022                 }
2023                 current_font = rawtmpfont;
2024                 real_current_font = realtmpfont;
2025
2026                 setCursor(bview, cursor.par(), cursor.pos() + 1, false,
2027                           cursor.boundary());
2028                 if (isBoundary(bview->buffer(), cursor.par(), cursor.pos())
2029                     != cursor.boundary())
2030                         setCursor(bview, cursor.par(), cursor.pos(), false,
2031                           !cursor.boundary());
2032                 if (row->next() && row->next()->par() == row->par())
2033                         need_break_row = row->next();
2034                 else
2035                         need_break_row = 0;
2036         } else {
2037                 refresh_y = y;
2038                 refresh_x = cursor.x();
2039                 refresh_row = row;
2040                 refresh_pos = cursor.pos();
2041
2042                 int const tmpheight = row->height();
2043                 setHeightOfRow(bview, row);
2044                 if (tmpheight == row->height())
2045                         status(bview, LyXText::NEED_VERY_LITTLE_REFRESH);
2046                 else
2047                         status(bview, LyXText::NEED_MORE_REFRESH);
2048
2049                 current_font = rawtmpfont;
2050                 real_current_font = realtmpfont;
2051                 setCursor(bview, cursor.par(), cursor.pos() + 1, false,
2052                           cursor.boundary());
2053         }
2054
2055         // check, wether the last characters font has changed.
2056         if (cursor.pos() && cursor.pos() == cursor.par()->size()
2057             && rawparfont != rawtmpfont) {
2058                 redoHeightOfParagraph(bview, cursor);
2059         } else {
2060                 // now the special right address boxes
2061                 if (textclasslist[bview->buffer()->params.textclass][cursor.par()->layout()].margintype
2062                     == MARGIN_RIGHT_ADDRESS_BOX) {
2063                         redoDrawingOfParagraph(bview, cursor);
2064                 }
2065         }
2066
2067         charInserted();
2068 }
2069
2070
2071 void LyXText::charInserted()
2072 {
2073         // Here we could call FinishUndo for every 20 characters inserted.
2074         // This is from my experience how emacs does it.
2075         static unsigned int counter;
2076         if (counter < 20) {
2077                 ++counter;
2078         } else {
2079                 finishUndo();
2080                 counter = 0;
2081         }
2082 }
2083
2084
2085 void LyXText::prepareToPrint(BufferView * bview,
2086                              Row * row, float & x,
2087                              float & fill_separator,
2088                              float & fill_hfill,
2089                              float & fill_label_hfill,
2090                              bool bidi) const
2091 {
2092         float nlh;
2093         float ns;
2094
2095         float w = row->fill();
2096         fill_hfill = 0;
2097         fill_label_hfill = 0;
2098         fill_separator = 0;
2099         fill_label_hfill = 0;
2100
2101         bool const is_rtl =
2102                 row->par()->isRightToLeftPar(bview->buffer()->params);
2103         if (is_rtl) {
2104                 x = (workWidth(bview) > 0)
2105                         ? rightMargin(bview->buffer(), row) : 0;
2106         } else
2107                 x = (workWidth(bview) > 0)
2108                         ? leftMargin(bview, row) : 0;
2109
2110         // is there a manual margin with a manual label
2111         LyXTextClass const & tclass = textclasslist[bview->buffer()->params.textclass];
2112         LyXLayout const & layout = tclass[row->par()->layout()];
2113
2114         if (layout.margintype == MARGIN_MANUAL
2115             && layout.labeltype == LABEL_MANUAL) {
2116                 // one more since labels are left aligned
2117                 nlh = numberOfLabelHfills(bview->buffer(), row) + 1;
2118                 if (nlh && !row->par()->getLabelWidthString().empty()) {
2119                         fill_label_hfill = labelFill(bview, row) / nlh;
2120                 }
2121         }
2122
2123         // are there any hfills in the row?
2124         float const nh = numberOfHfills(bview->buffer(), row);
2125
2126         if (nh) {
2127                 if (w > 0)
2128                         fill_hfill = w / nh;
2129         // we don't have to look at the alignment if it is ALIGN_LEFT and
2130         // if the row is already larger then the permitted width as then
2131         // we force the LEFT_ALIGN'edness!
2132         } else if (static_cast<int>(row->width()) < workWidth(bview)) {
2133                 // is it block, flushleft or flushright?
2134                 // set x how you need it
2135                 int align;
2136                 if (row->par()->params().align() == LYX_ALIGN_LAYOUT) {
2137                         align = layout.align;
2138                 } else {
2139                         align = row->par()->params().align();
2140                 }
2141
2142                 // center displayed insets
2143                 Inset * inset;
2144                 if (row->par()->isInset(row->pos())
2145                     && (inset=row->par()->getInset(row->pos()))
2146                     && (inset->display())) // || (inset->scroll() < 0)))
2147                     align = (inset->lyxCode() == Inset::MATHMACRO_CODE)
2148                         ? LYX_ALIGN_BLOCK : LYX_ALIGN_CENTER;
2149                 // ERT insets should always be LEFT ALIGNED on screen
2150                 inset = row->par()->inInset();
2151                 if (inset && inset->owner() &&
2152                         inset->owner()->lyxCode() == Inset::ERT_CODE)
2153                 {
2154                         align = LYX_ALIGN_LEFT;
2155                 }
2156
2157                 switch (align) {
2158             case LYX_ALIGN_BLOCK:
2159                         ns = numberOfSeparators(bview->buffer(), row);
2160                         if (ns && row->next() && row->next()->par() == row->par() &&
2161                             !(row->next()->par()->isNewline(row->next()->pos() - 1))
2162                             && !(row->next()->par()->isInset(row->next()->pos())
2163                                  && row->next()->par()->getInset(row->next()->pos())
2164                                  && row->next()->par()->getInset(row->next()->pos())->display())
2165                                 )
2166                         {
2167                                 fill_separator = w / ns;
2168                         } else if (is_rtl) {
2169                                 x += w;
2170                         }
2171                         break;
2172             case LYX_ALIGN_RIGHT:
2173                         x += w;
2174                         break;
2175             case LYX_ALIGN_CENTER:
2176                         x += w / 2;
2177                         break;
2178                 }
2179         }
2180         if (!bidi)
2181                 return;
2182
2183         computeBidiTables(bview->buffer(), row);
2184         if (is_rtl) {
2185                 pos_type main_body =
2186                         beginningOfMainBody(bview->buffer(), row->par());
2187                 pos_type last = rowLast(row);
2188
2189                 if (main_body > 0 &&
2190                     (main_body - 1 > last ||
2191                      !row->par()->isLineSeparator(main_body - 1))) {
2192                         x += lyxfont::width(layout.labelsep,
2193                                             getLabelFont(bview->buffer(), row->par()));
2194                         if (main_body - 1 <= last)
2195                                 x += fill_label_hfill;
2196                 }
2197         }
2198 }
2199
2200 /* important for the screen */
2201
2202
2203 /* the cursor set functions have a special mechanism. When they
2204 * realize, that you left an empty paragraph, they will delete it.
2205 * They also delete the corresponding row */
2206
2207 void LyXText::cursorRightOneWord(BufferView * bview) const
2208 {
2209         // treat floats, HFills and Insets as words
2210         LyXCursor tmpcursor = cursor;
2211         // CHECK See comment on top of text.C
2212
2213         if (tmpcursor.pos() == tmpcursor.par()->size()
2214             && tmpcursor.par()->next()) {
2215                         tmpcursor.par(tmpcursor.par()->next());
2216                         tmpcursor.pos(0);
2217         } else {
2218                 int steps = 0;
2219
2220                 // Skip through initial nonword stuff.
2221                 while (tmpcursor.pos() < tmpcursor.par()->size() &&
2222                        ! tmpcursor.par()->isWord(tmpcursor.pos())) {
2223                   //    printf("Current pos1 %d", tmpcursor.pos()) ;
2224                         tmpcursor.pos(tmpcursor.pos() + 1);
2225                         ++steps;
2226                 }
2227                 // Advance through word.
2228                 while (tmpcursor.pos() < tmpcursor.par()->size() &&
2229                         tmpcursor.par()->isWord(tmpcursor.pos())) {
2230                   //     printf("Current pos2 %d", tmpcursor.pos()) ;
2231                         tmpcursor.pos(tmpcursor.pos() + 1);
2232                         ++steps;
2233                 }
2234         }
2235         setCursor(bview, tmpcursor.par(), tmpcursor.pos());
2236 }
2237
2238
2239 void LyXText::cursorTab(BufferView * bview) const
2240 {
2241     LyXCursor tmpcursor = cursor;
2242     while (tmpcursor.pos() < tmpcursor.par()->size()
2243            && !tmpcursor.par()->isNewline(tmpcursor.pos()))
2244         tmpcursor.pos(tmpcursor.pos() + 1);
2245
2246     if (tmpcursor.pos() == tmpcursor.par()->size()) {
2247         if (tmpcursor.par()->next()) {
2248             tmpcursor.par(tmpcursor.par()->next());
2249             tmpcursor.pos(0);
2250         }
2251     } else
2252         tmpcursor.pos(tmpcursor.pos() + 1);
2253     setCursor(bview, tmpcursor.par(), tmpcursor.pos());
2254 }
2255
2256
2257 /* -------> Skip initial whitespace at end of word and move cursor to *start*
2258             of prior word, not to end of next prior word. */
2259
2260 void LyXText::cursorLeftOneWord(BufferView * bview)  const
2261 {
2262         LyXCursor tmpcursor = cursor;
2263         cursorLeftOneWord(tmpcursor);
2264         setCursor(bview, tmpcursor.par(), tmpcursor.pos());
2265 }
2266
2267 void LyXText::cursorLeftOneWord(LyXCursor  & cur)  const
2268 {
2269         // treat HFills, floats and Insets as words
2270         cur = cursor;
2271         while (cur.pos()
2272                && (cur.par()->isSeparator(cur.pos() - 1)
2273                    || cur.par()->isKomma(cur.pos() - 1))
2274                && !(cur.par()->isHfill(cur.pos() - 1)
2275                     || cur.par()->isInset(cur.pos() - 1)))
2276                 cur.pos(cur.pos() - 1);
2277
2278         if (cur.pos()
2279             && (cur.par()->isInset(cur.pos() - 1)
2280                 || cur.par()->isHfill(cur.pos() - 1))) {
2281                 cur.pos(cur.pos() - 1);
2282         } else if (!cur.pos()) {
2283                 if (cur.par()->previous()) {
2284                         cur.par(cur.par()->previous());
2285                         cur.pos(cur.par()->size());
2286                 }
2287         } else {                // Here, cur != 0
2288                 while (cur.pos() > 0 &&
2289                        cur.par()->isWord(cur.pos()-1))
2290                         cur.pos(cur.pos() - 1);
2291         }
2292 }
2293
2294 /* -------> Select current word. This depends on behaviour of
2295 CursorLeftOneWord(), so it is patched as well. */
2296 void LyXText::getWord(LyXCursor & from, LyXCursor & to,
2297                       word_location const loc) const
2298 {
2299         // first put the cursor where we wana start to select the word
2300         from = cursor;
2301         switch (loc) {
2302         case WHOLE_WORD_STRICT:
2303                 if (cursor.pos() == 0 || cursor.pos() == cursor.par()->size()
2304                     || cursor.par()->isSeparator(cursor.pos())
2305                     || cursor.par()->isKomma(cursor.pos())
2306                     || cursor.par()->isSeparator(cursor.pos() -1)
2307                     || cursor.par()->isKomma(cursor.pos() -1)) {
2308                         to = from;
2309                         return;
2310                 }
2311                 // no break here, we go to the next
2312
2313         case WHOLE_WORD:
2314                 // Move cursor to the beginning, when not already there.
2315                 if (from.pos() && !from.par()->isSeparator(from.pos() - 1)
2316                     && !from.par()->isKomma(from.pos() - 1))
2317                         cursorLeftOneWord(from);
2318                 break;
2319         case PREVIOUS_WORD:
2320                 // always move the cursor to the beginning of previous word
2321                 cursorLeftOneWord(from);
2322                 break;
2323         case NEXT_WORD:
2324                 lyxerr << "LyXText::getWord: NEXT_WORD not implemented yet\n";
2325                 break;
2326         case PARTIAL_WORD:
2327                 break;
2328         }
2329         to = from;
2330         while (to.pos() < to.par()->size()
2331                && !to.par()->isSeparator(to.pos())
2332                && !to.par()->isKomma(to.pos())
2333                && !to.par()->isHfill(to.pos()))
2334         {
2335                 to.pos(to.pos() + 1);
2336         }
2337 }
2338
2339
2340 void LyXText::selectWord(BufferView * bview, word_location const loc)
2341 {
2342         LyXCursor from;
2343         LyXCursor to;
2344         getWord(from, to, loc);
2345         if (cursor != from)
2346                 setCursor(bview, from.par(), from.pos());
2347         if (to == from)
2348                 return;
2349         selection.cursor = cursor;
2350         setCursor(bview, to.par(), to.pos());
2351         setSelection(bview);
2352 }
2353
2354
2355 /* -------> Select the word currently under the cursor when no
2356         selection is currently set */
2357 bool LyXText::selectWordWhenUnderCursor(BufferView * bview,
2358                                         word_location const loc)
2359 {
2360         if (!selection.set()) {
2361                 selectWord(bview, loc);
2362                 return selection.set();
2363         }
2364         return false;
2365 }
2366
2367
2368 // This function is only used by the spellchecker for NextWord().
2369 // It doesn't handle LYX_ACCENTs and probably never will.
2370 string const LyXText::selectNextWordToSpellcheck(BufferView * bview,
2371                                                  float & value) const
2372 {
2373         if (the_locking_inset) {
2374                 string str = the_locking_inset->selectNextWordToSpellcheck(bview, value);
2375                 if (!str.empty()) {
2376                         value += float(cursor.y())/float(height);
2377                         return str;
2378                 }
2379                 // we have to go on checking so move cusor to the next char
2380                 if (cursor.pos() == cursor.par()->size()) {
2381                         if (!cursor.par()->next())
2382                                 return str;
2383                         cursor.par(cursor.par()->next());
2384                         cursor.pos(0);
2385                 } else
2386                         cursor.pos(cursor.pos() + 1);
2387         }
2388         Paragraph * tmppar = cursor.par();
2389
2390         // If this is not the very first word, skip rest of
2391         // current word because we are probably in the middle
2392         // of a word if there is text here.
2393         if (cursor.pos() || cursor.par()->previous()) {
2394                 while (cursor.pos() < cursor.par()->size()
2395                        && cursor.par()->isLetter(cursor.pos()))
2396                         cursor.pos(cursor.pos() + 1);
2397         }
2398
2399         // Now, skip until we have real text (will jump paragraphs)
2400         while ((cursor.par()->size() > cursor.pos()
2401                && (!cursor.par()->isLetter(cursor.pos()))
2402                && (!cursor.par()->isInset(cursor.pos()) ||
2403                            !cursor.par()->getInset(cursor.pos())->allowSpellcheck()))
2404                || (cursor.par()->size() == cursor.pos()
2405                    && cursor.par()->next()))
2406         {
2407                 if (cursor.pos() == cursor.par()->size()) {
2408                         cursor.par(cursor.par()->next());
2409                         cursor.pos(0);
2410                 } else
2411                         cursor.pos(cursor.pos() + 1);
2412         }
2413
2414         // now check if we hit an inset so it has to be a inset containing text!
2415         if (cursor.pos() < cursor.par()->size() &&
2416             cursor.par()->isInset(cursor.pos()))
2417         {
2418                 // lock the inset!
2419                 cursor.par()->getInset(cursor.pos())->edit(bview);
2420                 // now call us again to do the above trick
2421                 // but obviously we have to start from down below ;)
2422                 return bview->text->selectNextWordToSpellcheck(bview, value);
2423         }
2424
2425         // Update the value if we changed paragraphs
2426         if (cursor.par() != tmppar) {
2427                 setCursor(bview, cursor.par(), cursor.pos());
2428                 value = float(cursor.y())/float(height);
2429         }
2430
2431         // Start the selection from here
2432         selection.cursor = cursor;
2433
2434         // and find the end of the word (insets like optional hyphens
2435         // and ligature break are part of a word)
2436         while (cursor.pos() < cursor.par()->size()
2437                && (cursor.par()->isLetter(cursor.pos())))
2438                 cursor.pos(cursor.pos() + 1);
2439
2440         // Finally, we copy the word to a string and return it
2441         string str;
2442         if (selection.cursor.pos() < cursor.pos()) {
2443                 pos_type i;
2444                 for (i = selection.cursor.pos(); i < cursor.pos(); ++i) {
2445                         if (!cursor.par()->isInset(i))
2446                                 str += cursor.par()->getChar(i);
2447                 }
2448         }
2449         return str;
2450 }
2451
2452
2453 // This one is also only for the spellchecker
2454 void LyXText::selectSelectedWord(BufferView * bview)
2455 {
2456         if (the_locking_inset) {
2457                 the_locking_inset->selectSelectedWord(bview);
2458                 return;
2459         }
2460         // move cursor to the beginning
2461         setCursor(bview, selection.cursor.par(), selection.cursor.pos());
2462
2463         // set the sel cursor
2464         selection.cursor = cursor;
2465
2466         // now find the end of the word
2467         while (cursor.pos() < cursor.par()->size()
2468                && (cursor.par()->isLetter(cursor.pos())))
2469                 cursor.pos(cursor.pos() + 1);
2470
2471         setCursor(bview, cursor.par(), cursor.pos());
2472
2473         // finally set the selection
2474         setSelection(bview);
2475 }
2476
2477
2478 /* -------> Delete from cursor up to the end of the current or next word. */
2479 void LyXText::deleteWordForward(BufferView * bview)
2480 {
2481         if (!cursor.par()->size())
2482                 cursorRight(bview);
2483         else {
2484                 LyXCursor tmpcursor = cursor;
2485                 tmpcursor.row(0); // ??
2486                 selection.set(true); // to avoid deletion
2487                 cursorRightOneWord(bview);
2488                 setCursor(bview, tmpcursor, tmpcursor.par(), tmpcursor.pos());
2489                 selection.cursor = cursor;
2490                 cursor = tmpcursor;
2491                 setSelection(bview);
2492
2493                 /* -----> Great, CutSelection() gets rid of multiple spaces. */
2494                 cutSelection(bview, true, false);
2495         }
2496 }
2497
2498
2499 /* -------> Delete from cursor to start of current or prior word. */
2500 void LyXText::deleteWordBackward(BufferView * bview)
2501 {
2502        if (!cursor.par()->size())
2503                cursorLeft(bview);
2504        else {
2505                LyXCursor tmpcursor = cursor;
2506                tmpcursor.row(0); // ??
2507                selection.set(true); // to avoid deletion
2508                cursorLeftOneWord(bview);
2509                setCursor(bview, tmpcursor, tmpcursor.par(), tmpcursor.pos());
2510                selection.cursor = cursor;
2511                cursor = tmpcursor;
2512                setSelection(bview);
2513                cutSelection(bview, true, false);
2514        }
2515 }
2516
2517
2518 /* -------> Kill to end of line. */
2519 void LyXText::deleteLineForward(BufferView * bview)
2520 {
2521         if (!cursor.par()->size())
2522                 // Paragraph is empty, so we just go to the right
2523                 cursorRight(bview);
2524         else {
2525                 LyXCursor tmpcursor = cursor;
2526                 // We can't store the row over a regular setCursor
2527                 // so we set it to 0 and reset it afterwards.
2528                 tmpcursor.row(0); // ??
2529                 selection.set(true); // to avoid deletion
2530                 cursorEnd(bview);
2531                 setCursor(bview, tmpcursor, tmpcursor.par(), tmpcursor.pos());
2532                 selection.cursor = cursor;
2533                 cursor = tmpcursor;
2534                 setSelection(bview);
2535                 // What is this test for ??? (JMarc)
2536                 if (!selection.set()) {
2537                         deleteWordForward(bview);
2538                 } else {
2539                         cutSelection(bview, true, false);
2540                 }
2541         }
2542 }
2543
2544
2545 // Change the case of a word at cursor position.
2546 // This function directly manipulates Paragraph::text because there
2547 // is no Paragraph::SetChar currently. I did what I could to ensure
2548 // that it is correct. I guess part of it should be moved to
2549 // Paragraph, but it will have to change for 1.1 anyway. At least
2550 // it does not access outside of the allocated array as the older
2551 // version did. (JMarc)
2552 void LyXText::changeCase(BufferView * bview, LyXText::TextCase action)
2553 {
2554         LyXCursor from;
2555         LyXCursor to;
2556
2557         if (selection.set()) {
2558                 from = selection.start;
2559                 to = selection.end;
2560         } else {
2561                 getWord(from, to, PARTIAL_WORD);
2562                 setCursor(bview, to.par(), to.pos() + 1);
2563         }
2564
2565         changeRegionCase(bview, from, to, action);
2566 }
2567
2568
2569 void LyXText::changeRegionCase(BufferView * bview,
2570                                LyXCursor const & from,
2571                                LyXCursor const & to,
2572                                LyXText::TextCase action)
2573 {
2574         lyx::Assert(from <= to);
2575
2576         setUndo(bview, Undo::FINISH, from.par(), to.par()->next());
2577
2578         pos_type pos = from.pos();
2579         Paragraph * par = from.par();
2580
2581         while (par && (pos != to.pos() || par != to.par())) {
2582                 unsigned char c = par->getChar(pos);
2583                 if (!IsInsetChar(c) && !IsHfillChar(c)) {
2584                         switch (action) {
2585                         case text_lowercase:
2586                                 c = lowercase(c);
2587                                 break;
2588                         case text_capitalization:
2589                                 c = uppercase(c);
2590                                 action = text_lowercase;
2591                                 break;
2592                         case text_uppercase:
2593                                 c = uppercase(c);
2594                                 break;
2595                         }
2596                 }
2597                 par->setChar(pos, c);
2598                 checkParagraph(bview, par, pos);
2599
2600                 ++pos;
2601                 if (pos == par->size()) {
2602                         par = par->next();
2603                         pos = 0;
2604                 }
2605         }
2606         if (to.row() != from.row()) {
2607                 refresh_y = from.y() - from.row()->baseline();
2608                 refresh_row = from.row();
2609                 status(bview, LyXText::NEED_MORE_REFRESH);
2610         }
2611 }
2612
2613
2614 void LyXText::transposeChars(BufferView & bview)
2615 {
2616         Paragraph * tmppar = cursor.par();
2617
2618         setUndo(&bview, Undo::FINISH, tmppar, tmppar->next());
2619
2620         pos_type tmppos = cursor.pos();
2621
2622         // First decide if it is possible to transpose at all
2623
2624         // We are at the beginning of a paragraph.
2625         if (tmppos == 0) return;
2626
2627         // We are at the end of a paragraph.
2628         if (tmppos == tmppar->size() - 1) return;
2629
2630         unsigned char c1 = tmppar->getChar(tmppos);
2631         unsigned char c2 = tmppar->getChar(tmppos - 1);
2632
2633         if (c1 != Paragraph::META_INSET
2634             && c2 != Paragraph::META_INSET) {
2635                 tmppar->setChar(tmppos, c2);
2636                 tmppar->setChar(tmppos - 1, c1);
2637         }
2638         // We should have an implementation that handles insets
2639         // as well, but that will have to come later. (Lgb)
2640         checkParagraph(const_cast<BufferView*>(&bview), tmppar, tmppos);
2641 }
2642
2643
2644 void LyXText::Delete(BufferView * bview)
2645 {
2646         // this is a very easy implementation
2647
2648         LyXCursor old_cursor = cursor;
2649         int const old_cur_par_id = old_cursor.par()->id();
2650         int const old_cur_par_prev_id = old_cursor.par()->previous() ?
2651                 old_cursor.par()->previous()->id() : 0;
2652
2653         // just move to the right
2654         cursorRight(bview);
2655
2656         // CHECK Look at the comment here.
2657         // This check is not very good...
2658         // The cursorRightIntern calls DeleteEmptyParagrapgMechanism
2659         // and that can very well delete the par or par->previous in
2660         // old_cursor. Will a solution where we compare paragraph id's
2661         //work better?
2662         if ((cursor.par()->previous() ? cursor.par()->previous()->id() : 0)
2663             == old_cur_par_prev_id
2664             && cursor.par()->id() != old_cur_par_id) {
2665                 // delete-empty-paragraph-mechanism has done it
2666                 return;
2667         }
2668
2669         // if you had success make a backspace
2670         if (old_cursor.par() != cursor.par() || old_cursor.pos() != cursor.pos()) {
2671                 LyXCursor tmpcursor = cursor;
2672                 // to make sure undo gets the right cursor position
2673                 cursor = old_cursor;
2674                 setUndo(bview, Undo::DELETE,
2675                         cursor.par(), cursor.par()->next());
2676                 cursor = tmpcursor;
2677                 backspace(bview);
2678         }
2679 }
2680
2681
2682 void LyXText::backspace(BufferView * bview)
2683 {
2684         // Get the font that is used to calculate the baselineskip
2685         pos_type lastpos = cursor.par()->size();
2686         LyXFont rawparfont =
2687                 cursor.par()->getFontSettings(bview->buffer()->params,
2688                                               lastpos - 1);
2689
2690         if (cursor.pos() == 0) {
2691                 // The cursor is at the beginning of a paragraph,
2692                 // so the the backspace will collapse two paragraphs into one.
2693
2694                 // we may paste some paragraphs
2695
2696                 // is it an empty paragraph?
2697
2698                 if ((lastpos == 0
2699                      || (lastpos == 1 && cursor.par()->isSeparator(0)))) {
2700                         // This is an empty paragraph and we delete it just by moving the cursor one step
2701                         // left and let the DeleteEmptyParagraphMechanism handle the actual deletion
2702                         // of the paragraph.
2703
2704                         if (cursor.par()->previous()) {
2705                                 Paragraph * tmppar = cursor.par()->previous();
2706                                 if (cursor.par()->layout() == tmppar->layout()
2707                                     && cursor.par()->getAlign() == tmppar->getAlign()) {
2708                                         // Inherit bottom DTD from the paragraph below.
2709                                         // (the one we are deleting)
2710                                         tmppar->params().lineBottom(cursor.par()->params().lineBottom());
2711                                         tmppar->params().spaceBottom(cursor.par()->params().spaceBottom());
2712                                         tmppar->params().pagebreakBottom(cursor.par()->params().pagebreakBottom());
2713                                 }
2714
2715                                 cursorLeft(bview);
2716
2717                                 // the layout things can change the height of a row !
2718                                 int const tmpheight = cursor.row()->height();
2719                                 setHeightOfRow(bview, cursor.row());
2720                                 if (cursor.row()->height() != tmpheight) {
2721                                         refresh_y = cursor.y() - cursor.row()->baseline();
2722                                         refresh_row = cursor.row();
2723                                         status(bview, LyXText::NEED_MORE_REFRESH);
2724                                 }
2725                                 return;
2726                         }
2727                 }
2728
2729                 if (cursor.par()->previous()) {
2730                         setUndo(bview, Undo::DELETE,
2731                                 cursor.par()->previous(), cursor.par()->next());
2732                 }
2733
2734                 Paragraph * tmppar = cursor.par();
2735                 Row * tmprow = cursor.row();
2736
2737                 // We used to do cursorLeftIntern() here, but it is
2738                 // not a good idea since it triggers the auto-delete
2739                 // mechanism. So we do a cursorLeftIntern()-lite,
2740                 // without the dreaded mechanism. (JMarc)
2741                 if (cursor.par()->previous()) {
2742                         // steps into the above paragraph.
2743                         setCursorIntern(bview, cursor.par()->previous(),
2744                                         cursor.par()->previous()->size(),
2745                                         false);
2746                 }
2747
2748                 /* Pasting is not allowed, if the paragraphs have different
2749                    layout. I think it is a real bug of all other
2750                    word processors to allow it. It confuses the user.
2751                    Even so with a footnote paragraph and a non-footnote
2752                    paragraph. I will not allow pasting in this case,
2753                    because the user would be confused if the footnote behaves
2754                    different wether it is open or closed.
2755
2756                    Correction: Pasting is always allowed with standard-layout
2757                 */
2758                 LyXTextClass const & tclass = textclasslist[bview->buffer()->params.textclass];
2759
2760                 if (cursor.par() != tmppar
2761                     && (cursor.par()->layout() == tmppar->layout()
2762                         || tmppar->layout() == tclass.defaultLayoutName())
2763                     && cursor.par()->getAlign() == tmppar->getAlign()) {
2764                         removeParagraph(tmprow);
2765                         removeRow(tmprow);
2766                         cursor.par()->pasteParagraph(bview->buffer()->params);
2767
2768                         if (!cursor.pos() || !cursor.par()->isSeparator(cursor.pos() - 1))
2769                                 ; //cursor.par()->insertChar(cursor.pos(), ' ');
2770                         // strangely enough it seems that commenting out the line above removes
2771                         // most or all of the segfaults. I will however also try to move the
2772                         // two Remove... lines in front of the PasteParagraph too.
2773                         else
2774                                 if (cursor.pos())
2775                                         cursor.pos(cursor.pos() - 1);
2776
2777                         status(bview, LyXText::NEED_MORE_REFRESH);
2778                         refresh_row = cursor.row();
2779                         refresh_y = cursor.y() - cursor.row()->baseline();
2780
2781                         // remove the lost paragraph
2782                         // This one is not safe, since the paragraph that the tmprow and the
2783                         // following rows belong to has been deleted by the PasteParagraph
2784                         // above. The question is... could this be moved in front of the
2785                         // PasteParagraph?
2786                         //RemoveParagraph(tmprow);
2787                         //RemoveRow(tmprow);
2788
2789                         // This rebuilds the rows.
2790                         appendParagraph(bview, cursor.row());
2791                         updateCounters(bview, cursor.row());
2792
2793                         // the row may have changed, block, hfills etc.
2794                         setCursor(bview, cursor.par(), cursor.pos(), false);
2795                 }
2796         } else {
2797                 /* this is the code for a normal backspace, not pasting
2798                  * any paragraphs */
2799                 setUndo(bview, Undo::DELETE,
2800                         cursor.par(), cursor.par()->next());
2801                 // We used to do cursorLeftIntern() here, but it is
2802                 // not a good idea since it triggers the auto-delete
2803                 // mechanism. So we do a cursorLeftIntern()-lite,
2804                 // without the dreaded mechanism. (JMarc)
2805                 setCursorIntern(bview, cursor.par(), cursor.pos()- 1,
2806                                 false, cursor.boundary());
2807
2808                 // some insets are undeletable here
2809                 if (cursor.par()->isInset(cursor.pos())) {
2810                         if (!cursor.par()->getInset(cursor.pos())->deletable())
2811                                 return;
2812                         // force complete redo when erasing display insets
2813                         // this is a cruel method but safe..... Matthias
2814                         if (cursor.par()->getInset(cursor.pos())->display() ||
2815                             cursor.par()->getInset(cursor.pos())->needFullRow()) {
2816                                 cursor.par()->erase(cursor.pos());
2817                                 redoParagraph(bview);
2818                                 return;
2819                         }
2820                 }
2821
2822                 Row * row = cursor.row();
2823                 int y = cursor.y() - row->baseline();
2824                 pos_type z;
2825                 /* remember that a space at the end of a row doesnt count
2826                  * when calculating the fill */
2827                 if (cursor.pos() < rowLast(row) ||
2828                     !cursor.par()->isLineSeparator(cursor.pos())) {
2829                         row->fill(row->fill() + singleWidth(bview,
2830                                                             cursor.par(),
2831                                                             cursor.pos()));
2832                 }
2833
2834                 /* some special code when deleting a newline. This is similar
2835                  * to the behavior when pasting paragraphs */
2836                 if (cursor.pos() && cursor.par()->isNewline(cursor.pos())) {
2837                         cursor.par()->erase(cursor.pos());
2838                         // refresh the positions
2839                         Row * tmprow = row;
2840                         while (tmprow->next() && tmprow->next()->par() == row->par()) {
2841                                 tmprow = tmprow->next();
2842                                 tmprow->pos(tmprow->pos() - 1);
2843                         }
2844                         if (cursor.par()->isLineSeparator(cursor.pos() - 1))
2845                                 cursor.pos(cursor.pos() - 1);
2846
2847                         if (cursor.pos() < cursor.par()->size()
2848                             && !cursor.par()->isSeparator(cursor.pos())) {
2849                                 cursor.par()->insertChar(cursor.pos(), ' ');
2850                                 setCharFont(bview->buffer(), cursor.par(),
2851                                             cursor.pos(), current_font);
2852                                 // refresh the positions
2853                                 tmprow = row;
2854                                 while (tmprow->next() && tmprow->next()->par() == row->par()) {
2855                                         tmprow = tmprow->next();
2856                                         tmprow->pos(tmprow->pos() + 1);
2857                                 }
2858                         }
2859                 } else {
2860                         cursor.par()->erase(cursor.pos());
2861
2862                         // refresh the positions
2863                         Row * tmprow = row;
2864                         while (tmprow->next()
2865                                && tmprow->next()->par() == row->par()) {
2866                                 tmprow = tmprow->next();
2867                                 tmprow->pos(tmprow->pos() - 1);
2868                         }
2869
2870                         // delete newlines at the beginning of paragraphs
2871                         while (cursor.par()->size() &&
2872                                cursor.par()->isNewline(cursor.pos()) &&
2873                                cursor.pos() == beginningOfMainBody(bview->buffer(),
2874                                                                    cursor.par())) {
2875                                 cursor.par()->erase(cursor.pos());
2876                                 // refresh the positions
2877                                 tmprow = row;
2878                                 while (tmprow->next() &&
2879                                        tmprow->next()->par() == row->par()) {
2880                                         tmprow = tmprow->next();
2881                                         tmprow->pos(tmprow->pos() - 1);
2882                                 }
2883                         }
2884                 }
2885
2886                 // is there a break one row above
2887                 if (row->previous() && row->previous()->par() == row->par()) {
2888                         z = nextBreakPoint(bview, row->previous(),
2889                                            workWidth(bview));
2890                         if (z >= row->pos()) {
2891                                 row->pos(z + 1);
2892
2893                                 Row * tmprow = row->previous();
2894
2895                                 // maybe the current row is now empty
2896                                 if (row->pos() >= row->par()->size()) {
2897                                         // remove it
2898                                         removeRow(row);
2899                                         need_break_row = 0;
2900                                 } else {
2901                                         breakAgainOneRow(bview, row);
2902                                         if (row->next() && row->next()->par() == row->par())
2903                                                 need_break_row = row->next();
2904                                         else
2905                                                 need_break_row = 0;
2906                                 }
2907
2908                                 // set the dimensions of the row above
2909                                 y -= tmprow->height();
2910                                 tmprow->fill(fill(bview, tmprow,
2911                                                   workWidth(bview)));
2912                                 setHeightOfRow(bview, tmprow);
2913
2914                                 refresh_y = y;
2915                                 refresh_row = tmprow;
2916                                 status(bview, LyXText::NEED_MORE_REFRESH);
2917                                 setCursor(bview, cursor.par(), cursor.pos(),
2918                                           false, cursor.boundary());
2919                                 //current_font = rawtmpfont;
2920                                 //real_current_font = realtmpfont;
2921                                 // check, whether the last character's font has changed.
2922                                 if (rawparfont !=
2923                                     cursor.par()->getFontSettings(bview->buffer()->params,
2924                                                                   cursor.par()->size() - 1))
2925                                         redoHeightOfParagraph(bview, cursor);
2926                                 return;
2927                         }
2928                 }
2929
2930                 // break the cursor row again
2931                 if (row->next() && row->next()->par() == row->par() &&
2932                     (rowLast(row) == row->par()->size() - 1 ||
2933                      nextBreakPoint(bview, row, workWidth(bview)) != rowLast(row))) {
2934
2935                         /* it can happen that a paragraph loses one row
2936                          * without a real breakup. This is when a word
2937                          * is to long to be broken. Well, I don t care this
2938                          * hack ;-) */
2939                         if (rowLast(row) == row->par()->size() - 1)
2940                                 removeRow(row->next());
2941
2942                         refresh_y = y;
2943                         refresh_row = row;
2944                         status(bview, LyXText::NEED_MORE_REFRESH);
2945
2946                         breakAgainOneRow(bview, row);
2947                         // will the cursor be in another row now?
2948                         if (row->next() && row->next()->par() == row->par() &&
2949                             rowLast(row) <= cursor.pos()) {
2950                                 row = row->next();
2951                                 breakAgainOneRow(bview, row);
2952                         }
2953
2954                         setCursor(bview, cursor.par(), cursor.pos(), false, cursor.boundary());
2955
2956                         if (row->next() && row->next()->par() == row->par())
2957                                 need_break_row = row->next();
2958                         else
2959                                 need_break_row = 0;
2960                 } else  {
2961                         // set the dimensions of the row
2962                         row->fill(fill(bview, row, workWidth(bview)));
2963                         int const tmpheight = row->height();
2964                         setHeightOfRow(bview, row);
2965                         if (tmpheight == row->height())
2966                                 status(bview, LyXText::NEED_VERY_LITTLE_REFRESH);
2967                         else
2968                                 status(bview, LyXText::NEED_MORE_REFRESH);
2969                         refresh_y = y;
2970                         refresh_row = row;
2971                         setCursor(bview, cursor.par(), cursor.pos(), false, cursor.boundary());
2972                 }
2973         }
2974
2975         // current_font = rawtmpfont;
2976         // real_current_font = realtmpfont;
2977
2978         if (isBoundary(bview->buffer(), cursor.par(), cursor.pos())
2979             != cursor.boundary())
2980                 setCursor(bview, cursor.par(), cursor.pos(), false,
2981                           !cursor.boundary());
2982
2983         lastpos = cursor.par()->size();
2984         if (cursor.pos() == lastpos)
2985                 setCurrentFont(bview);
2986
2987         // check, whether the last characters font has changed.
2988         if (rawparfont !=
2989             cursor.par()->getFontSettings(bview->buffer()->params, lastpos - 1)) {
2990                 redoHeightOfParagraph(bview, cursor);
2991         } else {
2992                 // now the special right address boxes
2993                 if (textclasslist
2994                     [bview->buffer()->params.textclass]
2995                     [cursor.par()->layout()].margintype == MARGIN_RIGHT_ADDRESS_BOX) {
2996                         redoDrawingOfParagraph(bview, cursor);
2997                 }
2998         }
2999 }
3000
3001
3002 bool LyXText::paintRowBackground(DrawRowParams & p)
3003 {
3004         bool clear_area = true;
3005         Inset * inset = 0;
3006         LyXFont font(LyXFont::ALL_SANE);
3007
3008         pos_type const last = rowLastPrintable(p.row);
3009
3010         if (!p.bv->screen()->forceClear() && last == p.row->pos()
3011                 && p.row->par()->isInset(p.row->pos())) {
3012                 inset = p.row->par()->getInset(p.row->pos());
3013                 if (inset) {
3014                         clear_area = inset->doClearArea();
3015                 }
3016         }
3017
3018         if (p.cleared) {
3019                 return true;
3020         }
3021
3022         if (clear_area) {
3023                 int const x = p.xo;
3024                 int const y = p.yo < 0 ? 0 : p.yo;
3025                 int const h = p.yo < 0 ? p.row->height() + p.yo : p.row->height();
3026                 p.pain->fillRectangle(x, y, p.width, h, backgroundColor());
3027                 return true;
3028         }
3029
3030         if (inset == 0)
3031                 return false;
3032
3033         int h = p.row->baseline() - inset->ascent(p.bv, font);
3034
3035         // first clear the whole row above the inset!
3036         if (h > 0) {
3037                 p.pain->fillRectangle(p.xo, p.yo, p.width, h, backgroundColor());
3038         }
3039
3040         // clear the space below the inset!
3041         h += inset->ascent(p.bv, font) + inset->descent(p.bv, font);
3042         if ((p.row->height() - h) > 0) {
3043                 p.pain->fillRectangle(p.xo, p.yo + h,
3044                         p.width, p.row->height() - h, backgroundColor());
3045         }
3046
3047         // clear the space behind the inset, if needed
3048         if (!inset->display() && !inset->needFullRow()) {
3049                 int const xp = int(p.x) + inset->width(p.bv, font);
3050                 if (p.width - xp > 0) {
3051                         p.pain->fillRectangle(xp, p.yo, p.width - xp,
3052                                 p.row->height(), backgroundColor());
3053                 }
3054         }
3055
3056         return false;
3057 }
3058
3059
3060 void LyXText::paintRowSelection(DrawRowParams & p)
3061 {
3062         bool const is_rtl = p.row->par()->isRightToLeftPar(p.bv->buffer()->params);
3063
3064         // the current selection
3065         int const startx = selection.start.x();
3066         int const endx = selection.end.x();
3067         int const starty = selection.start.y();
3068         int const endy = selection.end.y();
3069         Row const * startrow = selection.start.row();
3070         Row const * endrow = selection.end.row();
3071
3072         Row * row = p.row;
3073
3074         if (bidi_same_direction) {
3075                 int x;
3076                 int y = p.yo;
3077                 int w;
3078                 int h = row->height();
3079
3080                 if (startrow == row && endrow == row) {
3081                         if (startx < endx) {
3082                                 x = p.xo + startx;
3083                                 w = endx - startx;
3084                                 p.pain->fillRectangle(x, y, w, h, LColor::selection);
3085                         } else {
3086                                 x = p.xo + endx;
3087                                 w = startx - endx;
3088                                 p.pain->fillRectangle(x, y, w, h, LColor::selection);
3089                         }
3090                 } else if (startrow == row) {
3091                         int const x = (is_rtl) ? p.xo : (p.xo + startx);
3092                         int const w = (is_rtl) ? startx : (p.width - startx);
3093                         p.pain->fillRectangle(x, y, w, h, LColor::selection);
3094                 } else if (endrow == row) {
3095                         int const x = (is_rtl) ? (p.xo + endx) : p.xo;
3096                         int const w = (is_rtl) ? (p.width - endx) : endx;
3097                         p.pain->fillRectangle(x, y, w, h, LColor::selection);
3098                 } else if (p.y > starty && p.y < endy) {
3099                         p.pain->fillRectangle(p.xo, y, p.width, h, LColor::selection);
3100                 }
3101                 return;
3102         } else if (startrow != row && endrow != row) {
3103                 int w = p.width;
3104                 int h = row->height();
3105                 if (p.y > starty && p.y < endy) {
3106                         p.pain->fillRectangle(p.xo, p.yo, w, h, LColor::selection);
3107                 }
3108                 return;
3109         }
3110
3111         if (!((startrow != row && !is_rtl) || (endrow != row && is_rtl))) {
3112                 return;
3113         }
3114
3115         float tmpx = p.x;
3116
3117         p.pain->fillRectangle(p.xo, p.yo, int(p.x), row->height(), LColor::selection);
3118
3119         Buffer const * buffer = p.bv->buffer();
3120         Paragraph * par = row->par();
3121         pos_type main_body = beginningOfMainBody(buffer, par);
3122         pos_type const last = rowLastPrintable(row);
3123
3124         for (pos_type vpos = row->pos(); vpos <= last; ++vpos)  {
3125                 pos_type pos = vis2log(vpos);
3126                 float const old_tmpx = tmpx;
3127                 if (main_body > 0 && pos == main_body - 1) {
3128                         LyXLayout const & layout =
3129                                 textclasslist
3130                                 [buffer->params.textclass]
3131                                 [par->layout()];
3132                         LyXFont const lfont = getLabelFont(buffer, par);
3133
3134
3135                         tmpx += p.label_hfill + lyxfont::width(layout.labelsep, lfont);
3136
3137                         if (par->isLineSeparator(main_body - 1))
3138                                 tmpx -= singleWidth(p.bv, par, main_body - 1);
3139                 }
3140
3141                 if (hfillExpansion(buffer, row, pos)) {
3142                         tmpx += singleWidth(p.bv, par, pos);
3143                         if (pos >= main_body)
3144                                 tmpx += p.hfill;
3145                         else
3146                                 tmpx += p.label_hfill;
3147                 }
3148
3149                 else if (par->isSeparator(pos)) {
3150                         tmpx += singleWidth(p.bv, par, pos);
3151                         if (pos >= main_body)
3152                                 tmpx += p.separator;
3153                 } else {
3154                         tmpx += singleWidth(p.bv, par, pos);
3155                 }
3156
3157                 if ((startrow != row || selection.start.pos() <= pos) &&
3158                         (endrow != row || pos < selection.end.pos())) {
3159                         // Here we do not use p.x as p.xo was added to p.x.
3160                         p.pain->fillRectangle(int(old_tmpx), p.yo,
3161                                 int(tmpx - old_tmpx + 1),
3162                                 row->height(), LColor::selection);
3163                 }
3164
3165                 if ((startrow != row && is_rtl) || (endrow != row && !is_rtl)) {
3166                         p.pain->fillRectangle(p.xo + int(tmpx),
3167                                 p.yo, int(p.bv->workWidth() - tmpx),
3168                                 row->height(), LColor::selection);
3169                 }
3170         }
3171 }
3172
3173
3174 void LyXText::paintRowAppendix(DrawRowParams & p)
3175 {
3176         // FIXME: can be just p.width ?
3177         int const ww = p.bv->workWidth();
3178         Paragraph * firstpar = p.row->par();
3179
3180         if (firstpar->params().appendix()) {
3181                 p.pain->line(1, p.yo, 1, p.yo + p.row->height(), LColor::appendixline);
3182                 p.pain->line(ww - 2, p.yo, ww - 2, p.yo + p.row->height(), LColor::appendixline);
3183         }
3184 }
3185
3186
3187 void LyXText::paintRowDepthBar(DrawRowParams & p)
3188 {
3189         Paragraph::depth_type const depth = p.row->par()->getDepth();
3190
3191         if (depth <= 0)
3192                 return;
3193
3194         Paragraph::depth_type prev_depth = 0;
3195         if (p.row->previous())
3196                 prev_depth = p.row->previous()->par()->getDepth();
3197         Paragraph::depth_type next_depth = 0;
3198         if (p.row->next())
3199                 next_depth = p.row->next()->par()->getDepth();
3200
3201         for (Paragraph::depth_type i = 1; i <= depth; ++i) {
3202                 int const x = (LYX_PAPER_MARGIN / 5) * i + p.xo;
3203                 int const h = p.yo + p.row->height() - 1 - (i - next_depth - 1) * 3;
3204
3205                 p.pain->line(x, p.yo, x, h, LColor::depthbar);
3206
3207                 int const w = LYX_PAPER_MARGIN / 5;
3208
3209                 if (i > prev_depth) {
3210                         p.pain->fillRectangle(x, p.yo, w, 2, LColor::depthbar);
3211                 }
3212                 if (i > next_depth) {
3213                         p.pain->fillRectangle(x, h, w, 2, LColor::depthbar);
3214                 }
3215         }
3216 }
3217
3218
3219 int LyXText::getLengthMarkerHeight(BufferView * bv, VSpace const & vsp) const
3220 {
3221         int const arrow_size = 4;
3222         int const space_size = int(vsp.inPixels(bv));
3223
3224         if (vsp.kind() != VSpace::LENGTH) {
3225                 return space_size;
3226         }
3227
3228         LyXFont font;
3229         font.decSize();
3230         int const min_size = max(3 * arrow_size,
3231                                       lyxfont::maxAscent(font)
3232                                       + lyxfont::maxDescent(font));
3233
3234         if (vsp.length().len().value() < 0.0)
3235                 return min_size;
3236         else
3237                 return max(min_size, space_size);
3238 }
3239
3240
3241 int LyXText::drawLengthMarker(DrawRowParams & p, string const & prefix,
3242                               VSpace const & vsp, int start)
3243 {
3244         int const arrow_size = 4;
3245         int const size = getLengthMarkerHeight(p.bv, vsp);
3246         int const end = start + size;
3247
3248         // the label to display (if any)
3249         string str;
3250         // y-values for top arrow
3251         int ty1, ty2;
3252         // y-values for bottom arrow
3253         int by1, by2;
3254         switch (vsp.kind()) {
3255         case VSpace::LENGTH:
3256         {
3257                 str = prefix + " (" + vsp.asLyXCommand() + ")";
3258                 // adding or removing space
3259                 bool const added = !(vsp.length().len().value() < 0.0);
3260                 ty1 = added ? (start + arrow_size) : start;
3261                 ty2 = added ? start : (start + arrow_size);
3262                 by1 = added ? (end - arrow_size) : end;
3263                 by2 = added ? end : (end - arrow_size);
3264                 break;
3265         }
3266         case VSpace:: VFILL:
3267                 str = prefix + " (vertical fill)";
3268                 ty1 = ty2 = start;
3269                 by1 = by2 = end;
3270                 break;
3271         default:
3272                 // nothing to draw here
3273                 return size;
3274         }
3275
3276         int const leftx = p.xo + leftMargin(p.bv, p.row);
3277         int const midx = leftx + arrow_size;
3278         int const rightx = midx + arrow_size;
3279
3280         // first the string
3281         int w = 0;
3282         int a = 0;
3283         int d = 0;
3284
3285         LyXFont font;
3286         font.setColor(LColor::added_space).decSize();
3287         lyxfont::rectText(str, font, w, a, d);
3288
3289         p.pain->rectText(leftx + 2 * arrow_size + 5,
3290                          start + ((end - start) / 2) + d,
3291                          str, font,
3292                          backgroundColor(),
3293                          backgroundColor());
3294
3295         // top arrow
3296         p.pain->line(leftx, ty1, midx, ty2, LColor::added_space);
3297         p.pain->line(midx, ty2, rightx, ty1, LColor::added_space);
3298
3299         // bottom arrow
3300         p.pain->line(leftx, by1, midx, by2, LColor::added_space);
3301         p.pain->line(midx, by2, rightx, by1, LColor::added_space);
3302
3303         // joining line
3304         p.pain->line(midx, ty2, midx, by2, LColor::added_space);
3305
3306         return size;
3307 }
3308
3309
3310 void LyXText::paintFirstRow(DrawRowParams & p)
3311 {
3312         Paragraph * par = p.row->par();
3313         ParagraphParameters const & parparams = par->params();
3314
3315         // start of appendix?
3316         if (parparams.startOfAppendix()) {
3317                 p.pain->line(1, p.yo, p.width - 2, p.yo, LColor::appendixline);
3318         }
3319
3320         int y_top = 0;
3321
3322         // think about the margins
3323         if (!p.row->previous() && bv_owner)
3324                 y_top += LYX_PAPER_MARGIN;
3325
3326         // draw a top pagebreak
3327         if (parparams.pagebreakTop()) {
3328                 int const y = p.yo + y_top + 2*defaultHeight();
3329                 p.pain->line(p.xo, y, p.xo + p.width, y,
3330                         LColor::pagebreak, Painter::line_onoffdash);
3331
3332                 int w = 0;
3333                 int a = 0;
3334                 int d = 0;
3335
3336                 LyXFont pb_font;
3337                 pb_font.setColor(LColor::pagebreak).decSize();
3338                 lyxfont::rectText(_("Page Break (top)"), pb_font, w, a, d);
3339                 p.pain->rectText((p.width - w)/2, y + d,
3340                               _("Page Break (top)"), pb_font,
3341                               backgroundColor(),
3342                               backgroundColor());
3343                 y_top += 3 * defaultHeight();
3344         }
3345
3346         // draw the additional space if needed:
3347         y_top += drawLengthMarker(p, _("Space above"),
3348                                   parparams.spaceTop(), p.yo + y_top);
3349
3350         Buffer const * buffer = p.bv->buffer();
3351
3352         LyXTextClass const & tclass = textclasslist[buffer->params.textclass];
3353         LyXLayout const & layout = tclass[par->layout()];
3354
3355         // think about the parskip
3356         // some parskips VERY EASY IMPLEMENTATION
3357         if (buffer->params.paragraph_separation == BufferParams::PARSEP_SKIP) {
3358                 if (par->previous()) {
3359                         if (layout.latextype == LATEX_PARAGRAPH
3360                                 && !par->getDepth()) {
3361                                 y_top += buffer->params.getDefSkip().inPixels(p.bv);
3362                         } else {
3363                                 LyXLayout const & playout =
3364                                         tclass[par->previous()->layout()];
3365                                 if (playout.latextype == LATEX_PARAGRAPH
3366                                         && !par->previous()->getDepth()) {
3367                                         // is it right to use defskip here, too? (AS)
3368                                         y_top += buffer->params.getDefSkip().inPixels(p.bv);
3369                                 }
3370                         }
3371                 }
3372         }
3373
3374         int const ww = p.bv->workWidth();
3375
3376         // draw a top line
3377         if (parparams.lineTop()) {
3378                 LyXFont font(LyXFont::ALL_SANE);
3379                 int const asc = lyxfont::ascent('x', getFont(buffer, par, 0));
3380
3381                 y_top += asc;
3382
3383                 int const w = (inset_owner ?  inset_owner->width(p.bv, font) : ww);
3384                 int const xp = static_cast<int>(inset_owner ? p.xo : 0);
3385                 p.pain->line(xp, p.yo + y_top, xp + w, p.yo + y_top,
3386                         LColor::topline, Painter::line_solid,
3387                         Painter::line_thick);
3388
3389                 y_top += asc;
3390         }
3391
3392         bool const is_rtl = p.row->par()->isRightToLeftPar(p.bv->buffer()->params);
3393
3394         // should we print a label?
3395         if (layout.labeltype >= LABEL_STATIC
3396             && (layout.labeltype != LABEL_STATIC
3397                 || layout.latextype != LATEX_ENVIRONMENT
3398                 || par->isFirstInSequence())) {
3399
3400                 LyXFont font = getLabelFont(buffer, par);
3401                 if (!par->getLabelstring().empty()) {
3402                         float x = p.x;
3403                         string const str = par->getLabelstring();
3404
3405                         // this is special code for the chapter layout. This is
3406                         // printed in an extra row and has a pagebreak at
3407                         // the top.
3408                         if (layout.labeltype == LABEL_COUNTER_CHAPTER) {
3409                                 if (buffer->params.secnumdepth >= 0) {
3410                                         float spacing_val = 1.0;
3411                                         if (!parparams.spacing().isDefault()) {
3412                                                 spacing_val = parparams.spacing().getValue();
3413                                         } else {
3414                                                 spacing_val = buffer->params.spacing.getValue();
3415                                         }
3416
3417                                         int const maxdesc =
3418                                                 int(lyxfont::maxDescent(font) * layout.spacing.getValue() * spacing_val)
3419                                                 + int(layout.parsep) * defaultHeight();
3420
3421                                         if (is_rtl) {
3422                                                 x = ww - leftMargin(p.bv, p.row) -
3423                                                         lyxfont::width(str, font);
3424                                         }
3425
3426                                         p.pain->text(int(x),
3427                                                 p.yo + p.row->baseline() -
3428                                                 p.row->ascent_of_text() - maxdesc,
3429                                                 str, font);
3430                                 }
3431                         } else {
3432                                 if (is_rtl) {
3433                                         x = ww - leftMargin(p.bv, p.row)
3434                                                 + lyxfont::width(layout.labelsep, font);
3435                                 } else {
3436                                         x = p.x - lyxfont::width(layout.labelsep, font)
3437                                                 - lyxfont::width(str, font);
3438                                 }
3439
3440                                 p.pain->text(int(x), p.yo + p.row->baseline(), str, font);
3441                         }
3442                 }
3443         // the labels at the top of an environment.
3444         // More or less for bibliography
3445         } else if (par->isFirstInSequence() &&
3446                 (layout.labeltype == LABEL_TOP_ENVIRONMENT ||
3447                 layout.labeltype == LABEL_BIBLIO ||
3448                 layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)) {
3449                 LyXFont font = getLabelFont(buffer, par);
3450                 if (!par->getLabelstring().empty()) {
3451                         string const str = par->getLabelstring();
3452                         float spacing_val = 1.0;
3453                         if (!parparams.spacing().isDefault()) {
3454                                 spacing_val = parparams.spacing().getValue();
3455                         } else {
3456                                 spacing_val = buffer->params.spacing.getValue();
3457                         }
3458
3459                         int maxdesc =
3460                                 int(lyxfont::maxDescent(font) * layout.spacing.getValue() * spacing_val
3461                                 + (layout.labelbottomsep * defaultHeight()));
3462
3463                         float x = p.x;
3464                         if (layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT) {
3465                                 x = ((is_rtl ? leftMargin(p.bv, p.row) : p.x)
3466                                          + ww - rightMargin(buffer, p.row)) / 2;
3467                                 x -= lyxfont::width(str, font) / 2;
3468                         } else if (is_rtl) {
3469                                 x = ww - leftMargin(p.bv, p.row) -
3470                                         lyxfont::width(str, font);
3471                         }
3472                         p.pain->text(int(x), p.yo + p.row->baseline()
3473                                   - p.row->ascent_of_text() - maxdesc,
3474                                   str, font);
3475                 }
3476         }
3477
3478         if (layout.labeltype == LABEL_BIBLIO && par->bibkey) {
3479                 LyXFont font = getLayoutFont(buffer, par);
3480                 float x;
3481                 if (is_rtl) {
3482                         x = ww - leftMargin(p.bv, p.row)
3483                                 + lyxfont::width(layout.labelsep, font);
3484                 } else {
3485                         x = p.x - lyxfont::width(layout.labelsep, font)
3486                                 - par->bibkey->width(p.bv, font);
3487                 }
3488                 par->bibkey->draw(p.bv, font, p.yo + p.row->baseline(), x, p.cleared);
3489         }
3490 }
3491
3492
3493 void LyXText::paintLastRow(DrawRowParams & p)
3494 {
3495         Paragraph * par = p.row->par();
3496         ParagraphParameters const & parparams = par->params();
3497         int y_bottom = p.row->height() - 1;
3498
3499         // think about the margins
3500         if (!p.row->next() && bv_owner)
3501                 y_bottom -= LYX_PAPER_MARGIN;
3502
3503         int const ww = p.bv->workWidth();
3504
3505         // draw a bottom pagebreak
3506         if (parparams.pagebreakBottom()) {
3507                 LyXFont pb_font;
3508                 pb_font.setColor(LColor::pagebreak).decSize();
3509                 int const y = p.yo + y_bottom - 2 * defaultHeight();
3510
3511                 p.pain->line(p.xo, y, p.xo + p.width, y, LColor::pagebreak,
3512                              Painter::line_onoffdash);
3513
3514                 int w = 0;
3515                 int a = 0;
3516                 int d = 0;
3517                 lyxfont::rectText(_("Page Break (bottom)"), pb_font, w, a, d);
3518                 p.pain->rectText((ww - w) / 2, y + d,
3519                         _("Page Break (bottom)"),
3520                         pb_font, backgroundColor(), backgroundColor());
3521
3522                 y_bottom -= 3 * defaultHeight();
3523         }
3524
3525         // draw the additional space if needed:
3526         int const height =  getLengthMarkerHeight(p.bv,
3527                                                   parparams.spaceBottom());
3528         y_bottom -= drawLengthMarker(p, _("Space below"),
3529                                      parparams.spaceBottom(),
3530                                      p.yo + y_bottom - height);
3531
3532         Buffer const * buffer = p.bv->buffer();
3533
3534         // draw a bottom line
3535         if (parparams.lineBottom()) {
3536                 LyXFont font(LyXFont::ALL_SANE);
3537                 int const asc = lyxfont::ascent('x',
3538                         getFont(buffer, par,
3539                         max(pos_type(0), par->size() - 1)));
3540
3541                 y_bottom -= asc;
3542
3543                 int const w = (inset_owner ?  inset_owner->width(p.bv, font) : ww);
3544                 int const xp = static_cast<int>(inset_owner ? p.xo : 0);
3545                 int const y = p.yo + y_bottom;
3546                 p.pain->line(xp, y, xp + w, y, LColor::topline, Painter::line_solid,
3547                           Painter::line_thick);
3548
3549                 y_bottom -= asc;
3550         }
3551
3552         bool const is_rtl = p.row->par()->isRightToLeftPar(p.bv->buffer()->params);
3553         int const endlabel = par->getEndLabel(buffer->params);
3554
3555         // draw an endlabel
3556         switch (endlabel) {
3557         case END_LABEL_BOX:
3558         case END_LABEL_FILLED_BOX:
3559         {
3560                 LyXFont const font = getLabelFont(buffer, par);
3561                 int const size = int(0.75 * lyxfont::maxAscent(font));
3562                 int const y = (p.yo + p.row->baseline()) - size;
3563                 int x = is_rtl ? LYX_PAPER_MARGIN : ww - LYX_PAPER_MARGIN - size;
3564
3565                 if (p.row->fill() <= size)
3566                         x += (size - p.row->fill() + 1) * (is_rtl ? -1 : 1);
3567
3568                 if (endlabel == END_LABEL_BOX) {
3569                         p.pain->rectangle(x, y, size, size, LColor::eolmarker);
3570                 } else {
3571                         p.pain->fillRectangle(x, y, size, size,
3572                                               LColor::eolmarker);
3573                 }
3574                 break;
3575         }
3576         case END_LABEL_STATIC:
3577         {
3578                 LyXFont font(LyXFont::ALL_SANE);
3579                 string const & layout = par->layout();
3580                 string const str = textclasslist[buffer->params.textclass][layout].endlabelstring();
3581                 font = getLabelFont(buffer, par);
3582                 int const x = is_rtl ?
3583                         int(p.x) - lyxfont::width(str, font)
3584                         : ww - rightMargin(buffer, p.row) - p.row->fill();
3585                 p.pain->text(x, p.yo + p.row->baseline(), str, font);
3586                 break;
3587         }
3588         case END_LABEL_NO_LABEL:
3589                 break;
3590         }
3591 }
3592
3593 void LyXText::paintRowText(DrawRowParams & p)
3594 {
3595         Paragraph * par = p.row->par();
3596         Buffer const * buffer = p.bv->buffer();
3597
3598         pos_type const last = rowLastPrintable(p.row);
3599         pos_type main_body =
3600                 beginningOfMainBody(buffer, par);
3601         if (main_body > 0 &&
3602                 (main_body - 1 > last ||
3603                 !par->isLineSeparator(main_body - 1))) {
3604                 main_body = 0;
3605         }
3606
3607         LyXLayout const & layout =
3608                 textclasslist[buffer->params.textclass][par->layout()];
3609
3610         pos_type vpos = p.row->pos();
3611         while (vpos <= last) {
3612                 if (p.x > p.bv->workWidth())
3613                         break;
3614                 pos_type pos = vis2log(vpos);
3615                 if (p.x + singleWidth(p.bv, par, pos) < 0) {
3616                         p.x += singleWidth(p.bv, par, pos);
3617                         ++vpos;
3618                         continue;
3619                 }
3620                 if (main_body > 0 && pos == main_body - 1) {
3621                         int const lwidth = lyxfont::width(layout.labelsep,
3622                                 getLabelFont(buffer, par));
3623
3624                         p.x += p.label_hfill + lwidth
3625                                 - singleWidth(p.bv, par, main_body - 1);
3626                 }
3627
3628                 if (par->isHfill(pos)) {
3629                         p.x += 1;
3630
3631                         int const y0 = p.yo + p.row->baseline();
3632                         int const y1 = y0 - defaultHeight() / 2;
3633
3634                         p.pain->line(int(p.x), y1, int(p.x), y0,
3635                                      LColor::added_space);
3636
3637                         if (hfillExpansion(buffer, p.row, pos)) {
3638                                 int const y2 = (y0 + y1) / 2;
3639
3640                                 if (pos >= main_body) {
3641                                         p.pain->line(int(p.x), y2,
3642                                                   int(p.x + p.hfill), y2,
3643                                                   LColor::added_space,
3644                                                   Painter::line_onoffdash);
3645                                         p.x += p.hfill;
3646                                 } else {
3647                                         p.pain->line(int(p.x), y2,
3648                                                   int(p.x + p.label_hfill), y2,
3649                                                   LColor::added_space,
3650                                                   Painter::line_onoffdash);
3651                                         p.x += p.label_hfill;
3652                                 }
3653                                 p.pain->line(int(p.x), y1,
3654                                              int(p.x), y0,
3655                                              LColor::added_space);
3656                         }
3657                         p.x += 2;
3658                         ++vpos;
3659                 } else if (par->isSeparator(pos)) {
3660                         p.x += singleWidth(p.bv, par, pos);
3661                         if (pos >= main_body)
3662                                 p.x += p.separator;
3663                         ++vpos;
3664                 } else {
3665                         draw(p, vpos);
3666                 }
3667         }
3668 }
3669
3670
3671 void LyXText::getVisibleRow(BufferView * bv, int y_offset, int x_offset,
3672                             Row * row, int y, bool cleared)
3673 {
3674         if (row->height() <= 0) {
3675                 lyxerr << "LYX_ERROR: row.height: "
3676                        << row->height() << endl;
3677                 return;
3678         }
3679
3680         DrawRowParams p;
3681
3682         // set up drawing parameters
3683         p.bv = bv;
3684         p.pain = &bv->painter();
3685         p.row = row;
3686         p.xo = x_offset;
3687         p.yo = y_offset;
3688         prepareToPrint(bv, row, p.x, p.separator, p.hfill, p.label_hfill);
3689         if (inset_owner && (p.x < 0))
3690                 p.x = 0;
3691         p.x += p.xo;
3692         p.y = y;
3693         p.width = inset_owner ? inset_owner->textWidth(bv, true) : bv->workWidth();
3694         p.cleared = cleared;
3695
3696         // start painting
3697
3698         // clear to background if necessary
3699         p.cleared = paintRowBackground(p);
3700
3701         // paint the selection background
3702         if (selection.set()) {
3703                 paintRowSelection(p);
3704         }
3705
3706         // vertical lines for appendix
3707         paintRowAppendix(p);
3708
3709         // environment depth brackets
3710         paintRowDepthBar(p);
3711
3712         // draw any stuff wanted for a first row of a paragraph
3713         if (!row->pos()) {
3714                 paintFirstRow(p);
3715         }
3716
3717         // draw any stuff wanted for the last row of a paragraph
3718         if (!row->next() || (row->next()->par() != row->par())) {
3719                 paintLastRow(p);
3720         }
3721
3722         // paint text
3723         paintRowText(p);
3724 }
3725
3726
3727 int LyXText::defaultHeight() const
3728 {
3729         LyXFont font(LyXFont::ALL_SANE);
3730         return int(lyxfont::maxAscent(font) + lyxfont::maxDescent(font) * 1.5);
3731 }
3732
3733
3734 /* returns the column near the specified x-coordinate of the row
3735 * x is set to the real beginning of this column  */
3736 pos_type
3737 LyXText::getColumnNearX(BufferView * bview, Row * row, int & x,
3738                         bool & boundary) const
3739 {
3740         float tmpx = 0.0;
3741         float fill_separator;
3742         float fill_hfill;
3743         float fill_label_hfill;
3744
3745         prepareToPrint(bview, row, tmpx, fill_separator,
3746                        fill_hfill, fill_label_hfill);
3747
3748         pos_type vc = row->pos();
3749         pos_type last = rowLastPrintable(row);
3750         pos_type c = 0;
3751         LyXLayout const & layout =
3752                 textclasslist[bview->buffer()->params.textclass][
3753                                     row->par()->layout()];
3754         bool left_side = false;
3755
3756         pos_type main_body = beginningOfMainBody(bview->buffer(), row->par());
3757         float last_tmpx = tmpx;
3758
3759         if (main_body > 0 &&
3760             (main_body - 1 > last ||
3761              !row->par()->isLineSeparator(main_body - 1)))
3762                 main_body = 0;
3763
3764         while (vc <= last && tmpx <= x) {
3765                 c = vis2log(vc);
3766                 last_tmpx = tmpx;
3767                 if (main_body > 0 && c == main_body-1) {
3768                         tmpx += fill_label_hfill +
3769                                 lyxfont::width(layout.labelsep,
3770                                                getLabelFont(bview->buffer(), row->par()));
3771                         if (row->par()->isLineSeparator(main_body - 1))
3772                                 tmpx -= singleWidth(bview, row->par(), main_body-1);
3773                 }
3774
3775                 if (hfillExpansion(bview->buffer(), row, c)) {
3776                         x += singleWidth(bview, row->par(), c);
3777                         if (c >= main_body)
3778                                 tmpx += fill_hfill;
3779                         else
3780                                 tmpx += fill_label_hfill;
3781                 }
3782                 else if (row->par()->isSeparator(c)) {
3783                         tmpx += singleWidth(bview, row->par(), c);
3784                         if (c >= main_body)
3785                                 tmpx+= fill_separator;
3786                 } else
3787                         tmpx += singleWidth(bview, row->par(), c);
3788                 ++vc;
3789         }
3790
3791         if ((tmpx + last_tmpx) / 2 > x) {
3792                 tmpx = last_tmpx;
3793                 left_side = true;
3794         }
3795
3796         if (vc > last + 1)  // This shouldn't happen.
3797                 vc = last + 1;
3798
3799         boundary = false;
3800         bool const lastrow = lyxrc.rtl_support // This is not needed, but gives
3801                                          // some speedup if rtl_support=false
3802                 && (!row->next() || row->next()->par() != row->par());
3803         bool const rtl = (lastrow)
3804                 ? row->par()->isRightToLeftPar(bview->buffer()->params)
3805                 : false; // If lastrow is false, we don't need to compute
3806                          // the value of rtl.
3807
3808         if (row->pos() > last)  // Row is empty?
3809                 c = row->pos();
3810         else if (lastrow &&
3811                  ((rtl &&  left_side && vc == row->pos() && x < tmpx - 5) ||
3812                    (!rtl && !left_side && vc == last + 1   && x > tmpx + 5)))
3813                 c = last + 1;
3814         else if (vc == row->pos()) {
3815                 c = vis2log(vc);
3816                 if (bidi_level(c) % 2 == 1)
3817                         ++c;
3818         } else {
3819                 c = vis2log(vc - 1);
3820                 bool const rtl = (bidi_level(c) % 2 == 1);
3821                 if (left_side == rtl) {
3822                         ++c;
3823                         boundary = isBoundary(bview->buffer(), row->par(), c);
3824                 }
3825         }
3826
3827         if (row->pos() <= last && c > last
3828             && row->par()->isNewline(last)) {
3829                 if (bidi_level(last) % 2 == 0)
3830                         tmpx -= singleWidth(bview, row->par(), last);
3831                 else
3832                         tmpx += singleWidth(bview, row->par(), last);
3833                 c = last;
3834         }
3835
3836         c -= row->pos();
3837         x = int(tmpx);
3838         return c;
3839 }
3840
3841
3842 // returns pointer to a specified row
3843 Row * LyXText::getRow(Paragraph * par, pos_type pos, int & y) const
3844 {
3845         if (!firstrow)
3846                 return 0;
3847
3848         Row * tmprow = firstrow;
3849         y = 0;
3850
3851         // find the first row of the specified paragraph
3852         while (tmprow->next() && tmprow->par() != par) {
3853                 y += tmprow->height();
3854                 tmprow = tmprow->next();
3855         }
3856
3857         // now find the wanted row
3858         while (tmprow->pos() < pos
3859                && tmprow->next()
3860                && tmprow->next()->par() == par
3861                && tmprow->next()->pos() <= pos) {
3862                 y += tmprow->height();
3863                 tmprow = tmprow->next();
3864         }
3865
3866         return tmprow;
3867 }
3868
3869
3870 Row * LyXText::getRowNearY(int & y) const
3871 {
3872 #if 1
3873         // If possible we should optimize this method. (Lgb)
3874         Row * tmprow = firstrow;
3875         int tmpy = 0;
3876
3877         while (tmprow->next() && tmpy + tmprow->height() <= y) {
3878                 tmpy += tmprow->height();
3879                 tmprow = tmprow->next();
3880         }
3881
3882         y = tmpy;   // return the real y
3883
3884         //lyxerr << "returned y = " << y << endl;
3885
3886         return tmprow;
3887 #else
3888         // Search from the current cursor position.
3889
3890         Row * tmprow = cursor.row();
3891         int tmpy = cursor.y() - tmprow->baseline();
3892
3893         lyxerr << "cursor.y() = " << tmpy << endl;
3894         lyxerr << "tmprow->height() = " << tmprow->height() << endl;
3895         lyxerr << "tmprow->baseline() = " << tmprow->baseline() << endl;
3896         lyxerr << "first = " << first << endl;
3897         lyxerr << "y = " << y << endl;
3898
3899         if (y < tmpy) {
3900                 lyxerr << "up" << endl;
3901 #if 0
3902                 while (tmprow && tmpy - tmprow->height() >= y) {
3903                         tmpy -= tmprow->height();
3904                         tmprow = tmprow->previous();
3905                 }
3906 #else
3907                 do {
3908                         tmpy -= tmprow->height();
3909                         tmprow = tmprow->previous();
3910                 } while (tmprow && tmpy - tmprow->height() >= y);
3911 #endif
3912         } else if (y > tmpy) {
3913                 lyxerr << "down" << endl;
3914
3915                 while (tmprow->next() && tmpy + tmprow->height() <= y) {
3916                         tmpy += tmprow->height();
3917                         tmprow = tmprow->next();
3918                 }
3919         } else {
3920                 lyxerr << "equal" << endl;
3921         }
3922
3923         y = tmpy; // return the real y
3924
3925         lyxerr << "returned y = " << y << endl;
3926
3927         return tmprow;
3928
3929 #endif
3930 }
3931
3932
3933 int LyXText::getDepth() const
3934 {
3935         return cursor.par()->getDepth();
3936 }