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