]> git.lyx.org Git - lyx.git/blob - src/text.C
Make LFUN_QUOTE work for InsetText.
[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         if (is_rtl) {
2200                 x = (workWidth(bview) > 0)
2201                         ? RightMargin(bview->buffer(), row) : 0;
2202 #ifndef NEW_INSETS
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 #endif
2209         } else
2210                 x = (workWidth(bview) > 0) ? LeftMargin(bview, row) : 0;
2211         
2212         // is there a manual margin with a manual label
2213         if (textclasslist.Style(bview->buffer()->params.textclass,
2214                            row->par()->GetLayout()).margintype == MARGIN_MANUAL
2215             && textclasslist.Style(bview->buffer()->params.textclass,
2216                               row->par()->GetLayout()).labeltype == LABEL_MANUAL) {
2217                
2218                 /* one more since labels are left aligned */ 
2219                 nlh = NumberOfLabelHfills(bview->buffer(), row) + 1;
2220                 if (nlh && !row->par()->GetLabelWidthString().empty()) {
2221                         fill_label_hfill = LabelFill(bview, row) / nlh;
2222                 }
2223         }
2224                 
2225         // are there any hfills in the row?
2226         float const nh = NumberOfHfills(bview->buffer(), row);
2227
2228         if (nh)
2229           fill_hfill = w / nh;
2230         else  {
2231                 // is it block, flushleft or flushright? 
2232                 // set x how you need it
2233         int align;
2234 #ifndef NEW_INSETS
2235         if (row->par()->FirstPhysicalPar()->align == LYX_ALIGN_LAYOUT)
2236           align = textclasslist.Style(bview->buffer()->params.textclass, row->par()->GetLayout()).align;
2237         else
2238           align = row->par()->FirstPhysicalPar()->align;
2239 #else
2240         if (row->par()->align == LYX_ALIGN_LAYOUT)
2241           align = textclasslist.Style(bview->buffer()->params.textclass, row->par()->GetLayout()).align;
2242         else
2243           align = row->par()->align;
2244 #endif
2245            
2246         // center displayed insets 
2247         Inset * inset;
2248            if (row->par()->GetChar(row->pos()) == LyXParagraph::META_INSET
2249                && (inset=row->par()->GetInset(row->pos()))
2250                && (inset->display())) // || (inset->scroll() < 0)))
2251              align = (inset->LyxCode() == Inset::MATHMACRO_CODE)
2252                      ? LYX_ALIGN_BLOCK : LYX_ALIGN_CENTER;
2253
2254            switch (align) {
2255             case LYX_ALIGN_BLOCK:
2256               ns = NumberOfSeparators(bview->buffer(), row);
2257               if (ns && row->next() && row->next()->par() == row->par() &&
2258                   !(row->next()->par()->IsNewline(row->next()->pos() - 1))
2259                   && !(row->next()->par()->GetChar(row->next()->pos()) == LyXParagraph::META_INSET
2260                        && row->next()->par()->GetInset(row->next()->pos())
2261                        && row->next()->par()->GetInset(row->next()->pos())->display())
2262                   )
2263                 fill_separator = w / ns;
2264               else if (is_rtl)
2265                 x += w;
2266               break;
2267             case LYX_ALIGN_RIGHT:
2268               x += w;
2269               break;
2270             case LYX_ALIGN_CENTER:
2271               x += w / 2;
2272               break;
2273            }
2274         }
2275         if (!bidi)
2276                 return;
2277
2278         ComputeBidiTables(bview->buffer(), row);
2279         if (is_rtl) {
2280                 LyXParagraph::size_type main_body = 
2281                         BeginningOfMainBody(bview->buffer(), row->par());
2282                 LyXParagraph::size_type last = RowLast(row);
2283
2284                 if (main_body > 0 &&
2285                     (main_body-1 > last || 
2286                      !row->par()->IsLineSeparator(main_body-1))) {
2287                         LyXLayout const & layout =
2288                                 textclasslist.Style(bview->buffer()->params.textclass,
2289                                                     row->par()->GetLayout());
2290                         x += lyxfont::width(layout.labelsep,
2291                                             GetFont(bview->buffer(), row->par(), -2));
2292                         if (main_body-1 <= last)
2293                                 x += fill_label_hfill;
2294                 }
2295         }
2296 }
2297       
2298 /* important for the screen */
2299
2300
2301 /* the cursor set functions have a special mechanism. When they
2302 * realize, that you left an empty paragraph, they will delete it.
2303 * They also delete the corresponding row */
2304
2305 void LyXText::CursorRightOneWord(BufferView * bview) const
2306 {
2307         // treat floats, HFills and Insets as words
2308         LyXCursor tmpcursor = cursor;
2309         // CHECK See comment on top of text.C
2310
2311         if (tmpcursor.pos() == tmpcursor.par()->Last()
2312             && tmpcursor.par()->Next()) {
2313                         tmpcursor.par(tmpcursor.par()->Next());
2314                         tmpcursor.pos(0);
2315         } else {
2316                 int steps = 0;
2317
2318                 // Skip through initial nonword stuff.
2319                 while (tmpcursor.pos() < tmpcursor.par()->Last() &&
2320                         ! tmpcursor.par()->IsWord( tmpcursor.pos() ) ) 
2321                 {
2322                   //    printf("Current pos1 %d", tmpcursor.pos()) ;
2323                         tmpcursor.pos(tmpcursor.pos() + 1);
2324                         ++steps;
2325                 }
2326                 // Advance through word.
2327                 while (tmpcursor.pos() < tmpcursor.par()->Last() &&
2328                         tmpcursor.par()->IsWord( tmpcursor.pos() ) )
2329                 {
2330                   //     printf("Current pos2 %d", tmpcursor.pos()) ;
2331                         tmpcursor.pos(tmpcursor.pos() + 1);
2332                         ++steps;
2333                 }
2334         }
2335         SetCursor(bview, tmpcursor.par(), tmpcursor.pos());
2336 }
2337
2338
2339 void LyXText::CursorTab(BufferView * bview) const
2340 {
2341     LyXCursor tmpcursor = cursor;
2342     while (tmpcursor.pos() < tmpcursor.par()->Last()
2343            && !tmpcursor.par()->IsNewline(tmpcursor.pos()))
2344         tmpcursor.pos(tmpcursor.pos() + 1);
2345    
2346     if (tmpcursor.pos() == tmpcursor.par()->Last()){
2347         if (tmpcursor.par()->Next()) {
2348             tmpcursor.par(tmpcursor.par()->Next());
2349             tmpcursor.pos(0);
2350         }
2351     } else
2352         tmpcursor.pos(tmpcursor.pos() + 1);
2353     SetCursor(bview, tmpcursor.par(), tmpcursor.pos());
2354 }
2355
2356
2357 /* -------> Skip initial whitespace at end of word and move cursor to *start*
2358             of prior word, not to end of next prior word. */
2359
2360 void LyXText::CursorLeftOneWord(BufferView * bview)  const
2361 {
2362         // treat HFills, floats and Insets as words
2363         LyXCursor tmpcursor = cursor;
2364         while (tmpcursor.pos() 
2365                && (tmpcursor.par()->IsSeparator(tmpcursor.pos() - 1) 
2366                    || tmpcursor.par()->IsKomma(tmpcursor.pos() - 1))
2367                && !(tmpcursor.par()->IsHfill(tmpcursor.pos() - 1)
2368 #ifndef NEW_INSETS
2369                     || tmpcursor.par()->IsFloat(tmpcursor.pos() - 1)
2370 #endif
2371                     || tmpcursor.par()->IsInset(tmpcursor.pos() - 1)))
2372                 tmpcursor.pos(tmpcursor.pos() - 1);
2373
2374         if (tmpcursor.pos()
2375             && (tmpcursor.par()->IsInset(tmpcursor.pos() - 1)
2376 #ifndef NEW_INSETS
2377                 || tmpcursor.par()->IsFloat(tmpcursor.pos() - 1)
2378 #endif
2379                 || tmpcursor.par()->IsHfill(tmpcursor.pos() - 1))) {
2380                 tmpcursor.pos(tmpcursor.pos() - 1);
2381         } else if (!tmpcursor.pos()) {
2382                 if (tmpcursor.par()->Previous()){
2383                         tmpcursor.par(tmpcursor.par()->Previous());
2384                         tmpcursor.pos(tmpcursor.par()->Last());
2385                 }
2386         } else {                // Here, tmpcursor != 0 
2387                 while (tmpcursor.pos() > 0 &&
2388                        tmpcursor.par()->IsWord(tmpcursor.pos()-1) )
2389                         tmpcursor.pos(tmpcursor.pos() - 1);
2390         }
2391         SetCursor(bview, tmpcursor.par(), tmpcursor.pos());
2392 }
2393
2394 /* -------> Select current word. This depends on behaviour of CursorLeftOneWord(), so it is
2395                         patched as well. */
2396
2397 void LyXText::SelectWord(BufferView * bview) 
2398 {
2399         // Move cursor to the beginning, when not already there.
2400         if (cursor.pos()
2401             && !cursor.par()->IsSeparator(cursor.pos()-1)
2402             && !cursor.par()->IsKomma(cursor.pos()-1) )
2403                 CursorLeftOneWord(bview);
2404
2405         // set the sel cursor
2406         sel_cursor = cursor;
2407
2408         while (cursor.pos() < cursor.par()->Last()
2409                && !cursor.par()->IsSeparator(cursor.pos())
2410                && !cursor.par()->IsKomma(cursor.pos()) )
2411                 cursor.pos(cursor.pos() + 1);
2412         SetCursor(bview, cursor.par(), cursor.pos() );
2413         
2414         // finally set the selection
2415         SetSelection(bview);
2416 }
2417
2418
2419 /* -------> Select the word currently under the cursor when:
2420                         1: no selection is currently set,
2421                         2: the cursor is not at the borders of the word. */
2422
2423 bool LyXText::SelectWordWhenUnderCursor(BufferView * bview) 
2424 {
2425         if (!selection &&
2426             cursor.pos() > 0 && cursor.pos() < cursor.par()->Last()
2427             && !cursor.par()->IsSeparator(cursor.pos())
2428             && !cursor.par()->IsKomma(cursor.pos())
2429             && !cursor.par()->IsSeparator(cursor.pos() -1)
2430             && !cursor.par()->IsKomma(cursor.pos() -1)) {
2431                 SelectWord(bview);
2432                 return true;
2433         }
2434         return false;
2435 }
2436
2437
2438 // This function is only used by the spellchecker for NextWord().
2439 // It doesn't handle LYX_ACCENTs and probably never will.
2440 string const LyXText::SelectNextWord(BufferView * bview,
2441                                      float & value) const
2442 {
2443         LyXParagraph * tmppar = cursor.par();
2444         
2445         // If this is not the very first word, skip rest of
2446         // current word because we are probably in the middle
2447         // of a word if there is text here.
2448         if (cursor.pos() || cursor.par()->previous) {
2449                 while (cursor.pos() < cursor.par()->Last()
2450                        && cursor.par()->IsLetter(cursor.pos()))
2451                         cursor.pos(cursor.pos() + 1);
2452         }
2453         // Now, skip until we have real text (will jump paragraphs)
2454         while ((cursor.par()->Last() > cursor.pos()
2455                 && (!cursor.par()->IsLetter(cursor.pos())
2456                     || cursor.par()->getFont(bview->buffer()->params, cursor.pos())
2457                     .latex() == LyXFont::ON))
2458                || (cursor.par()->Last() == cursor.pos() 
2459                    && cursor.par()->Next())){
2460                 if (cursor.pos() == cursor.par()->Last()) {
2461                         cursor.par(cursor.par()->Next());
2462                         cursor.pos(0);
2463                 } else
2464                         cursor.pos(cursor.pos() + 1);
2465         }
2466   
2467         // Update the value if we changed paragraphs
2468         if (cursor.par() != tmppar){
2469                 SetCursor(bview, cursor.par(), cursor.pos());
2470                 value = float(cursor.y())/float(height);
2471         }
2472
2473         // Start the selection from here
2474         sel_cursor = cursor;
2475
2476         std::ostringstream latex;
2477
2478         // and find the end of the word 
2479         // (optional hyphens are part of a word)
2480         while (cursor.pos() < cursor.par()->Last()
2481                && (cursor.par()->IsLetter(cursor.pos())) 
2482                    || (cursor.par()->GetChar(cursor.pos()) == LyXParagraph::META_INSET
2483                        && cursor.par()->GetInset(cursor.pos()) != 0
2484                        && cursor.par()->GetInset(cursor.pos())->Latex(bview->buffer(), latex, false, false) == 0
2485                        && latex.str() == "\\-"
2486                            ))
2487                 cursor.pos(cursor.pos() + 1);
2488
2489         // Finally, we copy the word to a string and return it
2490         string str;
2491         if (sel_cursor.pos() < cursor.pos()) {
2492                 LyXParagraph::size_type i;
2493                 for (i = sel_cursor.pos(); i < cursor.pos(); ++i) {
2494                         if (cursor.par()->GetChar(i) != LyXParagraph::META_INSET)
2495                                 str += cursor.par()->GetChar(i);
2496                 }
2497         }
2498         return str;
2499 }
2500
2501
2502 // This one is also only for the spellchecker
2503 void LyXText::SelectSelectedWord(BufferView * bview)
2504 {
2505         // move cursor to the beginning
2506         SetCursor(bview, sel_cursor.par(), sel_cursor.pos());
2507         
2508         // set the sel cursor
2509         sel_cursor = cursor;
2510
2511         std::ostringstream latex;
2512         
2513         // now find the end of the word
2514         while (cursor.pos() < cursor.par()->Last()
2515                && (cursor.par()->IsLetter(cursor.pos())
2516                    || (cursor.par()->GetChar(cursor.pos()) == LyXParagraph::META_INSET
2517                        && cursor.par()->GetInset(cursor.pos()) != 0
2518                        && cursor.par()->GetInset(cursor.pos())->Latex(bview->buffer(), latex, false, false) == 0
2519                        && latex.str() == "\\-"
2520                            )))
2521                 cursor.pos(cursor.pos() + 1);
2522         
2523         SetCursor(bview, cursor.par(), cursor.pos());
2524         
2525         // finally set the selection
2526         SetSelection(bview);
2527 }
2528
2529
2530 /* -------> Delete from cursor up to the end of the current or next word. */
2531 void LyXText::DeleteWordForward(BufferView * bview)
2532 {
2533         if (!cursor.par()->Last())
2534                 CursorRight(bview);
2535         else {
2536                 LyXCursor tmpcursor = cursor;
2537                 tmpcursor.row(0); // ??
2538                 selection = true; // to avoid deletion 
2539                 CursorRightOneWord(bview);
2540                 SetCursor(bview, tmpcursor, tmpcursor.par(), tmpcursor.pos());
2541                 sel_cursor = cursor;
2542                 cursor = tmpcursor;
2543                 SetSelection(bview); 
2544                 
2545                 /* -----> Great, CutSelection() gets rid of multiple spaces. */
2546                 CutSelection(bview);
2547         }
2548 }
2549
2550
2551 /* -------> Delete from cursor to start of current or prior word. */
2552 void LyXText::DeleteWordBackward(BufferView * bview)
2553 {
2554        if (!cursor.par()->Last())
2555                CursorLeft(bview);
2556        else {
2557                LyXCursor tmpcursor = cursor;
2558                tmpcursor.row(0); // ??
2559                selection = true; // to avoid deletion 
2560                CursorLeftOneWord(bview);
2561                SetCursor(bview, tmpcursor, tmpcursor.par(), tmpcursor.pos());
2562                sel_cursor = cursor;
2563                cursor = tmpcursor;
2564                SetSelection(bview);
2565                CutSelection(bview);
2566        }
2567 }
2568
2569
2570 /* -------> Kill to end of line. */
2571 void LyXText::DeleteLineForward(BufferView * bview)
2572 {
2573         if (!cursor.par()->Last())
2574                 // Paragraph is empty, so we just go to the right
2575                 CursorRight(bview);
2576         else {
2577                 LyXCursor tmpcursor = cursor;
2578                 // We can't store the row over a regular SetCursor
2579                 // so we set it to 0 and reset it afterwards.
2580                 tmpcursor.row(0); // ??
2581                 selection = true; // to avoid deletion 
2582                 CursorEnd(bview);
2583                 SetCursor(bview, tmpcursor, tmpcursor.par(), tmpcursor.pos());
2584                 sel_cursor = cursor;
2585                 cursor = tmpcursor;
2586                 SetSelection(bview);
2587                 // What is this test for ??? (JMarc)
2588                 if (!selection) {
2589                         DeleteWordForward(bview);
2590                 } else {
2591                         CutSelection(bview);
2592                 }
2593         }
2594 }
2595
2596
2597 // Change the case of a word at cursor position. 
2598 // This function directly manipulates LyXParagraph::text because there
2599 // is no LyXParagraph::SetChar currently. I did what I could to ensure
2600 // that it is correct. I guess part of it should be moved to
2601 // LyXParagraph, but it will have to change for 1.1 anyway. At least
2602 // it does not access outside of the allocated array as the older
2603 // version did. (JMarc) 
2604 void LyXText::ChangeWordCase(BufferView * bview, LyXText::TextCase action) 
2605 {
2606 #ifndef NEW_INSETS
2607         LyXParagraph * tmppar = cursor.par()->ParFromPos(cursor.pos());
2608 #else
2609         LyXParagraph * tmppar = cursor.par();
2610 #endif
2611
2612         SetUndo(bview->buffer(),Undo::FINISH, tmppar->previous, tmppar->next); 
2613
2614 #ifndef NEW_INSETS
2615         LyXParagraph::size_type tmppos = 
2616                 cursor.par()->PositionInParFromPos(cursor.pos());
2617 #else
2618         LyXParagraph::size_type tmppos = cursor.pos();
2619 #endif
2620         while (tmppos < tmppar->size()) {
2621                 unsigned char c = tmppar->GetChar(tmppos);
2622                 if (IsKommaChar(c) || IsLineSeparatorChar(c))
2623                         break;
2624                 if (c != LyXParagraph::META_INSET) {
2625                         switch (action) {
2626                         case text_lowercase:
2627                                 c = tolower(c);
2628                                 break;
2629                         case text_capitalization:
2630                                 c = toupper(c);
2631                                 action = text_lowercase;
2632                                 break;
2633                         case text_uppercase:
2634                                 c = toupper(c);
2635                                 break;
2636                         }
2637                 }
2638                 
2639                 //tmppar->text[tmppos] = c;
2640                 tmppar->SetChar(tmppos, c);
2641                 ++tmppos;
2642         }
2643         CheckParagraph(bview, tmppar, tmppos);
2644         CursorRightOneWord(bview);
2645 }
2646
2647
2648 void LyXText::Delete(BufferView * bview)
2649 {
2650         // this is a very easy implementation
2651
2652         LyXCursor old_cursor = cursor;
2653         int const old_cur_par_id = old_cursor.par()->id();
2654         int const old_cur_par_prev_id = old_cursor.par()->previous ?
2655                 old_cursor.par()->previous->id() : 0;
2656         
2657         // just move to the right
2658         CursorRight(bview);
2659
2660         // CHECK Look at the comment here.
2661         // This check is not very good...
2662         // The CursorRightIntern calls DeleteEmptyParagrapgMechanism
2663         // and that can very well delete the par or par->previous in
2664         // old_cursor. Will a solution where we compare paragraph id's
2665         //work better?
2666         if ((cursor.par()->previous ? cursor.par()->previous->id() : 0)
2667             == old_cur_par_prev_id
2668             && cursor.par()->id() != old_cur_par_id)
2669                 return; // delete-empty-paragraph-mechanism has done it
2670
2671         // if you had success make a backspace
2672         if (old_cursor.par() != cursor.par() || old_cursor.pos() != cursor.pos()) {
2673                 LyXCursor tmpcursor = cursor;
2674                 cursor = old_cursor; // to make sure undo gets the right cursor position
2675                 SetUndo(bview->buffer(), Undo::DELETE,
2676 #ifndef NEW_INSETS
2677                         cursor.par()->ParFromPos(cursor.pos())->previous, 
2678                         cursor.par()->ParFromPos(cursor.pos())->next
2679 #else
2680                         cursor.par()->previous, 
2681                         cursor.par()->next
2682 #endif
2683                         ); 
2684                 cursor = tmpcursor;
2685                 Backspace(bview);
2686         }
2687 }
2688
2689
2690 void LyXText::Backspace(BufferView * bview)
2691 {
2692         // Get the font that is used to calculate the baselineskip
2693         LyXParagraph::size_type lastpos = cursor.par()->Last();
2694         LyXFont rawparfont = cursor.par()->GetFontSettings(bview->buffer()->params,
2695                                                          lastpos - 1);
2696
2697         if (cursor.pos() == 0) {
2698                 // The cursor is at the beginning of a paragraph,
2699                 // so the the backspace will collapse two paragraphs into one.
2700                 
2701                 // we may paste some paragraphs
2702       
2703                 // is it an empty paragraph?
2704       
2705                 if ((lastpos == 0
2706                      || (lastpos == 1 && cursor.par()->IsSeparator(0)))
2707 #ifndef NEW_INSETS
2708                     && !(cursor.par()->Next() 
2709                          && cursor.par()->footnoteflag == LyXParagraph::NO_FOOTNOTE
2710                          && cursor.par()->Next()->footnoteflag == LyXParagraph::OPEN_FOOTNOTE)
2711 #endif
2712                         ) {
2713                         // This is an empty paragraph and we delete it just by moving the cursor one step
2714                         // left and let the DeleteEmptyParagraphMechanism handle the actual deletion
2715                         // of the paragraph.
2716                         
2717                         if (cursor.par()->previous) {
2718 #ifndef NEW_INSETS
2719                                 LyXParagraph * tmppar = cursor.par()->previous->FirstPhysicalPar();
2720 #else
2721                                 LyXParagraph * tmppar = cursor.par()->previous;
2722 #endif
2723                                 if (cursor.par()->GetLayout() == tmppar->GetLayout()
2724 #ifndef NEW_INSETS
2725                                     && cursor.par()->footnoteflag == tmppar->footnoteflag
2726 #endif
2727                                     && cursor.par()->GetAlign() == tmppar->GetAlign()) {
2728                                         // Inherit botom DTD from the paragraph below.
2729                                         // (the one we are deleting)
2730                                         tmppar->line_bottom = cursor.par()->line_bottom;
2731                                         tmppar->added_space_bottom = cursor.par()->added_space_bottom;
2732                                         tmppar->pagebreak_bottom = cursor.par()->pagebreak_bottom;
2733                                 }
2734                                 
2735                                 CursorLeft(bview);
2736                      
2737                                 // the layout things can change the height of a row !
2738                                 int const tmpheight = cursor.row()->height();
2739                                 SetHeightOfRow(bview, cursor.row());
2740                                 if (cursor.row()->height() != tmpheight) {
2741                                         refresh_y = cursor.y() - cursor.row()->baseline();
2742                                         refresh_row = cursor.row();
2743                                         status = LyXText::NEED_MORE_REFRESH;
2744                                 }
2745                                 return;
2746                         }
2747                 }
2748
2749 #ifndef NEW_INSETS
2750                 if (cursor.par()->ParFromPos(cursor.pos())->previous){
2751                         SetUndo(bview->buffer(), Undo::DELETE,
2752                                 cursor.par()->ParFromPos(cursor.pos())->previous->previous,
2753                                 cursor.par()->ParFromPos(cursor.pos())->next);
2754                 }
2755 #else
2756                 if (cursor.par()->previous) {
2757                         SetUndo(bview->buffer(), Undo::DELETE,
2758                                 cursor.par()->previous->previous,
2759                                 cursor.par()->next);
2760                 }
2761 #endif
2762                 
2763                 LyXParagraph * tmppar = cursor.par();
2764                 Row * tmprow = cursor.row();
2765
2766                 // We used to do CursorLeftIntern() here, but it is
2767                 // not a good idea since it triggers the auto-delete
2768                 // mechanism. So we do a CursorLeftIntern()-lite,
2769                 // without the dreaded mechanism. (JMarc)
2770                 if (cursor.par()->Previous()) { 
2771                         // steps into the above paragraph.
2772                         SetCursorIntern(bview, cursor.par()->Previous(), 
2773                                         cursor.par()->Previous()->Last(), false);
2774                 }
2775
2776                 /* Pasting is not allowed, if the paragraphs have different
2777                    layout. I think it is a real bug of all other
2778                    word processors to allow it. It confuses the user.
2779                    Even so with a footnote paragraph and a non-footnote
2780                    paragraph. I will not allow pasting in this case, 
2781                    because the user would be confused if the footnote behaves 
2782                    different wether it is open or closed.
2783                   
2784                    Correction: Pasting is always allowed with standard-layout
2785                 */
2786                 if (cursor.par() != tmppar
2787                     && (cursor.par()->GetLayout() == tmppar->GetLayout()
2788                         || tmppar->GetLayout() == 0 /*standard*/)
2789 #ifndef NEW_INSETS
2790                     && cursor.par()->footnoteflag == tmppar->footnoteflag
2791 #endif
2792                     && cursor.par()->GetAlign() == tmppar->GetAlign()) {
2793
2794                         RemoveParagraph(tmprow);
2795                         RemoveRow(tmprow);
2796                         cursor.par()->PasteParagraph(bview->buffer()->params);
2797                         
2798                         if (!cursor.pos() || !cursor.par()->IsSeparator(cursor.pos() - 1))
2799                                 ; //cursor.par()->InsertChar(cursor.pos(), ' ');
2800                         // strangely enough it seems that commenting out the line above removes
2801                         // most or all of the segfaults. I will however also try to move the
2802                         // two Remove... lines in front of the PasteParagraph too.
2803                         else
2804                                 if (cursor.pos())
2805                                         cursor.pos(cursor.pos() - 1);
2806                         
2807                         status = LyXText::NEED_MORE_REFRESH;
2808                         refresh_row = cursor.row();
2809                         refresh_y = cursor.y() - cursor.row()->baseline();
2810                         
2811                         // remove the lost paragraph
2812                         // This one is not safe, since the paragraph that the tmprow and the
2813                         // following rows belong to has been deleted by the PasteParagraph
2814                         // above. The question is... could this be moved in front of the
2815                         // PasteParagraph?
2816                         //RemoveParagraph(tmprow);
2817                         //RemoveRow(tmprow);  
2818                         
2819                         // This rebuilds the rows.
2820                         AppendParagraph(bview, cursor.row());
2821                         UpdateCounters(bview, cursor.row());
2822                         
2823                         // the row may have changed, block, hfills etc.
2824                         SetCursor(bview, cursor.par(), cursor.pos(), false);
2825                 }
2826         } else {
2827                 /* this is the code for a normal backspace, not pasting
2828                  * any paragraphs */ 
2829                 SetUndo(bview->buffer(), Undo::DELETE,
2830 #ifndef NEW_INSETS
2831                         cursor.par()->ParFromPos(cursor.pos())->previous, 
2832                         cursor.par()->ParFromPos(cursor.pos())->next
2833 #else
2834                         cursor.par()->previous, 
2835                         cursor.par()->next
2836 #endif
2837                         ); 
2838                 // We used to do CursorLeftIntern() here, but it is
2839                 // not a good idea since it triggers the auto-delete
2840                 // mechanism. So we do a CursorLeftIntern()-lite,
2841                 // without the dreaded mechanism. (JMarc)
2842                 SetCursorIntern(bview, cursor.par(), cursor.pos()- 1,
2843                                 false, cursor.boundary());
2844                 
2845                 // some insets are undeletable here
2846                 if (cursor.par()->GetChar(cursor.pos()) == LyXParagraph::META_INSET) {
2847                         if (!cursor.par()->GetInset(cursor.pos())->Deletable())
2848                                 return; 
2849                         // force complete redo when erasing display insets
2850                         // this is a cruel method but safe..... Matthias 
2851                         if (cursor.par()->GetInset(cursor.pos())->display() ||
2852                             cursor.par()->GetInset(cursor.pos())->needFullRow()) {
2853                                 cursor.par()->Erase(cursor.pos());
2854                                 RedoParagraph(bview);
2855                                 return;
2856                         }
2857                 }
2858                 
2859                 Row * row = cursor.row();
2860                 int y = cursor.y() - row->baseline();
2861                 LyXParagraph::size_type z;
2862                 /* remember that a space at the end of a row doesnt count
2863                  * when calculating the fill */ 
2864                 if (cursor.pos() < RowLast(row) ||
2865                     !cursor.par()->IsLineSeparator(cursor.pos())) {
2866                         row->fill(row->fill() + SingleWidth(bview,
2867                                                             cursor.par(),
2868                                                             cursor.pos()));
2869                 }
2870                 
2871                 /* some special code when deleting a newline. This is similar
2872                  * to the behavior when pasting paragraphs */ 
2873                 if (cursor.pos() && cursor.par()->IsNewline(cursor.pos())) {
2874                         cursor.par()->Erase(cursor.pos());
2875                         // refresh the positions
2876                         Row * tmprow = row;
2877                         while (tmprow->next() && tmprow->next()->par() == row->par()) {
2878                                 tmprow = tmprow->next();
2879                                 tmprow->pos(tmprow->pos() - 1);
2880                         }
2881                         if (cursor.par()->IsLineSeparator(cursor.pos() - 1))
2882                                 cursor.pos(cursor.pos() - 1);
2883                         
2884                         if (cursor.pos() < cursor.par()->Last() && !cursor.par()->IsSeparator(cursor.pos())) {
2885                                 cursor.par()->InsertChar(cursor.pos(), ' ');
2886                                 SetCharFont(bview->buffer(), cursor.par(), 
2887                                             cursor.pos(), current_font);
2888                                 // refresh the positions
2889                                 tmprow = row;
2890                                 while (tmprow->next() && tmprow->next()->par() == row->par()) {
2891                                         tmprow = tmprow->next();
2892                                         tmprow->pos(tmprow->pos() + 1);
2893                                 }
2894                         }
2895                 } else {
2896                         cursor.par()->Erase(cursor.pos());
2897                         
2898                         // refresh the positions
2899                         Row * tmprow = row;
2900                         while (tmprow->next()
2901                                && tmprow->next()->par() == row->par()) {
2902                                 tmprow = tmprow->next();
2903                                 tmprow->pos(tmprow->pos() - 1);
2904                         }
2905
2906                         // delete newlines at the beginning of paragraphs
2907                         while (cursor.par()->Last() &&
2908                                cursor.par()->IsNewline(cursor.pos()) &&
2909                                cursor.pos() == BeginningOfMainBody(bview->buffer(),
2910                                                                    cursor.par())) {
2911                                 cursor.par()->Erase(cursor.pos());
2912                                 // refresh the positions
2913                                 tmprow = row;
2914                                 while (tmprow->next() && 
2915                                        tmprow->next()->par() == row->par()) {
2916                                         tmprow = tmprow->next();
2917                                         tmprow->pos(tmprow->pos() - 1);
2918                                 }
2919                         }
2920                 }
2921                 
2922                 // is there a break one row above
2923                 if (row->previous() && row->previous()->par() == row->par()) {
2924                         z = NextBreakPoint(bview, row->previous(),
2925                                            workWidth(bview));
2926                         if (z >= row->pos()) {
2927                                 row->pos(z + 1);
2928                                 
2929                                 Row * tmprow = row->previous();
2930                                 
2931                                 // maybe the current row is now empty
2932                                 if (row->pos() >= row->par()->Last()) {
2933                                         // remove it
2934                                         RemoveRow(row);
2935                                         need_break_row = 0;
2936                                 } else {
2937                                         BreakAgainOneRow(bview, row);
2938                                         if (row->next() && row->next()->par() == row->par())
2939                                                 need_break_row = row->next();
2940                                         else
2941                                                 need_break_row = 0;
2942                                 }
2943                                 
2944                                 // set the dimensions of the row above
2945                                 y -= tmprow->height();
2946                                 tmprow->fill(Fill(bview, tmprow,
2947                                                   workWidth(bview)));
2948                                 SetHeightOfRow(bview, tmprow);
2949                                 
2950                                 refresh_y = y;
2951                                 refresh_row = tmprow;
2952                                 status = LyXText::NEED_MORE_REFRESH;
2953                                 SetCursor(bview, cursor.par(), cursor.pos(),
2954                                           false, cursor.boundary());
2955                                 //current_font = rawtmpfont;
2956                                 //real_current_font = realtmpfont;
2957                                 // check, whether the last character's font has changed.
2958                                 if (rawparfont !=
2959                                     cursor.par()->GetFontSettings(bview->buffer()->params,
2960                                                                   cursor.par()->Last() - 1))
2961                                         RedoHeightOfParagraph(bview, cursor);
2962                                 return;
2963                         }
2964                 }
2965                 
2966                 // break the cursor row again
2967                 if (row->next() && row->next()->par() == row->par() &&
2968                     (RowLast(row) == row->par()->Last() - 1 ||
2969                      NextBreakPoint(bview, row, workWidth(bview)) != RowLast(row))) {
2970                         
2971                         /* it can happen that a paragraph loses one row
2972                          * without a real breakup. This is when a word
2973                          * is to long to be broken. Well, I don t care this 
2974                          * hack ;-) */ 
2975                         if (RowLast(row) == row->par()->Last() - 1)
2976                                 RemoveRow(row->next());
2977                         
2978                         refresh_y = y;
2979                         refresh_row = row;
2980                         status = LyXText::NEED_MORE_REFRESH;
2981                         
2982                         BreakAgainOneRow(bview, row);
2983                         // will the cursor be in another row now?
2984                         if (row->next() && row->next()->par() == row->par() &&
2985                             RowLast(row) <= cursor.pos()) {
2986                                 row = row->next();
2987                                 BreakAgainOneRow(bview, row);
2988                         }
2989
2990                         SetCursor(bview, cursor.par(), cursor.pos(), false, cursor.boundary());
2991
2992                         if (row->next() && row->next()->par() == row->par())
2993                                 need_break_row = row->next();
2994                         else
2995                                 need_break_row = 0;
2996                 } else  {
2997                         // set the dimensions of the row
2998                         row->fill(Fill(bview, row, workWidth(bview)));
2999                         int const tmpheight = row->height();
3000                         SetHeightOfRow(bview, row);
3001                         if (tmpheight == row->height())
3002                                 status = LyXText::NEED_VERY_LITTLE_REFRESH;
3003                         else
3004                                 status = LyXText::NEED_MORE_REFRESH;
3005                         refresh_y = y;
3006                         refresh_row = row;
3007                         SetCursor(bview, cursor.par(), cursor.pos(), false, cursor.boundary());
3008                 }
3009         }
3010
3011         // current_font = rawtmpfont;
3012         // real_current_font = realtmpfont;
3013
3014         if (IsBoundary(bview->buffer(), cursor.par(), cursor.pos())
3015             != cursor.boundary())
3016                 SetCursor(bview, cursor.par(), cursor.pos(), false,
3017                           !cursor.boundary());
3018
3019         lastpos = cursor.par()->Last();
3020         if (cursor.pos() == lastpos)
3021                 SetCurrentFont(bview);
3022         
3023         // check, whether the last characters font has changed.
3024         if (rawparfont != 
3025             cursor.par()->GetFontSettings(bview->buffer()->params, lastpos - 1)) {
3026                 RedoHeightOfParagraph(bview, cursor);
3027         } else {
3028                 // now the special right address boxes
3029                 if (textclasslist.Style(bview->buffer()->params.textclass,
3030                                         cursor.par()->GetLayout()).margintype == MARGIN_RIGHT_ADDRESS_BOX) {
3031                         RedoDrawingOfParagraph(bview, cursor); 
3032                 }
3033         }
3034 }
3035
3036
3037 void LyXText::GetVisibleRow(BufferView * bview, int y_offset, int x_offset,
3038                             Row * row_ptr, int y, bool cleared)
3039 {
3040         /* returns a printed row */
3041         Painter & pain = bview->painter();
3042         
3043         bool const is_rtl =
3044                 row_ptr->par()->isRightToLeftPar(bview->buffer()->params);
3045         
3046         LyXParagraph::size_type const last = RowLastPrintable(row_ptr);
3047
3048         LyXParagraph::size_type vpos, pos;
3049         float x;
3050         float tmpx;
3051         int y_top;
3052         int y_bottom;
3053
3054         LyXFont font(LyXFont::ALL_SANE);
3055         int maxdesc;
3056         if (row_ptr->height() <= 0) {
3057                 lyxerr << "LYX_ERROR: row.height: "
3058                        << row_ptr->height() << endl;
3059                 return;
3060         }
3061
3062         float fill_separator;
3063         float fill_hfill;
3064         float fill_label_hfill;
3065         PrepareToPrint(bview, row_ptr, x, fill_separator,
3066                        fill_hfill, fill_label_hfill);
3067         
3068         if (inset_owner && (x < 0))
3069                 x = 0;
3070         x += x_offset;
3071         
3072         // clear the area where we want to paint/print
3073         int ww = bview->workWidth();
3074
3075         bool clear_area = true;
3076         Inset * inset = 0;
3077
3078         if (!bview->screen()->forceClear() && last == row_ptr->pos()
3079             && row_ptr->par()->GetChar(row_ptr->pos()) == LyXParagraph::META_INSET
3080             && (inset = row_ptr->par()->GetInset(row_ptr->pos()))) {
3081                 clear_area = inset->doClearArea();
3082         }
3083         // we don't need to clear it's already done!!!
3084         if (cleared) {
3085                 clear_area = true;
3086         } else if (clear_area) {
3087 #ifdef WITH_WARNINGS
3088 #warning Should be fixed with a lyxinset::clear_width(bv, font) function! (Jug)
3089 #warning Should we not fix this in the Painter, please have a look Lars! (Jug)
3090 #endif
3091                 int w = (inset_owner ? inset_owner->width(bview, font)-2 : ww);
3092                 int h = row_ptr->height();
3093                 int x = x_offset;
3094                 int y = y_offset;
3095                 if (y < 0) {
3096                     h += y;
3097                     y = 0;
3098                 }
3099
3100                 pain.fillRectangle(x, y, w, h);
3101         } else if (inset != 0) {
3102                 int h = row_ptr->baseline() - inset->ascent(bview, font);
3103                 if (h > 0) {
3104                         int const w = (inset_owner ?
3105                                  inset_owner->width(bview, font) : ww);
3106                         pain.fillRectangle(x_offset, y_offset, w, h);
3107                 }
3108                 h += inset->ascent(bview, font) + inset->descent(bview, font);
3109                 if ((row_ptr->height() - h) > 0) {
3110                         int const w = (inset_owner ?
3111                                  inset_owner->width(bview, font) : ww);
3112                         pain.fillRectangle(x_offset, y_offset + h,
3113                                            w, row_ptr->height() - h);
3114                 }
3115                 if (!inset_owner && !inset->display() && !inset->needFullRow())
3116                 {
3117                         int const w = inset->width(bview, font) + int(x);
3118                         pain.fillRectangle(w, y_offset, ww - w, row_ptr->height());
3119                 }
3120         }
3121         
3122         if (selection) {
3123                 int const w = (inset_owner ?
3124                                inset_owner->width(bview, font) : ww);
3125                 /* selection code */
3126                 if (bidi_same_direction) {
3127                         if (sel_start_cursor.row() == row_ptr &&
3128                             sel_end_cursor.row() == row_ptr) {
3129                                 if (sel_start_cursor.x() < sel_end_cursor.x())
3130                                         pain.fillRectangle(x_offset + sel_start_cursor.x(),
3131                                                            y_offset,
3132                                                            sel_end_cursor.x() - sel_start_cursor.x(),
3133                                                            row_ptr->height(),
3134                                                            LColor::selection);
3135                                 else
3136                                         pain.fillRectangle(x_offset + sel_end_cursor.x(),
3137                                                            y_offset,
3138                                                            sel_start_cursor.x() - sel_end_cursor.x(),
3139                                                            row_ptr->height(),
3140                                                            LColor::selection);
3141                         } else if (sel_start_cursor.row() == row_ptr) {
3142                                 if (is_rtl)
3143                                         pain.fillRectangle(x_offset, y_offset,
3144                                                            sel_start_cursor.x(),
3145                                                            row_ptr->height(),
3146                                                            LColor::selection);
3147                                 else
3148                                         pain.fillRectangle(x_offset + sel_start_cursor.x(),
3149                                                            y_offset,
3150                                                            w - sel_start_cursor.x(),
3151                                                            row_ptr->height(),
3152                                                            LColor::selection);
3153                         } else if (sel_end_cursor.row() == row_ptr) {
3154                                 if (is_rtl)
3155                                         pain.fillRectangle(x_offset + sel_end_cursor.x(),
3156                                                            y_offset,
3157                                                            w - sel_end_cursor.x(),
3158                                                            row_ptr->height(),
3159                                                            LColor::selection);
3160                                 else
3161                                         pain.fillRectangle(x_offset, y_offset,
3162                                                            sel_end_cursor.x(),
3163                                                            row_ptr->height(),
3164                                                            LColor::selection);
3165                         } else if (y > sel_start_cursor.y()
3166                                    && y < sel_end_cursor.y()) {
3167                                 pain.fillRectangle(x_offset, y_offset, w,
3168                                                    row_ptr->height(),
3169                                                    LColor::selection);
3170                         }
3171                 } else if (sel_start_cursor.row() != row_ptr &&
3172                             sel_end_cursor.row() != row_ptr &&
3173                             y > sel_start_cursor.y()
3174                             && y < sel_end_cursor.y()) {
3175                         pain.fillRectangle(x_offset, y_offset, w,
3176                                            row_ptr->height(),
3177                                            LColor::selection);
3178                 } else if (sel_start_cursor.row() == row_ptr ||
3179                            sel_end_cursor.row() == row_ptr) {
3180                         float tmpx = x;
3181                         if ((sel_start_cursor.row() != row_ptr && !is_rtl) ||
3182                              (sel_end_cursor.row() != row_ptr && is_rtl))
3183                                 pain.fillRectangle(x_offset, y_offset,
3184                                                    int(tmpx),
3185                                                    row_ptr->height(),
3186                                                    LColor::selection);
3187                         LyXParagraph::size_type main_body =
3188                                 BeginningOfMainBody(bview->buffer(),
3189                                                     row_ptr->par());
3190                         
3191                         for (vpos = row_ptr->pos(); vpos <= last; ++vpos)  {
3192                                 pos = vis2log(vpos);
3193                                 float const old_tmpx = tmpx;
3194                                 if (main_body > 0 && pos == main_body-1) {
3195                                         tmpx += fill_label_hfill +
3196                                                 lyxfont::width(textclasslist.Style(bview->buffer()->params.textclass,
3197                                                                                    row_ptr->par()->GetLayout()).labelsep,
3198                                                                GetFont(bview->buffer(),row_ptr->par(), -2));
3199                                         if (row_ptr->par()->IsLineSeparator(main_body-1))
3200                                                 tmpx -= SingleWidth(bview, row_ptr->par(), main_body-1);
3201                                 }
3202                                 if (HfillExpansion(bview->buffer(), row_ptr, pos)) {
3203                                         tmpx += SingleWidth(bview, row_ptr->par(), pos);
3204                                         if (pos >= main_body)
3205                                                 tmpx += fill_hfill;
3206                                         else 
3207                                                 tmpx += fill_label_hfill;
3208                                 }
3209                                 else if (row_ptr->par()->IsSeparator(pos)) {
3210                                         tmpx += SingleWidth(bview, row_ptr->par(), pos);
3211                                         if (pos >= main_body)
3212                                                 tmpx += fill_separator;
3213                                 } else
3214                                         tmpx += SingleWidth(bview, row_ptr->par(), pos);
3215                                 
3216                                 if ((sel_start_cursor.row() != row_ptr ||
3217                                       sel_start_cursor.pos() <= pos) &&
3218                                      (sel_end_cursor.row() != row_ptr ||
3219                                       pos < sel_end_cursor.pos()) )
3220                                         /// Here we do not use x_offset as x_offset was
3221                                         // added to x.
3222                                         pain.fillRectangle(int(old_tmpx),
3223                                                            y_offset,
3224                                                            int(tmpx - old_tmpx + 1),
3225                                                            row_ptr->height(),
3226                                                            LColor::selection);
3227                         }
3228
3229                         if ((sel_start_cursor.row() != row_ptr && is_rtl) ||
3230                              (sel_end_cursor.row() != row_ptr && !is_rtl) )
3231                                 pain.fillRectangle(x_offset + int(tmpx),
3232                                                    y_offset,
3233                                                    int(ww - tmpx),
3234                                                    row_ptr->height(),
3235                                                    LColor::selection);
3236                 }
3237         }
3238
3239         int box_x = 0;
3240 #ifndef NEW_INSETS
3241         if (row_ptr->par()->footnoteflag == LyXParagraph::OPEN_FOOTNOTE) {
3242                 LyXFont font(LyXFont::ALL_SANE);
3243                 font.setSize(LyXFont::SIZE_FOOTNOTE);
3244                 font.setColor(LColor::footnote);
3245                 
3246                 box_x = LYX_PAPER_MARGIN + lyxfont::width(" wide-tab ", font);
3247                 if (row_ptr->previous() &&
3248                     row_ptr->previous()->par()->footnoteflag != LyXParagraph::OPEN_FOOTNOTE){
3249                         string fs;
3250                         switch (row_ptr->par()->footnotekind) {
3251                         case LyXParagraph::MARGIN:
3252                                 fs = " margin";
3253                                 break;
3254                         case LyXParagraph::FIG:
3255                                 fs = " fig";
3256                                 break;
3257                         case LyXParagraph::TAB:
3258                                 fs = " tab";
3259                                 break;
3260                         case LyXParagraph::WIDE_FIG:
3261                                 fs = " wide-fig";
3262                                 break;
3263                         case LyXParagraph::WIDE_TAB:
3264                                 fs = " wide-tab";
3265                                 break;
3266                         case LyXParagraph::ALGORITHM:
3267                                 fs = " alg";
3268                                 break;
3269                         case LyXParagraph::FOOTNOTE:
3270                                 fs = " foot";
3271                                 break;
3272                         }
3273                         
3274                         pain.fillRectangle(LYX_PAPER_MARGIN,
3275                                            y_offset + 1,
3276                                            box_x - LYX_PAPER_MARGIN,
3277                                            int(lyxfont::maxAscent(font)
3278                                                + lyxfont::maxDescent(font)),
3279                                            LColor::footnotebg);
3280                         
3281                         pain.line(LYX_PAPER_MARGIN, y_offset,
3282                                   workWidth(bview) - LYX_PAPER_MARGIN, y_offset,
3283                                   LColor::footnoteframe);
3284                         
3285                         pain.text(LYX_PAPER_MARGIN,
3286                                   y_offset + int(lyxfont::maxAscent(font)) + 1,
3287                                   fs, font);
3288                         
3289                         pain.line(LYX_PAPER_MARGIN, y_offset,
3290                                   LYX_PAPER_MARGIN,
3291                                   y_offset + int(lyxfont::maxAscent(font)
3292                                                + lyxfont::maxDescent(font)),
3293                                   LColor::footnoteframe);
3294                         
3295                         pain.line(LYX_PAPER_MARGIN,
3296                                   y_offset + int(lyxfont::maxAscent(font)
3297                                                + lyxfont::maxDescent(font)) + 1,
3298                                   box_x,
3299                                   y_offset + int(lyxfont::maxAscent(font)
3300                                                + lyxfont::maxDescent(font)) + 1,
3301                                   LColor::footnoteframe);
3302                         
3303                 }
3304                 
3305                 /* draw the open floats in a red box */
3306                 pain.line(box_x, y_offset,
3307                           box_x, y_offset + row_ptr->height(),
3308                           LColor::footnoteframe);
3309                 
3310                 pain.line(workWidth(bview) - LYX_PAPER_MARGIN,
3311                           y_offset,
3312                           workWidth(bview) - LYX_PAPER_MARGIN,
3313                           y_offset + row_ptr->height(),
3314                           LColor::footnoteframe);
3315
3316
3317                 // Draw appendix lines
3318                 LyXParagraph * p = row_ptr->par()->PreviousBeforeFootnote()->FirstPhysicalPar();
3319                 if (p->appendix){
3320                         pain.line(1, y_offset,
3321                                   1, y_offset + row_ptr->height(),
3322                                   LColor::appendixline);
3323                         pain.line(workWidth(bview) - 2, y_offset,
3324                                   workWidth(bview) - 2,
3325                                   y_offset + row_ptr->height(),
3326                                   LColor::appendixline);
3327                 }
3328
3329                 // Draw minipage line
3330                 bool const minipage =
3331                         (p->pextra_type == LyXParagraph::PEXTRA_MINIPAGE);
3332                 if (minipage)
3333                         pain.line(LYX_PAPER_MARGIN/5, y_offset,
3334                                   LYX_PAPER_MARGIN/5, 
3335                                   y_offset + row_ptr->height() - 1,
3336                                   LColor::minipageline);
3337
3338                 // Draw depth lines
3339                 int const depth = p->GetDepth();
3340                 for (int i = 1; i <= depth; ++i) {
3341                         int const line_x = (LYX_PAPER_MARGIN / 5) *
3342                                 (i + minipage);
3343                         pain.line(line_x, y_offset, line_x,
3344                                   y_offset + row_ptr->height() - 1,
3345                                   LColor::depthbar);
3346                 }
3347         } else if (row_ptr->previous() &&
3348                    row_ptr->previous()->par()->footnoteflag
3349                    == LyXParagraph::OPEN_FOOTNOTE) {
3350                 LyXFont font(LyXFont::ALL_SANE);
3351                 font.setSize(LyXFont::SIZE_FOOTNOTE);
3352                 
3353                 int const box_x = LYX_PAPER_MARGIN
3354                         + lyxfont::width(" wide-tab ", font);
3355                 
3356                 pain.line(box_x, y_offset,
3357                           workWidth(bview) - LYX_PAPER_MARGIN,
3358                           y_offset, LColor::footnote);
3359         }
3360 #endif
3361         // Draw appendix lines
3362 #ifndef NEW_INSETS
3363         LyXParagraph * firstpar = row_ptr->par()->FirstPhysicalPar();
3364 #else
3365         LyXParagraph * firstpar = row_ptr->par();
3366 #endif
3367         if (firstpar->appendix){
3368                 pain.line(1, y_offset,
3369                           1, y_offset + row_ptr->height(),
3370                           LColor::appendixline);
3371                 pain.line(ww - 2, y_offset,
3372                           ww - 2, y_offset + row_ptr->height(),
3373                           LColor::appendixline);
3374         }
3375
3376         // Draw minipage line
3377         bool const minipage =
3378                 (firstpar->pextra_type == LyXParagraph::PEXTRA_MINIPAGE);
3379         if (minipage)
3380                 pain.line(LYX_PAPER_MARGIN/5 + box_x, y_offset,
3381                           LYX_PAPER_MARGIN/5 + box_x, 
3382                           y_offset + row_ptr->height() - 1,
3383                           LColor::minipageline);
3384
3385         // Draw depth lines
3386         int const depth = firstpar->GetDepth();
3387         if (depth > 0) {
3388                 int next_depth = 0;
3389                 int prev_depth = 0;
3390                 if (row_ptr->next())
3391 #ifndef NEW_INSETS
3392                         if (row_ptr->par()->footnoteflag ==
3393                             row_ptr->next()->par()->footnoteflag)
3394                                 next_depth = row_ptr->next()->par()->GetDepth();
3395                         else if (row_ptr->par()->footnoteflag != LyXParagraph::OPEN_FOOTNOTE)
3396                                 next_depth = depth;
3397 #else
3398                                 next_depth = row_ptr->next()->par()->GetDepth();
3399 #endif
3400                 if (row_ptr->previous())
3401 #ifndef NEW_INSETS
3402                         if (row_ptr->par()->footnoteflag ==
3403                             row_ptr->previous()->par()->footnoteflag)
3404                                 prev_depth = row_ptr->previous()->par()->GetDepth();
3405                         else if (row_ptr->par()->footnoteflag != LyXParagraph::OPEN_FOOTNOTE)
3406                                 prev_depth = depth;
3407 #else
3408                                 prev_depth = row_ptr->previous()->par()->GetDepth();
3409 #endif
3410
3411                 for (int i = 1; i <= depth; ++i) {
3412                         int const line_x = (LYX_PAPER_MARGIN / 5) *
3413                                 (i + minipage) + box_x + x_offset;
3414                         pain.line(line_x, y_offset, line_x,
3415                                   y_offset + row_ptr->height() - 1 - (i - next_depth - 1) * 3,
3416                                   LColor::depthbar);
3417                 
3418                         if (i > prev_depth)
3419                                 pain.fillRectangle(line_x, y_offset, LYX_PAPER_MARGIN / 5, 2,
3420                                                    LColor::depthbar);
3421                         if (i > next_depth)
3422                                 pain.fillRectangle(line_x,
3423                                                    y_offset + row_ptr->height() - 2 - (i - next_depth - 1) * 3,
3424                                                    LYX_PAPER_MARGIN / 5, 2,
3425                                                    LColor::depthbar);
3426                 }
3427         }
3428
3429         
3430         LyXLayout const & layout =
3431                 textclasslist.Style(bview->buffer()->params.textclass,
3432                                     row_ptr->par()->GetLayout());
3433
3434         y_top = 0;
3435         y_bottom = row_ptr->height();
3436         
3437         /* is it a first row? */ 
3438         if (!row_ptr->pos() && (row_ptr->par() == firstpar)) {
3439                 
3440                 /* start of appendix? */
3441                 if (row_ptr->par()->start_of_appendix){
3442                         pain.line(1, y_offset,
3443                                   ww - 2, y_offset,
3444                                   LColor::appendixline);
3445                 }
3446                 
3447                 /* think about the margins */ 
3448                 if (!row_ptr->previous() && bv_owner)
3449                         y_top += LYX_PAPER_MARGIN;
3450                 
3451                 if (row_ptr->par()->pagebreak_top){ /* draw a top pagebreak  */
3452                         LyXFont pb_font;
3453                         pb_font.setColor(LColor::pagebreak).decSize();
3454                         int w = 0, a = 0, d = 0;
3455                         pain.line(0, y_offset + y_top + 2*DefaultHeight(),
3456                                   ww, 
3457                                   y_offset + y_top + 2 * DefaultHeight(),
3458                                   LColor::pagebreak, 
3459                                   Painter::line_onoffdash)
3460                                 .rectText(0,
3461                                           0,
3462                                           _("Page Break (top)"),
3463                                           pb_font,
3464                                           LColor::background,
3465                                           LColor::background, false, w, a, d);
3466                         pain.rectText((ww - w)/2,
3467                                       y_offset + y_top + 2 * DefaultHeight() + d,
3468                                       _("Page Break (top)"),
3469                                       pb_font,
3470                                       LColor::background,
3471                                       LColor::background);
3472                         y_top += 3 * DefaultHeight();
3473                 }
3474                 
3475                 if (row_ptr->par()->added_space_top.kind() == VSpace::VFILL) {
3476                         /* draw a vfill top  */
3477                         pain.line(0, y_offset + 2 + y_top,
3478                                   LYX_PAPER_MARGIN, y_offset + 2 + y_top,
3479                                   LColor::vfillline);
3480                         
3481                         pain.line(0, y_offset + y_top + 3 * DefaultHeight(),
3482                                   LYX_PAPER_MARGIN,
3483                                   y_offset + y_top + 3 * DefaultHeight(),
3484                                   LColor::vfillline);
3485                         
3486                         pain.line(LYX_PAPER_MARGIN / 2, y_offset + 2 + y_top,
3487                                   LYX_PAPER_MARGIN / 2,
3488                                   y_offset + y_top + 3 * DefaultHeight(),
3489                                   LColor::vfillline);
3490                         
3491                         y_top += 3 * DefaultHeight();
3492                 }
3493                 
3494                 /* think about user added space */ 
3495                 y_top += int(row_ptr->par()->added_space_top.inPixels(bview));
3496                 
3497                 /* think about the parskip */ 
3498                 /* some parskips VERY EASY IMPLEMENTATION */ 
3499                 if (bview->buffer()->params.paragraph_separation == BufferParams::PARSEP_SKIP) {
3500                         if (layout.latextype == LATEX_PARAGRAPH
3501                             && firstpar->GetDepth() == 0
3502                             && firstpar->Previous())
3503                                 y_top += bview->buffer()->params.getDefSkip().inPixels(bview);
3504                         else if (firstpar->Previous()
3505                                  && textclasslist.Style(bview->buffer()->params.textclass,
3506                                                         firstpar->Previous()->GetLayout()).latextype == LATEX_PARAGRAPH
3507                                  && firstpar->Previous()->GetDepth() == 0)
3508                                 // is it right to use defskip here, too? (AS) 
3509                                 y_top += bview->buffer()->params.getDefSkip().inPixels(bview);
3510                 }
3511                 
3512                 if (row_ptr->par()->line_top) {      /* draw a top line  */
3513                         y_top +=  lyxfont::ascent('x',
3514                                                   GetFont(bview->buffer(),
3515                                                           row_ptr->par(), 0));
3516                         int const w = (inset_owner ?
3517                                        inset_owner->width(bview, font) : ww);
3518                         int const xp = static_cast<int>(inset_owner ? x : 0);
3519                         pain.line(xp, y_offset + y_top,
3520                                   w, y_offset + y_top,
3521                                   LColor::topline,
3522                                   Painter::line_solid,
3523                                   Painter::line_thick);
3524                         
3525                         y_top +=  lyxfont::ascent('x',GetFont(bview->buffer(),
3526                                                               row_ptr->par(), 0));
3527                 }
3528                 
3529                 /* should we print a label? */ 
3530                 if (layout.labeltype >= LABEL_STATIC
3531                     && (layout.labeltype != LABEL_STATIC
3532                         || layout.latextype != LATEX_ENVIRONMENT
3533                         || row_ptr->par()->IsFirstInSequence())) {
3534                         font = GetFont(bview->buffer(), row_ptr->par(), -2);
3535                         if (!row_ptr->par()->GetLabelstring().empty()) {
3536                                 tmpx = x;
3537                                 string const tmpstring =
3538                                         row_ptr->par()->GetLabelstring();
3539                                 
3540                                 if (layout.labeltype == LABEL_COUNTER_CHAPTER) {
3541                                         if (bview->buffer()->params.secnumdepth >= 0) {
3542                                                 /* this is special code for the chapter layout. This is printed in
3543                                                  * an extra row and has a pagebreak at the top. */
3544                                                 float spacing_val = 1.0;
3545                                                 if (!row_ptr->par()->spacing.isDefault()) {
3546                                                         spacing_val = row_ptr->par()->spacing.getValue();
3547                                                 } else {
3548                                                         spacing_val = bview->buffer()->params.spacing.getValue();
3549                                                 }
3550    
3551                                                 maxdesc = int(lyxfont::maxDescent(font) * layout.spacing.getValue() * spacing_val)
3552                                                         + int(layout.parsep) * DefaultHeight();
3553                                                 if (is_rtl)
3554                                                         tmpx = ww - LeftMargin(bview, row_ptr) - 
3555                                                                 lyxfont::width(tmpstring, font);
3556                                                 pain.text(int(tmpx),
3557                                                           y_offset + row_ptr->baseline() - row_ptr->ascent_of_text() - maxdesc,
3558                                                           tmpstring, font);
3559                                         }
3560                                 } else {
3561                                         if (is_rtl) {
3562                                                 tmpx = ww - LeftMargin(bview, row_ptr)
3563                                                         + lyxfont::width(layout.labelsep, font);
3564 #ifndef NEW_INSETS
3565                                                 if (row_ptr->par()->footnoteflag == LyXParagraph::OPEN_FOOTNOTE)  {
3566                                                         LyXFont font(LyXFont::ALL_SANE);
3567                                                         font.setSize(LyXFont::SIZE_SMALL);
3568                                                         tmpx += lyxfont::width("Mwide-fixM", font);
3569                                                 }
3570 #endif
3571                                         } else
3572                                                 tmpx = x - lyxfont::width(layout.labelsep, font)
3573                                                         - lyxfont::width(tmpstring, font);
3574
3575                                         /* draw it! */
3576                                         pain.text(int(tmpx),
3577                                                   y_offset + row_ptr->baseline(),
3578                                                   tmpstring, font);
3579                                 }
3580                         }
3581                         /* the labels at the top of an environment. More or less for bibliography */ 
3582                 } else if (layout.labeltype == LABEL_TOP_ENVIRONMENT ||
3583                            layout.labeltype == LABEL_BIBLIO ||
3584                            layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT) {
3585                         if (row_ptr->par()->IsFirstInSequence()) {
3586                                 font = GetFont(bview->buffer(),
3587                                                row_ptr->par(), -2);
3588                                 if (!row_ptr->par()->GetLabelstring().empty()) {
3589                                         string const tmpstring =
3590                                                 row_ptr->par()->GetLabelstring();
3591                                         float spacing_val = 1.0;
3592                                         if (!row_ptr->par()->spacing.isDefault()) {
3593                                                 spacing_val = row_ptr->par()->spacing.getValue();
3594                                         } else {
3595                                                 spacing_val = bview->buffer()->params.spacing.getValue();
3596                                         }
3597    
3598                                         maxdesc = int(lyxfont::maxDescent(font) * layout.spacing.getValue() * spacing_val
3599                                                       + (layout.labelbottomsep * DefaultHeight()));
3600                                         
3601                                         tmpx = x;
3602                                         if (layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT){
3603                                                 tmpx = ( (is_rtl ? LeftMargin(bview, row_ptr) : x)
3604                                                          + ww - RightMargin(bview->buffer(), row_ptr) ) / 2; 
3605                                                 tmpx -= lyxfont::width(tmpstring, font) / 2;
3606                                         } else if (is_rtl)
3607                                                 tmpx = ww - LeftMargin(bview, row_ptr) - 
3608                                                         lyxfont::width(tmpstring, font);
3609                                         pain.text(int(tmpx),
3610                                                   y_offset + row_ptr->baseline()
3611                                                   - row_ptr->ascent_of_text()
3612                                                   - maxdesc,
3613                                                   tmpstring, font);
3614                                 }
3615                         }
3616                 }
3617                 if (layout.labeltype == LABEL_BIBLIO && row_ptr->par()->bibkey) {
3618                         font = GetFont(bview->buffer(), row_ptr->par(), -1);
3619                         if (is_rtl)
3620                                 tmpx = ww - LeftMargin(bview, row_ptr)
3621                                         + lyxfont::width(layout.labelsep, font);
3622                         else
3623                                 tmpx = x - lyxfont::width(layout.labelsep, font)
3624                                         - row_ptr->par()->bibkey->width(bview, font);
3625                         row_ptr->par()->bibkey->draw(bview, font,
3626                                                    y_offset + row_ptr->baseline(), 
3627                                                    tmpx, clear_area);
3628                 }
3629         }
3630         
3631         /* is it a last row? */
3632 #ifndef NEW_INSETS
3633         LyXParagraph * par = row_ptr->par()->LastPhysicalPar();
3634 #else
3635         LyXParagraph * par = row_ptr->par();
3636 #endif
3637         if (
3638 #ifndef NEW_INSETS
3639                 row_ptr->par()->ParFromPos(last + 1) == par
3640 #else
3641                 row_ptr->par() == par
3642 #endif
3643                 && (!row_ptr->next() || row_ptr->next()->par() != row_ptr->par()))
3644         {
3645                 /* think about the margins */ 
3646                 if (!row_ptr->next() && bv_owner)
3647                         y_bottom -= LYX_PAPER_MARGIN;
3648                 
3649                 /* draw a bottom pagebreak */ 
3650                 if (firstpar->pagebreak_bottom) {
3651                         LyXFont pb_font;
3652                         pb_font.setColor(LColor::pagebreak).decSize();
3653                         int w = 0, a = 0, d = 0;
3654                         pain.line(0,
3655                                   y_offset + y_bottom - 2 * DefaultHeight(), 
3656                                   ww, 
3657                                   y_offset + y_bottom - 2 * DefaultHeight(),
3658                                   LColor::pagebreak,
3659                                   Painter::line_onoffdash)
3660                                 .rectText(0,
3661                                           0,
3662                                           _("Page Break (bottom)"),
3663                                           pb_font,
3664                                           LColor::background,
3665                                           LColor::background, false, w, a, d);
3666                         pain.rectText((ww - w) / 2,
3667                                       y_offset + y_top + 2 * DefaultHeight() + d,
3668                                       _("Page Break (bottom)"),
3669                                       pb_font,
3670                                       LColor::background,
3671                                       LColor::background);
3672                         y_bottom -= 3 * DefaultHeight();
3673                 }
3674                 
3675                 if (firstpar->added_space_bottom.kind() == VSpace::VFILL) {
3676                         /* draw a vfill bottom  */
3677                         pain.line(0, y_offset + y_bottom - 3 * DefaultHeight(),
3678                                   LYX_PAPER_MARGIN,
3679                                   y_offset + y_bottom - 3 * DefaultHeight(),
3680                                   LColor::vfillline);
3681                         pain.line(0, y_offset + y_bottom - 2,
3682                                   LYX_PAPER_MARGIN,
3683                                   y_offset + y_bottom - 2,
3684                                   LColor::vfillline);
3685                         pain.line(LYX_PAPER_MARGIN / 2,
3686                                   y_offset + y_bottom - 3 * DefaultHeight(),
3687                                   LYX_PAPER_MARGIN / 2,
3688                                   y_offset + y_bottom - 2,
3689                                   LColor::vfillline);
3690                         y_bottom -= 3 * DefaultHeight();
3691                 }
3692                 
3693                 /* think about user added space */ 
3694                 y_bottom -= int(firstpar->added_space_bottom.inPixels(bview));
3695                 
3696                 if (firstpar->line_bottom) {
3697                         /* draw a bottom line */
3698                         y_bottom -= lyxfont::ascent('x', GetFont(bview->buffer(),
3699                                                                  par, par->Last() - 1));
3700                         int const w = (inset_owner ?
3701                                        inset_owner->width(bview, font) : ww);
3702                         int const xp = static_cast<int>(inset_owner ? x : 0);
3703                         pain.line(xp, y_offset + y_bottom,
3704                                   w, y_offset + y_bottom,
3705                                   LColor::topline, Painter::line_solid,
3706                                   Painter::line_thick);
3707                         y_bottom -= lyxfont::ascent('x',
3708                                                     GetFont(bview->buffer(),
3709                                                             par,
3710                                                             par->Last() - 1));
3711                 }
3712
3713                 // draw an endlabel
3714                 int const endlabel =
3715                         row_ptr->par()->GetEndLabel(bview->buffer()->params);
3716                 switch (endlabel) {
3717                 case END_LABEL_BOX:
3718                 case END_LABEL_FILLED_BOX:
3719                 {
3720                         LyXFont const font = GetFont(bview->buffer(),
3721                                                      row_ptr->par(), last);
3722                         int const size = int(0.75 * lyxfont::maxAscent(font));
3723                         int const y = (y_offset + row_ptr->baseline()) - size;
3724                         int x = is_rtl ? LYX_PAPER_MARGIN 
3725                                 : ww - LYX_PAPER_MARGIN - size;
3726 #ifndef NEW_INSETS
3727                         if (row_ptr->par()->footnoteflag == LyXParagraph::OPEN_FOOTNOTE)
3728                                 if (is_rtl) {
3729                                         LyXFont font(LyXFont::ALL_SANE);
3730                                         font.setSize(LyXFont::SIZE_SMALL);
3731                                         x += lyxfont::width("Mwide-figM", font);
3732                                 } else
3733                                         x -= LYX_PAPER_MARGIN/2;
3734 #endif
3735                         if (row_ptr->fill() <= size)
3736                                 x += (size - row_ptr->fill() + 1) * (is_rtl ? -1 : 1);
3737                         if (endlabel == END_LABEL_BOX) {
3738                                 pain.line(x, y, x, y + size,
3739                                           LColor::eolmarker);
3740                                 pain.line(x + size, y, x + size , y + size,
3741                                           LColor::eolmarker);
3742                                 pain.line(x, y, x + size, y,
3743                                           LColor::eolmarker);
3744                                 pain.line(x, y + size, x + size, y + size,
3745                                           LColor::eolmarker);
3746                         } else
3747                                 pain.fillRectangle(x, y, size, size,
3748                                                    LColor::eolmarker);
3749                         break;
3750                 }
3751                 case END_LABEL_STATIC:
3752                 {
3753                         LyXTextClass::LayoutList::size_type layout = row_ptr->par()->GetLayout();
3754                         string const tmpstring = textclasslist.
3755                                 Style(bview->buffer()->params.textclass,
3756                                       layout).endlabelstring();
3757                         font = GetFont(bview->buffer(), row_ptr->par(), -2);
3758                         int const tmpx = is_rtl ?
3759                                 int(x) - lyxfont::width(tmpstring, font)
3760                                 : ww - RightMargin(bview->buffer(), row_ptr) - row_ptr->fill();
3761                         pain.text( tmpx, y_offset + row_ptr->baseline(), tmpstring, font);
3762                         break;
3763                 }
3764                 case END_LABEL_NO_LABEL:
3765                         break;
3766                 }
3767         }
3768         
3769         /* draw the text in the pixmap */  
3770         
3771         vpos = row_ptr->pos();
3772
3773         LyXParagraph::size_type main_body = 
3774                 BeginningOfMainBody(bview->buffer(), row_ptr->par());
3775         if (main_body > 0 &&
3776             (main_body-1 > last || 
3777              !row_ptr->par()->IsLineSeparator(main_body - 1)))
3778                 main_body = 0;
3779         
3780         while (vpos <= last)  {
3781                 pos = vis2log(vpos);
3782                 if (main_body > 0 && pos == main_body - 1) {
3783                         x += fill_label_hfill
3784                                 + lyxfont::width(layout.labelsep,
3785                                                  GetFont(bview->buffer(),
3786                                                          row_ptr->par(), -2))
3787                                 - SingleWidth(bview,
3788                                               row_ptr->par(),
3789                                               main_body - 1);
3790                 }
3791                 
3792                 if (row_ptr->par() ->IsHfill(pos)) {
3793                         x += 1;
3794                         pain.line(int(x),
3795                                   y_offset + row_ptr->baseline() - DefaultHeight() / 2,
3796                                   int(x),
3797                                   y_offset + row_ptr->baseline(),
3798                                   LColor::vfillline);
3799                         
3800                         if (HfillExpansion(bview->buffer(),
3801                                            row_ptr, pos)) {
3802                                 if (pos >= main_body) {
3803                                         pain.line(int(x),
3804                                                   y_offset + row_ptr->baseline() - DefaultHeight() / 4,
3805                                                   int(x + fill_hfill),
3806                                                   y_offset + row_ptr->baseline() - DefaultHeight() / 4,
3807                                                   LColor::vfillline,
3808                                                   Painter::line_onoffdash);
3809                                         x += fill_hfill;
3810                                 } else {
3811                                         pain.line(int(x),
3812                                                   y_offset + row_ptr->baseline() - DefaultHeight() / 4,
3813                                                   int(x + fill_label_hfill),
3814                                                   y_offset + row_ptr->baseline() - DefaultHeight() / 4,
3815                                                   LColor::vfillline,
3816                                                   Painter::line_onoffdash);
3817                                         
3818                                         x += fill_label_hfill;
3819                                 }
3820                                 pain.line(int(x),
3821                                           y_offset + row_ptr->baseline() - DefaultHeight() / 2,
3822                                           int(x),
3823                                           y_offset + row_ptr->baseline(),
3824                                           LColor::vfillline);
3825                         }
3826                         x += 2;
3827                         ++vpos;
3828                 } else if (row_ptr->par()->IsSeparator(pos)) {
3829                         x += SingleWidth(bview,
3830                                          row_ptr->par(), pos);
3831                         if (pos >= main_body)
3832                                 x += fill_separator;
3833                         ++vpos;
3834                 } else
3835                         draw(bview, row_ptr, vpos, y_offset, x, clear_area);
3836         }
3837 }
3838
3839
3840 int LyXText::DefaultHeight() const
3841 {
3842         LyXFont font(LyXFont::ALL_SANE);
3843         return int(lyxfont::maxAscent(font) + lyxfont::maxDescent(font) * 1.5);
3844 }
3845
3846    
3847 /* returns the column near the specified x-coordinate of the row 
3848 * x is set to the real beginning of this column  */ 
3849 int LyXText::GetColumnNearX(BufferView * bview, Row * row, int & x,
3850                             bool & boundary) const
3851 {
3852         float tmpx = 0.0;
3853         float fill_separator, fill_hfill, fill_label_hfill;
3854    
3855         PrepareToPrint(bview, row, tmpx, fill_separator,
3856                        fill_hfill, fill_label_hfill);
3857
3858         LyXParagraph::size_type vc = row->pos();
3859         LyXParagraph::size_type last = RowLastPrintable(row);
3860         LyXParagraph::size_type c = 0;
3861         LyXLayout const & layout =
3862                 textclasslist.Style(bview->buffer()->params.textclass,
3863                                     row->par()->GetLayout());
3864         bool left_side = false;
3865
3866         LyXParagraph::size_type
3867                 main_body = BeginningOfMainBody(bview->buffer(), row->par());
3868         float last_tmpx = tmpx;
3869         
3870         if (main_body > 0 &&
3871             (main_body-1 > last || 
3872              !row->par()->IsLineSeparator(main_body - 1)))
3873                 main_body = 0;
3874         
3875         while (vc <= last && tmpx <= x) {
3876                 c = vis2log(vc);
3877                 last_tmpx = tmpx;
3878                 if (main_body > 0 && c == main_body-1) {
3879                         tmpx += fill_label_hfill +
3880                                 lyxfont::width(layout.labelsep,
3881                                                GetFont(bview->buffer(), row->par(), -2));
3882                         if (row->par()->IsLineSeparator(main_body - 1))
3883                                 tmpx -= SingleWidth(bview, row->par(), main_body-1);
3884                 }
3885                 
3886                 if (HfillExpansion(bview->buffer(), row, c)) {
3887                         x += SingleWidth(bview, row->par(), c);
3888                         if (c >= main_body)
3889                                 tmpx += fill_hfill;
3890                         else
3891                                 tmpx += fill_label_hfill;
3892                 }
3893                 else if (row->par()->IsSeparator(c)) {
3894                         tmpx += SingleWidth(bview, row->par(), c);
3895                         if (c >= main_body)
3896                                 tmpx+= fill_separator;
3897                 } else
3898                         tmpx += SingleWidth(bview, row->par(), c);
3899                 ++vc;
3900         }
3901         
3902         if ((tmpx + last_tmpx) / 2 > x) {
3903                 tmpx = last_tmpx;
3904                 left_side = true;
3905         }
3906
3907         if (vc > last + 1)  // This shouldn't happen.
3908                 vc = last + 1;
3909
3910         boundary = false;
3911         bool const lastrow = lyxrc.rtl_support // This is not needed, but gives
3912                                          // some speedup if rtl_support=false
3913                 && (!row->next() || row->next()->par() != row->par());
3914         bool const rtl = (lastrow)
3915                 ? row->par()->isRightToLeftPar(bview->buffer()->params)
3916                 : false; // If lastrow is false, we don't need to compute
3917                          // the value of rtl.
3918
3919         if (row->pos() > last)  // Row is empty?
3920                 c = row->pos();
3921         else if (lastrow &&
3922                  ( ( rtl &&  left_side && vc == row->pos() && x < tmpx - 5) ||
3923                    (!rtl && !left_side && vc == last + 1   && x > tmpx + 5) ))
3924                 c = last + 1;
3925         else if (vc == row->pos()) {
3926                 c = vis2log(vc);
3927                 if (bidi_level(c) % 2 == 1)
3928                         ++c;
3929         } else {
3930                 c = vis2log(vc - 1);
3931                 bool const rtl = (bidi_level(c) % 2 == 1);
3932                 if (left_side == rtl) {
3933                         ++c;
3934                         boundary = IsBoundary(bview->buffer(), row->par(), c);
3935                 }
3936         }
3937
3938         if (row->pos() <= last && c > last
3939             && row->par()->IsNewline(last)) {
3940                 if (bidi_level(last) % 2 == 0)
3941                         tmpx -= SingleWidth(bview, row->par(), last);
3942                 else
3943                         tmpx += SingleWidth(bview, row->par(), last);
3944                 c = last;
3945         }
3946
3947         c -= row->pos();
3948         x = int(tmpx);
3949         return c;
3950 }
3951
3952
3953 #ifndef NEW_INSETS
3954 /* turn the selection into a new environment. If there is no selection,
3955 * create an empty environment */ 
3956 void LyXText::InsertFootnoteEnvironment(BufferView * bview, 
3957                                         LyXParagraph::footnote_kind kind)
3958 {
3959    /* no footnoteenvironment in a footnoteenvironment */ 
3960    if (cursor.par()->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
3961       WriteAlert(_("Impossible operation"), 
3962                  _("You can't insert a float in a float!"), 
3963                  _("Sorry."));
3964      return;
3965    }
3966    /* no marginpars in minipages */
3967    if (kind == LyXParagraph::MARGIN 
3968       && cursor.par()->pextra_type == LyXParagraph::PEXTRA_MINIPAGE) {
3969       WriteAlert(_("Impossible operation"), 
3970                  _("You can't insert a marginpar in a minipage!"), 
3971                  _("Sorry."));
3972       return;
3973    }
3974    
3975    /* this doesnt make sense, if there is no selection */ 
3976    bool dummy_selection = false;
3977    if (!selection) {
3978       sel_start_cursor = cursor;       /* dummy selection  */
3979       sel_end_cursor = cursor;
3980       dummy_selection = true;
3981    }
3982    
3983    LyXParagraph * tmppar;
3984
3985    /* a test to make sure there is not already a footnote
3986     * in the selection. */
3987    
3988    tmppar = sel_start_cursor.par()->ParFromPos(sel_start_cursor.pos());
3989    
3990    while (tmppar != sel_end_cursor.par()->ParFromPos(sel_end_cursor.pos()) && 
3991           tmppar->footnoteflag == LyXParagraph::NO_FOOTNOTE)
3992      tmppar = tmppar->next;
3993    
3994    if (tmppar != sel_end_cursor.par()->ParFromPos(sel_end_cursor.pos())
3995        || tmppar->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
3996       WriteAlert(_("Impossible operation"), 
3997                  _("Float would include float!"), 
3998                  _("Sorry."));
3999       return;
4000    }
4001    
4002    /* ok we have a selection. This is always between sel_start_cursor
4003     * and sel_end cursor */
4004
4005    SetUndo(bview->buffer(), Undo::FINISH, 
4006            sel_start_cursor.par()->ParFromPos(sel_start_cursor.pos())->previous, 
4007            sel_end_cursor.par()->ParFromPos(sel_end_cursor.pos())->next); 
4008    
4009    if (sel_end_cursor.pos() > 0 
4010        && sel_end_cursor.par()->IsLineSeparator(sel_end_cursor.pos() - 1))
4011            sel_end_cursor.pos(sel_end_cursor.pos() - 1);
4012    /* please break before a space at the end */
4013    if (sel_start_cursor.par() == sel_end_cursor.par()
4014        && sel_start_cursor.pos() > sel_end_cursor.pos())
4015            sel_start_cursor.pos(sel_start_cursor.pos() - 1);
4016
4017    sel_end_cursor.par()->BreakParagraphConservative(bview->buffer()->params, sel_end_cursor.pos());
4018    
4019    sel_end_cursor.par(sel_end_cursor.par()->Next());
4020    sel_end_cursor.pos(0);
4021    
4022    // don't forget to insert a dummy layout paragraph if necessary
4023    if (sel_start_cursor.par()->GetLayout() != sel_end_cursor.par()->layout){
4024      sel_end_cursor.par()->BreakParagraphConservative(bview->buffer()->params, 0);
4025      sel_end_cursor.par()->layout = LYX_DUMMY_LAYOUT;
4026      sel_end_cursor.par(sel_end_cursor.par()->next);
4027    }
4028    else
4029      sel_end_cursor.par()->layout = LYX_DUMMY_LAYOUT;
4030
4031    cursor = sel_end_cursor;
4032
4033    /* please break behind a space, if there is one. The space should
4034     * be erased too */ 
4035    if (sel_start_cursor.pos() > 0 
4036        && sel_start_cursor.par()->IsLineSeparator(sel_start_cursor.pos() - 1))
4037      sel_start_cursor.pos(sel_start_cursor.pos() - 1);
4038    if (sel_start_cursor.par()->IsLineSeparator(sel_start_cursor.pos())) {
4039       sel_start_cursor.par()->Erase(sel_start_cursor.pos());
4040    }
4041    
4042    sel_start_cursor.par()->BreakParagraphConservative(bview->buffer()->params,
4043                                                     sel_start_cursor.pos());
4044    tmppar = sel_start_cursor.par()->Next();
4045    
4046    if (dummy_selection) {
4047            tmppar->Clear();
4048            if (kind == LyXParagraph::TAB
4049                || kind == LyXParagraph::FIG 
4050                || kind == LyXParagraph::WIDE_TAB
4051                || kind == LyXParagraph::WIDE_FIG 
4052                || kind == LyXParagraph::ALGORITHM) {
4053                    pair<bool, LyXTextClass::size_type> lres =
4054                            textclasslist.NumberOfLayout(bview->buffer()->params.textclass,
4055                                                         "Caption");
4056                    LyXTextClass::size_type lay;
4057                    if (lres.first) {
4058                            // layout fount
4059                            lay = lres.second;
4060                    } else {
4061                            // layout not found
4062                            lay = 0; // use default layout "Standard" (0)
4063                    }
4064                    tmppar->SetLayout(bview->buffer()->params, lay);
4065            }
4066    } else {
4067      if (sel_start_cursor.pos() > 0) {
4068        /* the footnote-environment should begin with a standard layout.
4069         * Imagine you insert a footnote within an enumeration, you 
4070         * certainly do not want an enumerated footnote! */ 
4071        tmppar->Clear();
4072      } else {
4073        /* this is a exception the user would sometimes expect, I hope */
4074        sel_start_cursor.par()->Clear();
4075      }
4076    }
4077    
4078    while (tmppar != sel_end_cursor.par()) {
4079       tmppar->footnoteflag = LyXParagraph::OPEN_FOOTNOTE;
4080       tmppar->footnotekind = kind;
4081       tmppar = tmppar->Next();
4082    }
4083
4084    RedoParagraphs(bview, sel_start_cursor, sel_end_cursor.par()->Next());
4085    
4086    SetCursor(bview, sel_start_cursor.par()->Next(), 0);
4087
4088    ClearSelection();
4089 }
4090 #endif
4091
4092
4093 // returns pointer to a specified row
4094 Row * LyXText::GetRow(LyXParagraph * par,
4095                       LyXParagraph::size_type pos, int & y) const
4096 {
4097         if (!firstrow)
4098                 return 0;
4099
4100         Row * tmprow = firstrow;
4101         y = 0;
4102         
4103         // find the first row of the specified paragraph
4104         while (tmprow->next() && tmprow->par() != par) {
4105                 y += tmprow->height();
4106                 tmprow = tmprow->next();
4107         }
4108         
4109         // now find the wanted row
4110         while (tmprow->pos() < pos
4111                && tmprow->next()
4112                && tmprow->next()->par() == par
4113                && tmprow->next()->pos() <= pos) {
4114                 y += tmprow->height();
4115                 tmprow = tmprow->next();
4116         }
4117         
4118         return tmprow;
4119 }