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