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