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