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