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