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