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