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