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