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