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