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