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