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