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