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