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