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