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