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