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