]> git.lyx.org Git - lyx.git/blob - src/text.C
GUI-indep toolbar and menus mostly work !
[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 (row_ptr->par()->ParFromPos(RowLast(row_ptr) + 1) == par
1632        && (!row_ptr->next() || row_ptr->next()->par() != row_ptr->par())) {     
1633           
1634           /* the paper margins */ 
1635           if (!par->next && bv_owner)
1636             maxdesc += LYX_PAPER_MARGIN;
1637         
1638           /* add the vertical spaces, that the user added */
1639           if (firstpar->added_space_bottom.kind() != VSpace::NONE)
1640                   maxdesc += int(firstpar->added_space_bottom.inPixels(bview));
1641           
1642           /* do not forget the DTP-lines! 
1643            * there height depends on the font of the nearest character */
1644           if (firstpar->line_bottom)
1645                   maxdesc += 2 * lyxfont::ascent('x', GetFont(bview->buffer(),
1646                                                               par, par->Last() - 1));
1647           
1648           /* and now the pagebreaks */
1649           if (firstpar->pagebreak_bottom)
1650             maxdesc += 3 * DefaultHeight();
1651           
1652           /* and now the layout spaces, for example before and after a section, 
1653            * or between the items of a itemize or enumerate environment */
1654           if (!firstpar->pagebreak_bottom && row_ptr->par()->Next()) {
1655              LyXParagraph * nextpar = row_ptr->par()->Next();
1656              LyXParagraph * comparepar = row_ptr->par();
1657              float usual = 0;
1658              float  unusual = 0;
1659              
1660              if (comparepar->GetDepth() > nextpar->GetDepth()) {
1661                 usual = (textclasslist.Style(bview->buffer()->params.textclass, comparepar->GetLayout()).bottomsep * DefaultHeight());
1662                 comparepar = comparepar->DepthHook(nextpar->GetDepth());
1663                 if (comparepar->GetLayout()!= nextpar->GetLayout()
1664                     || nextpar->GetLabelWidthString() != 
1665                         comparepar->GetLabelWidthString())
1666                   unusual = (textclasslist.Style(bview->buffer()->params.textclass, comparepar->GetLayout()).bottomsep * DefaultHeight());
1667                 
1668                 if (unusual > usual)
1669                   layoutdesc = unusual;
1670                 else
1671                   layoutdesc = usual;
1672              }
1673              else if (comparepar->GetDepth() ==  nextpar->GetDepth()) {
1674                 
1675                 if (comparepar->GetLayout()!= nextpar->GetLayout()
1676                     || nextpar->GetLabelWidthString() != 
1677                         comparepar->GetLabelWidthString())
1678                   layoutdesc = int(textclasslist.Style(bview->buffer()->params.textclass, comparepar->GetLayout()).bottomsep * DefaultHeight());
1679              }
1680           }
1681        }
1682    
1683    /* incalculate the layout spaces */ 
1684    maxasc += int(layoutasc * 2 / (2 + firstpar->GetDepth()));
1685    maxdesc += int(layoutdesc * 2 / (2 + firstpar->GetDepth()));
1686
1687 #ifndef NEW_TABULAR
1688    /* table stuff -- begin*/
1689    if (row_ptr->par()->table){
1690       maxasc += row_ptr->par()->table->
1691         AdditionalHeight(NumberOfCell(row_ptr->par(), row_ptr->pos()));
1692    }
1693    /* table stuff -- end*/
1694 #endif
1695    /* calculate the new height of the text */ 
1696    height -= row_ptr->height();
1697    
1698    row_ptr->height(maxasc + maxdesc + labeladdon);
1699    row_ptr->baseline(maxasc + labeladdon);
1700    
1701    height += row_ptr->height();
1702    float x, dummy;
1703    PrepareToPrint(bview, row_ptr, x, dummy, dummy, dummy, false);
1704    row_ptr->width(maxwidth+x);
1705    if (inset_owner) {
1706            Row * r = firstrow;
1707            width = max(0,workWidth(bview));
1708            while(r) {
1709                    if (r->width() > width)
1710                            width = r->width();
1711                    r = r->next();
1712            }
1713    }
1714 }
1715
1716
1717 /* Appends the implicit specified paragraph behind the specified row,
1718  * start at the implicit given position */
1719 void LyXText::AppendParagraph(BufferView * bview, Row * row) const
1720 {
1721    bool not_ready = true;
1722    
1723    // The last character position of a paragraph is an invariant so we can 
1724    // safely get it here. (Asger)
1725    int lastposition = row->par()->Last();
1726
1727    do {
1728       // Get the next breakpoint
1729       int z = NextBreakPoint(bview, row, workWidth(bview));
1730       
1731       Row * tmprow = row;
1732
1733       // Insert the new row
1734       if (z < lastposition) {
1735          ++z;
1736          InsertRow(row, row->par(), z);
1737          row = row->next();
1738
1739          row->height(0);
1740       } else
1741          not_ready = false;
1742       
1743       // Set the dimensions of the row
1744       tmprow->fill(Fill(bview, tmprow, workWidth(bview)));
1745       SetHeightOfRow(bview, tmprow);
1746
1747    } while (not_ready);
1748 }
1749
1750
1751 void LyXText::BreakAgain(BufferView * bview, Row * row) const
1752 {
1753    bool not_ready = true;
1754    
1755    do  {
1756       /* get the next breakpoint */
1757         LyXParagraph::size_type z = NextBreakPoint(bview, row, workWidth(bview));
1758       Row * tmprow = row;
1759       
1760       if (z < row->par()->Last() ) {
1761          if (!row->next() || (row->next() && row->next()->par() != row->par())) {
1762                  // insert a new row
1763             ++z;
1764             InsertRow(row, row->par(), z);
1765             row = row->next();
1766             row->height(0);
1767          } else  {
1768             row = row->next();
1769             ++z;
1770             if (row->pos() == z)
1771                     not_ready = false;     // the rest will not change
1772             else {
1773                row->pos(z);
1774             }
1775          }
1776       } else {
1777          /* if there are some rows too much, delete them */
1778          /* only if you broke the whole paragraph! */ 
1779          Row * tmprow2 = row;
1780          while (tmprow2->next() && tmprow2->next()->par() == row->par()) {
1781             tmprow2 = tmprow2->next();
1782          }
1783          while (tmprow2 != row) {
1784             tmprow2 = tmprow2->previous();
1785             RemoveRow(tmprow2->next());
1786          }
1787          not_ready = false;
1788       }
1789        
1790       /* set the dimensions of the row */ 
1791       tmprow->fill(Fill(bview, tmprow, workWidth(bview)));
1792       SetHeightOfRow(bview, tmprow);
1793    } while (not_ready);
1794 }
1795
1796
1797 // this is just a little changed version of break again
1798 void LyXText::BreakAgainOneRow(BufferView * bview, Row * row)
1799 {
1800         // get the next breakpoint
1801         LyXParagraph::size_type z = NextBreakPoint(bview, row, workWidth(bview));
1802         Row * tmprow = row;
1803         
1804         if (z < row->par()->Last() ) {
1805                 if (!row->next()
1806                     || (row->next() && row->next()->par() != row->par())) {
1807                         /* insert a new row */ 
1808                         ++z;
1809                         InsertRow(row, row->par(), z);
1810                         row = row->next();
1811                         row->height(0);
1812                 } else  {
1813                         row= row->next();
1814                         ++z;
1815                         if (row->pos() != z)
1816                                 row->pos(z);
1817                 }
1818         } else {
1819                 // if there are some rows too much, delete them
1820                 // only if you broke the whole paragraph!
1821                 Row * tmprow2 = row;
1822                 while (tmprow2->next()
1823                        && tmprow2->next()->par() == row->par()) {
1824                         tmprow2 = tmprow2->next();
1825                 }
1826                 while (tmprow2 != row) {
1827                         tmprow2 = tmprow2->previous();
1828                         RemoveRow(tmprow2->next());
1829                 }
1830         }
1831         
1832         // set the dimensions of the row
1833         tmprow->fill(Fill(bview, tmprow, workWidth(bview)));
1834         SetHeightOfRow(bview, tmprow);
1835 }
1836
1837
1838 void LyXText::BreakParagraph(BufferView * bview, char keep_layout)
1839 {
1840    LyXLayout const & layout = textclasslist.Style(bview->buffer()->params.textclass,
1841                                                   cursor.par()->GetLayout());
1842 #ifndef NEW_TABULAR   
1843    /* table stuff -- begin */
1844    if (cursor.par()->table) {
1845        // breaking of tables is only allowed at the beginning or the end */
1846        if (cursor.pos() && cursor.pos() < cursor.par()->size() &&
1847            !cursor.par()->table->ShouldBeVeryLastCell(NumberOfCell(cursor.par(), cursor.pos())))
1848                return; // no breaking of tables allowed
1849    }
1850    /* table stuff -- end */
1851 #endif
1852    // this is only allowed, if the current paragraph is not empty or caption
1853    if ((cursor.par()->Last() <= 0
1854 #ifndef NEW_INSETS
1855         && !cursor.par()->IsDummy()
1856 #endif
1857            )
1858        && 
1859        layout.labeltype!= LABEL_SENSITIVE)
1860      return;
1861
1862    SetUndo(bview->buffer(), Undo::INSERT, 
1863            cursor.par()->ParFromPos(cursor.pos())->previous, 
1864            cursor.par()->ParFromPos(cursor.pos())->next); 
1865
1866 #ifndef NEW_TABULAR
1867    /* table stuff -- begin */
1868    if (cursor.par()->table) {
1869        int cell = NumberOfCell(cursor.par(), cursor.pos());
1870        if (cursor.par()->table->ShouldBeVeryLastCell(cell))
1871            SetCursor(bview, cursor.par(), cursor.par()->size());
1872    }
1873    /* table stuff -- end */
1874 #endif
1875    // please break always behind a space
1876    if (cursor.pos() < cursor.par()->Last()
1877        && cursor.par()->IsLineSeparator(cursor.pos()))
1878      cursor.pos(cursor.pos() + 1);
1879    
1880    // break the paragraph
1881    if (keep_layout)
1882      keep_layout = 2;
1883    else 
1884      keep_layout = layout.isEnvironment();
1885    cursor.par()->BreakParagraph(bview->buffer()->params, cursor.pos(),
1886                                 keep_layout);
1887 #ifndef NEW_TABULAR
1888    /* table stuff -- begin */
1889    if (cursor.par()->table){
1890      // the table should stay with the contents
1891      if (!cursor.pos()){
1892        cursor.par()->Next()->table = cursor.par()->table;
1893        cursor.par()->table = 0;
1894      }
1895    }
1896    /* table stuff -- end */
1897 #endif
1898    // well this is the caption hack since one caption is really enough
1899    if (layout.labeltype == LABEL_SENSITIVE) {
1900      if (!cursor.pos())
1901              // set to standard-layout
1902              cursor.par()->SetLayout(bview->buffer()->params, 0);
1903      else
1904              // set to standard-layout
1905              cursor.par()->Next()->SetLayout(bview->buffer()->params, 0);
1906    }
1907    
1908    /* if the cursor is at the beginning of a row without prior newline, 
1909     * move one row up! 
1910     * This touches only the screen-update. Otherwise we would may have
1911     * an empty row on the screen */
1912    if (cursor.pos() && !cursor.row()->par()->IsNewline(cursor.row()->pos() - 1) &&
1913        cursor.row()->pos() == cursor.pos()) {
1914            CursorLeft(bview);
1915    } 
1916    
1917    status = LyXText::NEED_MORE_REFRESH;
1918    refresh_row = cursor.row();
1919    refresh_y = cursor.y() - cursor.row()->baseline();
1920    
1921    // Do not forget the special right address boxes
1922    if (layout.margintype == MARGIN_RIGHT_ADDRESS_BOX) {
1923       while (refresh_row->previous() &&
1924              refresh_row->previous()->par() == refresh_row->par()) {
1925               refresh_row = refresh_row->previous();
1926               refresh_y -= refresh_row->height();
1927       }
1928    }
1929    RemoveParagraph(cursor.row());
1930    
1931    // set the dimensions of the cursor row
1932    cursor.row()->fill(Fill(bview, cursor.row(), workWidth(bview)));
1933
1934    SetHeightOfRow(bview, cursor.row());
1935    
1936    while (
1937 #ifndef NEW_TABULAR
1938            !cursor.par()->Next()->table &&
1939 #endif
1940            cursor.par()->Next()->Last()
1941           && cursor.par()->Next()->IsNewline(0))
1942            cursor.par()->Next()->Erase(0);
1943    
1944    InsertParagraph(bview, cursor.par()->Next(), cursor.row());
1945
1946    UpdateCounters(bview, cursor.row()->previous());
1947    
1948    /* This check is necessary. Otherwise the new empty paragraph will
1949     * be deleted automatically. And it is more friendly for the user! */ 
1950    if (cursor.pos())
1951            SetCursor(bview, cursor.par()->Next(), 0);
1952    else
1953            SetCursor(bview, cursor.par(), 0);
1954    
1955    if (cursor.row()->next())
1956            BreakAgain(bview, cursor.row()->next());
1957
1958    need_break_row = 0;
1959 }
1960
1961
1962 #ifndef NEW_INSETS
1963 void LyXText::OpenFootnote(BufferView * bview)
1964 {
1965    LyXParagraph * endpar,* tmppar;
1966    Row * row;
1967    
1968    LyXParagraph * par = cursor.par()->ParFromPos(cursor.pos());
1969    
1970    /* if there is no footnote in this paragraph, just return. */ 
1971    if (!par->next
1972        || par->next->footnoteflag != LyXParagraph::CLOSED_FOOTNOTE)
1973      return;
1974    
1975    /* ok, move the cursor right before the footnote */ 
1976    
1977    /* just a little faster than using CursorRight() */
1978    for (cursor.pos(0);
1979         cursor.par()->ParFromPos(cursor.pos()) != par;) {
1980            cursor.pos(cursor.pos() + 1);
1981    }
1982    
1983    /* now the cursor is at the beginning of the physical par */
1984    SetCursor(bview, cursor.par(),
1985              cursor.pos() + cursor.par()->ParFromPos(cursor.pos())->size());
1986    
1987    /* the cursor must be exactly before the footnote */ 
1988    par = cursor.par()->ParFromPos(cursor.pos());
1989    
1990    status = LyXText::NEED_MORE_REFRESH;
1991    refresh_row = cursor.row();
1992    refresh_y = cursor.y() - cursor.row()->baseline();
1993    
1994    tmppar = cursor.par();
1995    endpar = cursor.par()->Next();
1996    row = cursor.row();
1997    
1998    tmppar->OpenFootnote(cursor.pos());
1999    RemoveParagraph(row);
2000    /* set the dimensions of the cursor row */
2001    row->fill(Fill(bview, row, workWidth(bview)));
2002    SetHeightOfRow(bview, row);
2003    // CHECK See comment on top of text.C
2004    tmppar = tmppar->Next();
2005    
2006    while (tmppar != endpar) {
2007       if (tmppar) {
2008          InsertParagraph(bview, tmppar, row);
2009          while (row->next() && row->next()->par() == tmppar)
2010            row = row->next();
2011          tmppar = tmppar->Next();
2012       }
2013    }
2014    SetCursor(bview, par->next, 0);
2015    sel_cursor = cursor;
2016 }
2017 #endif
2018
2019
2020 #ifndef NEW_TABULAR
2021 /* table stuff -- begin*/
2022
2023 void LyXText::TableFeatures(BufferView * bview, int feature, string const & val) const
2024 {
2025         if (!cursor.par()->table)
2026                 return; /* this should never happen */
2027   
2028         int actCell = NumberOfCell(cursor.par(), cursor.pos());
2029         SetUndo(bview->buffer(), Undo::FINISH, 
2030                 cursor.par()->ParFromPos(cursor.pos())->previous, 
2031                 cursor.par()->ParFromPos(cursor.pos())->next); 
2032         
2033         switch (feature){
2034         case LyXTable::SET_PWIDTH:
2035                 cursor.par()->table->SetPWidth(actCell, val);
2036                 break;
2037         case LyXTable::SET_SPECIAL_COLUMN:
2038         case LyXTable::SET_SPECIAL_MULTI:
2039                 cursor.par()->table->SetAlignSpecial(actCell, val, feature);
2040                 break;
2041         default:
2042                 break;
2043         }
2044         RedoParagraph(bview);
2045 }
2046
2047
2048 void LyXText::TableFeatures(BufferView * bview, int feature) const
2049 {
2050         int setLines = 0;
2051         int setAlign = LYX_ALIGN_LEFT;
2052         int lineSet;
2053         bool what;
2054     
2055     if (!cursor.par()->table)
2056         return; /* this should never happen */
2057   
2058     int actCell = NumberOfCell(cursor.par(), cursor.pos());
2059     SetUndo(bview->buffer(), Undo::FINISH, 
2060             cursor.par()->ParFromPos(cursor.pos())->previous, 
2061             cursor.par()->ParFromPos(cursor.pos())->next); 
2062
2063     switch (feature){
2064       case LyXTable::ALIGN_LEFT:
2065           setAlign= LYX_ALIGN_LEFT;
2066           break;
2067       case LyXTable::ALIGN_RIGHT:
2068           setAlign= LYX_ALIGN_RIGHT;
2069           break;
2070       case LyXTable::ALIGN_CENTER:
2071           setAlign= LYX_ALIGN_CENTER;
2072           break;
2073       default:
2074           break;
2075     }
2076     switch (feature){
2077       case LyXTable::APPEND_ROW: {
2078               LyXParagraph::size_type pos = cursor.pos();
2079
2080               /* move to the next row */
2081           int cell_org = actCell;
2082           int cell = cell_org;
2083
2084           // if there is a ContRow following this row I have to add
2085           // the row after the ContRow's
2086           if ((pos < cursor.par()->Last()) &&
2087               cursor.par()->table->RowHasContRow(cell_org)) {
2088               while((pos < cursor.par()->Last()) &&
2089                     !cursor.par()->table->IsContRow(cell)) {
2090                   while (pos < cursor.par()->Last() &&
2091                          !cursor.par()->IsNewline(pos))
2092                       ++pos;
2093                   if (pos < cursor.par()->Last())
2094                       ++pos;
2095                   ++cell;
2096               }
2097               while((pos < cursor.par()->Last()) &&
2098                     cursor.par()->table->IsContRow(cell)) {
2099                   while (pos < cursor.par()->Last() &&
2100                          !cursor.par()->IsNewline(pos))
2101                       ++pos;
2102                   if (pos < cursor.par()->Last())
2103                       ++pos;
2104                   ++cell;
2105               }
2106               cell_org = --cell;
2107               if (pos < cursor.par()->Last())
2108                   --pos;
2109           }
2110           while (pos < cursor.par()->Last() && 
2111                  (cell == cell_org || !cursor.par()->table->IsFirstCell(cell))){
2112               while (pos < cursor.par()->Last() && !cursor.par()->IsNewline(pos))
2113                   ++pos;
2114               if (pos < cursor.par()->Last())
2115                   ++pos;
2116               ++cell;
2117           }
2118                 
2119           /* insert the new cells */ 
2120           int number = cursor.par()->table->NumberOfCellsInRow(cell_org);
2121           Language const * lang = cursor.par()->getParLanguage(bview->buffer()->params);
2122           LyXFont font(LyXFont::ALL_INHERIT,lang);
2123           for (int i = 0; i < number; ++i) {
2124               cursor.par()->InsertChar(pos, LyXParagraph::META_NEWLINE, font);
2125           }
2126                 
2127           /* append the row into the table */
2128           cursor.par()->table->AppendRow(cell_org);
2129           RedoParagraph(bview);
2130           return;
2131       }
2132       case LyXTable::APPEND_CONT_ROW: {
2133               LyXParagraph::size_type pos = cursor.pos();
2134           /* move to the next row */
2135           int cell_org = actCell;
2136           int cell = cell_org;
2137
2138           // if there is already a controw but not for this cell
2139           // the AppendContRow sets only the right values but does
2140           // not actually add a row
2141           if (cursor.par()->table->RowHasContRow(cell_org) &&
2142               (cursor.par()->table->CellHasContRow(cell_org)<0)) {
2143               cursor.par()->table->AppendContRow(cell_org);
2144               RedoParagraph(bview);
2145               return;
2146           }
2147           while (pos < cursor.par()->Last() && 
2148                  (cell == cell_org
2149                   || !cursor.par()->table->IsFirstCell(cell))){
2150               while (pos < cursor.par()->Last() && !cursor.par()->IsNewline(pos))
2151                   ++pos;
2152               if (pos < cursor.par()->Last())
2153                   ++pos;
2154               ++cell;
2155           }
2156                 
2157           /* insert the new cells */ 
2158           int number = cursor.par()->table->NumberOfCellsInRow(cell_org);
2159           Language const * lang = cursor.par()->getParLanguage(bview->buffer()->params);
2160           LyXFont font(LyXFont::ALL_INHERIT,lang);
2161           for (int i = 0; i < number; ++i) {
2162               cursor.par()->InsertChar(pos, LyXParagraph::META_NEWLINE, font);
2163           }
2164
2165           /* append the row into the table */
2166           cursor.par()->table->AppendContRow(cell_org);
2167           RedoParagraph(bview);
2168           return;
2169       }
2170       case LyXTable::APPEND_COLUMN: {
2171               LyXParagraph::size_type pos = 0;
2172           int cell_org = actCell;
2173           int cell = 0;
2174           Language const * lang = cursor.par()->getParLanguage(bview->buffer()->params);
2175           LyXFont font(LyXFont::ALL_INHERIT,lang);
2176           do{
2177               if (pos && (cursor.par()->IsNewline(pos-1))){
2178                   if (cursor.par()->table->AppendCellAfterCell(cell_org, cell)) {
2179                       cursor.par()->InsertChar(pos,
2180                                                LyXParagraph::META_NEWLINE,
2181                                                font);
2182                       if (pos <= cursor.pos())
2183                           cursor.pos(cursor.pos() + 1);
2184                       ++pos;
2185                   }
2186                   ++cell;
2187               }
2188               ++pos;
2189           } while (pos <= cursor.par()->Last());
2190           /* remember that the very last cell doesn't end with a newline.
2191              This saves one byte memory per table ;-) */
2192           if (cursor.par()->table->AppendCellAfterCell(cell_org, cell)) {
2193                   LyXParagraph::size_type last = cursor.par()->Last();
2194                   cursor.par()->InsertChar(last,
2195                                            LyXParagraph::META_NEWLINE, font);
2196           }
2197                 
2198           /* append the column into the table */ 
2199           cursor.par()->table->AppendColumn(cell_org);
2200                 
2201           RedoParagraph(bview);
2202           return;
2203       }
2204       case LyXTable::DELETE_ROW:
2205           if (bview->the_locking_inset)
2206               bview->unlockInset(bview->the_locking_inset);
2207           RemoveTableRow(cursor);
2208           RedoParagraph(bview);
2209           return;
2210         
2211       case LyXTable::DELETE_COLUMN: {
2212               LyXParagraph::size_type pos = 0;
2213           int cell_org = actCell;
2214           int cell = 0;
2215           if (bview->the_locking_inset)
2216               bview->unlockInset(bview->the_locking_inset);
2217           do {
2218               if (!pos || (cursor.par()->IsNewline(pos-1))){
2219                   if (cursor.par()->table->DeleteCellIfColumnIsDeleted(cell, cell_org)){
2220                       // delete one cell
2221                       while (pos < cursor.par()->Last() && !cursor.par()->IsNewline(pos))
2222                           cursor.par()->Erase(pos);
2223                       if (pos < cursor.par()->Last())
2224                           cursor.par()->Erase(pos);
2225                       else 
2226                           cursor.par()->Erase(pos - 1); // the missing newline at the end of a table
2227                       --pos; // because of pos++ below
2228                   }   
2229                   ++cell;
2230               }
2231               ++pos;
2232           } while (pos <= cursor.par()->Last());
2233                 
2234           /* delete the column from the table */ 
2235           cursor.par()->table->DeleteColumn(cell_org);
2236                 
2237           /* set the cursor to the beginning of the table, where else? */ 
2238           cursor.pos(0);
2239           RedoParagraph(bview);
2240           return;
2241       }
2242       case LyXTable::TOGGLE_LINE_TOP:
2243           lineSet = !cursor.par()->table->TopLine(actCell);
2244           if (!selection){
2245               cursor.par()->table->SetTopLine(actCell, lineSet);
2246           } else {
2247                   LyXParagraph::size_type i;
2248                   int n = -1, m = -2;
2249               for (i = sel_start_cursor.pos(); i <= sel_end_cursor.pos(); ++i){
2250                   if ((n = NumberOfCell(sel_start_cursor.par(), i)) != m) {
2251                       cursor.par()->table->SetTopLine(n, lineSet);
2252                       m = n;
2253                   }
2254               }
2255           }
2256           RedoParagraph(bview);
2257           return;
2258     
2259       case LyXTable::TOGGLE_LINE_BOTTOM:
2260           lineSet = !cursor.par()->table->BottomLine(actCell);
2261           if (!selection){
2262               cursor.par()->table->SetBottomLine(actCell, lineSet);
2263           } else {
2264                   LyXParagraph::size_type i;
2265                   int n = -1, m = -2;
2266               for (i = sel_start_cursor.pos(); i <= sel_end_cursor.pos(); ++i) {
2267                   if ((n = NumberOfCell(sel_start_cursor.par(), i)) != m) {
2268                       cursor.par()->table->SetBottomLine(n, lineSet);
2269                       m = n;
2270                   }
2271               }
2272           }
2273           RedoParagraph(bview);
2274           return;
2275                 
2276       case LyXTable::TOGGLE_LINE_LEFT:
2277           lineSet = !cursor.par()->table->LeftLine(actCell);
2278           if (!selection){
2279               cursor.par()->table->SetLeftLine(actCell, lineSet);
2280           } else {
2281                   LyXParagraph::size_type i;
2282                   int n = -1, m = -2;
2283               for (i = sel_start_cursor.pos(); i <= sel_end_cursor.pos(); ++i){
2284                   if ((n= NumberOfCell(sel_start_cursor.par(), i)) != m) {
2285                       cursor.par()->table->SetLeftLine(n, lineSet);
2286                       m = n;
2287                   }
2288               }
2289           }
2290           RedoParagraph(bview);
2291           return;
2292
2293       case LyXTable::TOGGLE_LINE_RIGHT:
2294           lineSet = !cursor.par()->table->RightLine(actCell);
2295           if (!selection){
2296               cursor.par()->table->SetRightLine(actCell, lineSet);
2297           } else {
2298                   int n = -1, m = -2;
2299                   LyXParagraph::size_type i = sel_start_cursor.pos();
2300               for (; i <= sel_end_cursor.pos(); ++i) {
2301                   if ((n= NumberOfCell(sel_start_cursor.par(), i)) != m) {
2302                       cursor.par()->table->SetRightLine(n, lineSet);
2303                       m = n;
2304                   }
2305               }
2306           }
2307           RedoParagraph(bview);
2308           return;
2309     
2310       case LyXTable::ALIGN_LEFT:
2311       case LyXTable::ALIGN_RIGHT:
2312       case LyXTable::ALIGN_CENTER:
2313           if (!selection){
2314               cursor.par()->table->SetAlignment(actCell, setAlign);
2315           } else {
2316               int n = -1, m = -2;
2317               LyXParagraph::size_type i = sel_start_cursor.pos();
2318               for (; i <= sel_end_cursor.pos(); ++i) {
2319                   if ((n= NumberOfCell(sel_start_cursor.par(), i)) != m) {
2320                       cursor.par()->table->SetAlignment(n, setAlign);
2321                       m = n;
2322                   }
2323               }
2324           }
2325           RedoParagraph(bview);
2326           return;
2327                 
2328       case LyXTable::DELETE_TABLE:
2329           SetCursorIntern(bview, cursor.par(), 0);
2330           delete cursor.par()->table;
2331           cursor.par()->table = 0;
2332           // temporary: Should put table in simple_cut_buffer (with before and after
2333           // dummy-paragraph !! 
2334           // not necessar anymore with UNDO :)
2335           for (LyXParagraph::size_type i = 
2336                        cursor.par()->size() - 1; i >= 0; --i)
2337               cursor.par()->Erase(i);
2338           RedoParagraph(bview);
2339           return;
2340                 
2341       case LyXTable::MULTICOLUMN: {
2342           int number = 0;
2343           // check wether we are completly in a multicol
2344           int multicol = cursor.par()->table->IsMultiColumn(actCell);
2345           if (multicol && selection && sel_start_cursor.row() == sel_end_cursor.row()) {
2346               multicol = NumberOfCell(sel_start_cursor.par(), sel_start_cursor.pos())
2347                   == NumberOfCell(sel_end_cursor.par(), sel_end_cursor.pos());
2348           }
2349
2350           if (multicol){
2351               int newlines = cursor.par()->table->UnsetMultiColumn(actCell);
2352               LyXParagraph::size_type pos = cursor.pos();
2353               while (pos < cursor.par()->Last() && !cursor.par()->IsNewline(pos))
2354                   ++pos;
2355               for (; newlines; --newlines)
2356                   cursor.par()->InsertChar(pos, LyXParagraph::META_NEWLINE);
2357               RedoParagraph(bview);
2358               return;
2359           }
2360           else {
2361               // selection must be in one row (or no selection)
2362               if (!selection){
2363                   cursor.par()->table->SetMultiColumn(NumberOfCell(cursor.par(),
2364                                                                  cursor.pos()),
2365                                                     1);
2366                   RedoParagraph(bview);
2367                   return;
2368               }
2369               else {
2370                   if (sel_start_cursor.row() == sel_end_cursor.row()){
2371                       LyXParagraph::size_type i;
2372                       number = 1;
2373                       for (i = sel_start_cursor.pos();
2374                            i < sel_end_cursor.pos(); ++i){
2375                           if (sel_start_cursor.par()->IsNewline(i)){
2376                               sel_start_cursor.par()->Erase(i);
2377                               // check for double-blanks
2378                               if ((i && !sel_start_cursor.par()->IsLineSeparator(i-1))
2379                                   &&
2380                                   (i < sel_start_cursor.par()->Last() 
2381                                    && !sel_start_cursor.par()->IsLineSeparator(i)))
2382                                   sel_start_cursor.par()->InsertChar(i, ' ');
2383                               else {
2384                                   sel_end_cursor.pos(sel_end_cursor.pos() - 1);
2385                                   --i;
2386                               }
2387                               ++number;
2388                           }
2389                       }
2390                       cursor.par()->table->
2391                           SetMultiColumn(NumberOfCell(sel_start_cursor.par(),
2392                                                       sel_start_cursor.pos()),
2393                                          number);
2394                       cursor.pos(sel_start_cursor.pos());
2395                       RedoParagraph(bview);
2396                       return;
2397                   }
2398                   else {
2399                       WriteAlert(_("Impossible Operation!"), 
2400                                  _("Multicolumns can only be horizontally."), 
2401                                  _("Sorry."));
2402                   }
2403               }
2404           }
2405           break;
2406       }
2407       case LyXTable::SET_ALL_LINES:
2408           setLines = 1;
2409       case LyXTable::UNSET_ALL_LINES:
2410           if (!selection){
2411               cursor.par()->table->SetAllLines(NumberOfCell(cursor.par(),
2412                                                           cursor.pos()),
2413                                              setLines);
2414           } else {
2415                   LyXParagraph::size_type i;
2416                   int n = -1, m = -2;
2417               for (i = sel_start_cursor.pos(); i <= sel_end_cursor.pos(); ++i) {
2418                   if ((n= NumberOfCell(sel_start_cursor.par(), i)) != m) {
2419                       cursor.par()->table->SetAllLines(n, setLines);
2420                       m = n;
2421                   }
2422               }
2423           }
2424           RedoParagraph(bview);
2425           return;
2426       case LyXTable::SET_LONGTABLE:
2427           cursor.par()->table->SetLongTable(true);
2428           return;
2429       case LyXTable::UNSET_LONGTABLE:
2430           cursor.par()->table->SetLongTable(false);
2431           return;
2432       case LyXTable::SET_ROTATE_TABLE:
2433           cursor.par()->table->SetRotateTable(true);
2434           return;
2435       case LyXTable::UNSET_ROTATE_TABLE:
2436           cursor.par()->table->SetRotateTable(false);
2437           return;
2438       case LyXTable::SET_ROTATE_CELL:
2439           if (!selection){
2440               cursor.par()->table->SetRotateCell(actCell, true);
2441           } else {
2442                   LyXParagraph::size_type i;
2443                   int n = -1, m = -2;
2444               for (i = sel_start_cursor.pos(); i <= sel_end_cursor.pos(); ++i){
2445                   if ((n = NumberOfCell(sel_start_cursor.par(), i)) != m) {
2446                       cursor.par()->table->SetRotateCell(n, true);
2447                       m = n;
2448                   }
2449               }
2450           }
2451           return;
2452       case LyXTable::UNSET_ROTATE_CELL:
2453           if (!selection){
2454               cursor.par()->table->SetRotateCell(actCell, false);
2455           } else {
2456                   int n = -1, m = -2;
2457                   LyXParagraph::size_type i = sel_start_cursor.pos();
2458               for (; i <= sel_end_cursor.pos(); ++i) {
2459                   if ((n= NumberOfCell(sel_start_cursor.par(), i)) != m) {
2460                       cursor.par()->table->SetRotateCell(n, false);
2461                       m = n;
2462                   }
2463               }
2464           }
2465           return;
2466       case LyXTable::SET_LINEBREAKS:
2467           what = !cursor.par()->table->Linebreaks(cursor.par()->table->FirstVirtualCell(actCell));
2468           if (!selection){
2469               cursor.par()->table->SetLinebreaks(actCell, what);
2470           } else {
2471                   LyXParagraph::size_type i;
2472                   int n = -1, m = -2;
2473               for (i = sel_start_cursor.pos(); i <= sel_end_cursor.pos(); ++i) {
2474                   if ((n = NumberOfCell(sel_start_cursor.par(), i)) != m) {
2475                       cursor.par()->table->SetLinebreaks(n, what);
2476                       m = n;
2477                   }
2478               }
2479           }
2480           return;
2481       case LyXTable::SET_LTFIRSTHEAD:
2482           cursor.par()->table->SetLTHead(actCell, true);
2483           return;
2484       case LyXTable::SET_LTHEAD:
2485           cursor.par()->table->SetLTHead(actCell, false);
2486           return;
2487       case LyXTable::SET_LTFOOT:
2488           cursor.par()->table->SetLTFoot(actCell, false);
2489           return;
2490       case LyXTable::SET_LTLASTFOOT:
2491           cursor.par()->table->SetLTFoot(actCell, true);
2492           return;
2493       case LyXTable::SET_LTNEWPAGE:
2494           what = !cursor.par()->table->LTNewPage(actCell);
2495           cursor.par()->table->SetLTNewPage(actCell, what);
2496           return;
2497     }
2498 }
2499         
2500
2501 void LyXText::InsertCharInTable(BufferView * bview, char c)
2502 {
2503         Row * row = 0;
2504         Row * tmprow = 0;
2505         long y;
2506         bool jumped_over_space;
2507         
2508         /* first check, if there will be two blanks together or a blank at 
2509          * the beginning of a paragraph. 
2510          * I decided to handle blanks like normal characters, the main 
2511          * difference are the special checks when calculating the row.fill
2512          * (blank does not count at the end of a row) and the check here */ 
2513         
2514         LyXFont realtmpfont = real_current_font;
2515         LyXFont rawtmpfont = current_font; /* store the current font.
2516                                             * This is because of the use
2517                                             * of cursor movements. The moving
2518                                             * cursor would refresh the 
2519                                             * current font */
2520
2521         // Get the font that is used to calculate the baselineskip
2522         LyXParagraph::size_type const lastpos = 
2523                 cursor.par()->Last();
2524         LyXFont rawparfont = cursor.par()->GetFontSettings(bview->buffer()->params,
2525                                                            lastpos - 1);
2526
2527         jumped_over_space = false;
2528         if (IsLineSeparatorChar(c)) {
2529                 if ((cursor.pos() > 0 && 
2530                      cursor.par()->IsLineSeparator(cursor.pos() - 1))
2531                     || (cursor.pos() > 0 && cursor.par()->IsNewline(cursor.pos() - 1))
2532                     || (cursor.pos() == 0
2533 #ifndef NEW_INSETS
2534                         && !(cursor.par()->Previous()
2535                           && cursor.par()->Previous()->footnoteflag
2536                           == LyXParagraph::OPEN_FOOTNOTE)
2537 #endif
2538                             ))
2539                         return;
2540         } else if (IsNewlineChar(c)) {
2541             if (!IsEmptyTableCell()) {
2542                 TableFeatures(bview, LyXTable::APPEND_CONT_ROW);
2543                 CursorDown(bview);
2544             }
2545           return;
2546         }
2547    
2548         row = cursor.row();
2549         y = cursor.y() - row->baseline();
2550         if (c != LyXParagraph::META_INSET)      /* in this case LyXText::InsertInset 
2551                                          * already inserted the character */
2552                 cursor.par()->InsertChar(cursor.pos(), c);
2553         SetCharFont(bview->buffer(), cursor.par(), cursor.pos(), rawtmpfont);
2554
2555         if (!jumped_over_space) {
2556                 /* refresh the positions */
2557                 tmprow = row;
2558                 while (tmprow->next() && tmprow->next()->par() == row->par()) {
2559                         tmprow = tmprow->next();
2560                         tmprow->pos(tmprow->pos() + 1);
2561                 }
2562         }
2563
2564         cursor.pos(cursor.pos() + 1);
2565
2566         CheckParagraphInTable(bview, cursor.par(), cursor.pos());
2567         
2568         current_font = rawtmpfont;
2569         real_current_font = realtmpfont;
2570         
2571         /* check, whether the last character's font has changed. */
2572         if (cursor.pos() && cursor.pos() == cursor.par()->Last()
2573             && rawparfont != rawtmpfont)
2574                 RedoHeightOfParagraph(bview, cursor);
2575 }
2576
2577
2578 void LyXText::CheckParagraphInTable(BufferView * bview, LyXParagraph * par,
2579                                     LyXParagraph::size_type pos)
2580 {
2581         
2582         if (par->GetChar(pos) == LyXParagraph::META_INSET &&
2583             par->GetInset(pos) && par->GetInset(pos)->display()){
2584           par->GetInset(pos)->display(false);
2585         }
2586
2587         long y;
2588         Row * row = GetRow(par, pos, y);
2589         
2590         int tmpheight = row->height();
2591         SetHeightOfRow(bview, row);
2592
2593         LyXParagraph::size_type tmp_pos = pos;
2594         /* update the table information */
2595         while (tmp_pos && !par->IsNewline(tmp_pos - 1))
2596                 --tmp_pos;
2597         if (par->table->SetWidthOfCell(NumberOfCell(par, pos),
2598                                        WidthOfCell(bview, par, tmp_pos))) {
2599                 LyXCursor tmpcursor = cursor;
2600                 SetCursorIntern(bview, par, pos, false);
2601                 /* make a complete redraw */
2602                 RedoDrawingOfParagraph(bview, cursor);
2603                 cursor = tmpcursor;
2604         }
2605         else {
2606                 /* redraw only the row */
2607                 LyXCursor tmpcursor = cursor;
2608                 SetCursorIntern(bview, par, pos);
2609                 //CHECK See comment on top of text.C
2610                 refresh_y = y;
2611                 refresh_x = cursor.x();
2612                 refresh_row = row;
2613                 refresh_pos = cursor.pos();
2614                 cursor = tmpcursor;
2615                 
2616                 if (tmpheight == row->height())
2617                         status = LyXText::NEED_VERY_LITTLE_REFRESH;
2618                 else
2619                         status = LyXText::NEED_MORE_REFRESH;
2620         }
2621         SetCursorIntern(bview, cursor.par(), cursor.pos(), false,
2622                         cursor.boundary());
2623 }
2624
2625
2626 void LyXText::BackspaceInTable(BufferView * bview)
2627 {
2628         Row * tmprow, * row;
2629         long y;
2630         
2631         LyXFont rawtmpfont = current_font;
2632         LyXFont realtmpfont = real_current_font;
2633
2634         // Get the font that is used to calculate the baselineskip
2635         int const lastpos = cursor.par()->Last();
2636         LyXFont rawparfont = cursor.par()->GetFontSettings(bview->buffer()->params,
2637                                                            lastpos - 1);
2638         
2639         if (cursor.pos() == 0) {
2640                 /* no pasting of table paragraphs */
2641                 
2642                 CursorLeft(bview);
2643         } else {
2644                 /* this is the code for a normal backspace, not pasting
2645                  * any paragraphs */ 
2646                 SetUndo(bview->buffer(), Undo::DELETE, 
2647                         cursor.par()->ParFromPos(cursor.pos())->previous, 
2648                         cursor.par()->ParFromPos(cursor.pos())->next); 
2649           
2650                 CursorLeftIntern(bview);
2651                 
2652                 /* some insets are undeletable here */
2653                 if (cursor.par()->GetChar(cursor.pos()) == LyXParagraph::META_INSET) {
2654                         if (!cursor.par()->GetInset(cursor.pos())->Deletable())
2655                                 return;
2656                 }
2657                 
2658                 row = cursor.row();
2659                 y = cursor.y() - row->baseline();
2660                 
2661                 /* some special code when deleting a newline. */
2662                 if (cursor.par()->IsNewline(cursor.pos())) {
2663                         /* nothing :-) */
2664                         return;
2665                 } else {
2666                         cursor.par()->Erase(cursor.pos());
2667                         
2668                         /* refresh the positions */
2669                         tmprow = row;
2670                         while (tmprow->next()
2671                                && tmprow->next()->par() == row->par()) {
2672                                 tmprow = tmprow->next();
2673                                 tmprow->pos(tmprow->pos() - 1);
2674                         }
2675                 }
2676       
2677                 CheckParagraphInTable(bview, cursor.par(), cursor.pos());
2678       
2679                 /* check, wether the last characters font has changed. */ 
2680                 if (cursor.pos() && cursor.pos() == cursor.par()->Last()
2681                     && rawparfont != rawtmpfont)
2682                         RedoHeightOfParagraph(bview, cursor);
2683
2684                 /* restore the current font 
2685                  * That is what a user expects! */
2686                 current_font = rawtmpfont;
2687                 real_current_font = realtmpfont;
2688         }
2689         SetCursorIntern(bview, cursor.par(), cursor.pos(), true,
2690                         cursor.boundary());
2691         if (IsBoundary(bview->buffer(), cursor.par(), cursor.pos()) != cursor.boundary())
2692                 SetCursor(bview, cursor.par(), cursor.pos(), false, !cursor.boundary());
2693 }
2694
2695 /* table stuff -- end*/
2696 #endif
2697
2698
2699 // Just a macro to make some thing easier. 
2700 void LyXText::RedoParagraph(BufferView * bview) const
2701 {
2702         ClearSelection();
2703         RedoParagraphs(bview, cursor, cursor.par()->Next());
2704         SetCursorIntern(bview, cursor.par(), cursor.pos());
2705 }
2706
2707
2708 /* insert a character, moves all the following breaks in the 
2709  * same Paragraph one to the right and make a rebreak */
2710 void LyXText::InsertChar(BufferView * bview, char c)
2711 {
2712         SetUndo(bview->buffer(), Undo::INSERT, 
2713                 cursor.par()->ParFromPos(cursor.pos())->previous, 
2714                 cursor.par()->ParFromPos(cursor.pos())->next);
2715
2716         // When the free-spacing option is set for the current layout,
2717         // disable the double-space checking
2718
2719         bool freeSpacing = 
2720                 textclasslist.Style(bview->buffer()->params.textclass,
2721                                cursor.row()->par()->GetLayout()).free_spacing;
2722
2723 #ifndef NEW_TABULAR
2724         /* table stuff -- begin*/
2725         if (cursor.par()->table) {
2726                 InsertCharInTable(bview, c);
2727                 charInserted();
2728                 return;
2729         }
2730         /* table stuff -- end*/
2731 #endif
2732         /* First check, if there will be two blanks together or a blank at 
2733           the beginning of a paragraph. 
2734           I decided to handle blanks like normal characters, the main 
2735           difference are the special checks when calculating the row.fill
2736           (blank does not count at the end of a row) and the check here */ 
2737
2738         // The bug is triggered when we type in a description environment:
2739         // The current_font is not changed when we go from label to main text
2740         // and it should (along with realtmpfont) when we type the space.
2741         // CHECK There is a bug here! (Asger)
2742         
2743         LyXFont realtmpfont = real_current_font;
2744         LyXFont rawtmpfont = current_font;  /* store the current font.
2745                                      * This is because of the use
2746                                      * of cursor movements. The moving
2747                                      * cursor would refresh the 
2748                                      * current font */
2749
2750         // Get the font that is used to calculate the baselineskip
2751         LyXParagraph::size_type lastpos = cursor.par()->Last();
2752         LyXFont rawparfont = cursor.par()->GetFontSettings(bview->buffer()->params,
2753                                                            lastpos - 1);
2754
2755         bool jumped_over_space = false;
2756    
2757         if (!freeSpacing && IsLineSeparatorChar(c)) {
2758                 if ((cursor.pos() > 0 
2759                      && cursor.par()->IsLineSeparator(cursor.pos() - 1))
2760                     || (cursor.pos() > 0
2761                         && cursor.par()->IsNewline(cursor.pos() - 1))
2762                     || (cursor.pos() == 0
2763 #ifndef NEW_INSETS
2764                         && !(cursor.par()->Previous()
2765                              && cursor.par()->Previous()->footnoteflag
2766                              == LyXParagraph::OPEN_FOOTNOTE)
2767 #endif
2768                             )) {
2769                         if (cursor.pos() == 0 )
2770                                 bview->owner()->getMiniBuffer()->Set(_("You cannot insert a space at the beginning of a paragraph.  Please read the Tutorial."));
2771                         else
2772                                 bview->owner()->getMiniBuffer()->Set(_("You cannot type two spaces this way.  Please read the Tutorial."));
2773                         charInserted();
2774                         return;
2775                 }
2776         } else if (IsNewlineChar(c)) {
2777 #ifndef NEW_INSETS
2778                 if (cursor.par()->FirstPhysicalPar() == cursor.par()
2779 #else
2780                 if (cursor.par() == cursor.par()
2781 #endif
2782                     && cursor.pos() <= BeginningOfMainBody(bview->buffer(), cursor.par())) {
2783                         charInserted();
2784                         return;
2785                 }
2786                 /* No newline at first position 
2787                  * of a paragraph or behind labels. 
2788                  * TeX does not allow that. */
2789                 
2790                 if (cursor.pos() < cursor.par()->Last() &&
2791                     cursor.par()->IsLineSeparator(cursor.pos()))
2792                         // newline always after a blank!
2793                         CursorRightIntern(bview);
2794                 cursor.row()->fill(-1);        // to force a new break
2795         }
2796    
2797         // the display inset stuff
2798         if (cursor.row()->par()->GetChar(cursor.row()->pos()) == LyXParagraph::META_INSET
2799             && cursor.row()->par()->GetInset(cursor.row()->pos())
2800             && (cursor.row()->par()->GetInset(cursor.row()->pos())->display() ||
2801                 cursor.row()->par()->GetInset(cursor.row()->pos())->needFullRow()))
2802                 cursor.row()->fill(-1); // to force a new break  
2803
2804         // get the cursor row fist
2805         Row * row = cursor.row();
2806         long y = cursor.y() - row->baseline();
2807         if (c != LyXParagraph::META_INSET) /* Here case LyXText::InsertInset 
2808                                             * already insertet the character */
2809                 cursor.par()->InsertChar(cursor.pos(), c);
2810         SetCharFont(bview->buffer(), cursor.par(), cursor.pos(), rawtmpfont);
2811
2812         if (!jumped_over_space) {
2813                 // refresh the positions
2814                 Row * tmprow = row;
2815                 while (tmprow->next() && tmprow->next()->par() == row->par()) {
2816                         tmprow = tmprow->next();
2817                         tmprow->pos(tmprow->pos() + 1);
2818                 }
2819         }
2820    
2821         // Is there a break one row above
2822         if ((cursor.par()->IsLineSeparator(cursor.pos())
2823              || cursor.par()->IsNewline(cursor.pos())
2824              || cursor.row()->fill() == -1)
2825             && row->previous() && row->previous()->par() == row->par()) {
2826                 LyXParagraph::size_type z = NextBreakPoint(bview,
2827                                                            row->previous(),
2828                                                            workWidth(bview));
2829                 if ( z >= row->pos()) {
2830                         row->pos(z + 1);
2831                         
2832                         // set the dimensions of the row above
2833                         row->previous()->fill(Fill(bview,
2834                                                    row->previous(),
2835                                                    workWidth(bview)));
2836
2837                         SetHeightOfRow(bview, row->previous());
2838              
2839                         y -= row->previous()->height();
2840                         refresh_y = y;
2841                         refresh_row = row->previous();
2842                         status = LyXText::NEED_MORE_REFRESH;
2843              
2844                         BreakAgainOneRow(bview, row);
2845
2846                         current_font = rawtmpfont;
2847                         real_current_font = realtmpfont;
2848                         SetCursor(bview, cursor.par(), cursor.pos() + 1,
2849                                   false, cursor.boundary());
2850                         // cursor MUST be in row now.
2851              
2852                         if (row->next() && row->next()->par() == row->par())
2853                                 need_break_row = row->next();
2854                         else
2855                                 need_break_row = 0;
2856              
2857                         // check, wether the last characters font has changed. 
2858                         if (cursor.pos() && cursor.pos() == cursor.par()->Last()
2859                             && rawparfont != rawtmpfont)
2860                                 RedoHeightOfParagraph(bview, cursor);
2861                         
2862                         charInserted();
2863                         return;
2864                 }
2865         }
2866    
2867         // recalculate the fill of the row
2868         if (row->fill() >= 0)  /* needed because a newline
2869                               * will set fill to -1. Otherwise
2870                               * we would not get a rebreak! */
2871                 row->fill(Fill(bview, row, workWidth(bview)));
2872         if (row->fill() < 0 ) {
2873                 refresh_y = y;
2874                 refresh_row = row; 
2875                 refresh_x = cursor.x();
2876                 refresh_pos = cursor.pos();
2877                 status = LyXText::NEED_MORE_REFRESH;
2878                 BreakAgainOneRow(bview, row); 
2879                 // will the cursor be in another row now?
2880                 if (RowLast(row) <= cursor.pos() + 1 && row->next()) {
2881                         if (row->next() && row->next()->par() == row->par())
2882                                 // this should always be true
2883                                 row = row->next();
2884                         BreakAgainOneRow(bview, row);
2885                 }
2886                 current_font = rawtmpfont;
2887                 real_current_font = realtmpfont;
2888
2889                 SetCursor(bview, cursor.par(), cursor.pos() + 1, false,
2890                           cursor.boundary());
2891                 if (row->next() && row->next()->par() == row->par())
2892                         need_break_row = row->next();
2893                 else
2894                         need_break_row = 0;             
2895         } else {
2896                 refresh_y = y;
2897                 refresh_x = cursor.x();
2898                 refresh_row = row;
2899                 refresh_pos = cursor.pos();
2900                 
2901                 int tmpheight = row->height();
2902                 SetHeightOfRow(bview, row);
2903                 if (tmpheight == row->height())
2904                         status = LyXText::NEED_VERY_LITTLE_REFRESH;
2905                 else
2906                         status = LyXText::NEED_MORE_REFRESH;
2907             
2908                 current_font = rawtmpfont;
2909                 real_current_font = realtmpfont;
2910                 SetCursor(bview, cursor.par(), cursor.pos() + 1, false,
2911                           cursor.boundary());
2912         }
2913
2914         // check, wether the last characters font has changed.
2915         if (cursor.pos() && cursor.pos() == cursor.par()->Last()
2916             && rawparfont != rawtmpfont) {
2917                 RedoHeightOfParagraph(bview, cursor);
2918         } else {
2919                 // now the special right address boxes
2920                 if (textclasslist.Style(bview->buffer()->params.textclass,
2921                                    cursor.par()->GetLayout()).margintype
2922                     == MARGIN_RIGHT_ADDRESS_BOX) {
2923                         RedoDrawingOfParagraph(bview, cursor); 
2924                 }
2925         }
2926
2927         charInserted();
2928 }
2929    
2930
2931 void LyXText::charInserted()
2932 {
2933         // Here we could call FinishUndo for every 20 characters inserted.
2934         // This is from my experience how emacs does it.
2935         static unsigned int counter = 0;
2936         if (counter < 20) {
2937                 ++counter;
2938         } else {
2939                 FinishUndo();
2940                 counter = 0;
2941         }
2942 }
2943
2944
2945 void LyXText::PrepareToPrint(BufferView * bview,
2946                              Row * row, float & x,
2947                              float & fill_separator, 
2948                              float & fill_hfill,
2949                              float & fill_label_hfill,
2950                              bool bidi) const
2951 {
2952         float nlh, ns;
2953         
2954         float w = row->fill();
2955         fill_hfill = 0;
2956         fill_label_hfill = 0;
2957         fill_separator = 0;
2958         fill_label_hfill = 0;
2959
2960         bool is_rtl = row->par()->isRightToLeftPar(bview->buffer()->params);
2961 #ifndef NEW_INSETS
2962
2963         if (is_rtl) {
2964                 x = RightMargin(bview->buffer(), row);
2965                 if (row->par()->footnoteflag == LyXParagraph::OPEN_FOOTNOTE) {
2966                         LyXFont font(LyXFont::ALL_SANE);
2967                         font.setSize(LyXFont::SIZE_SMALL);
2968                         x += lyxfont::width("Mwide-figM", font);
2969                 }
2970         } else
2971 #endif
2972                 if (workWidth(bview) > 0)
2973                 x = LeftMargin(bview, row);
2974         else
2975                 x = 0;
2976         
2977         // is there a manual margin with a manual label
2978         if (textclasslist.Style(bview->buffer()->params.textclass,
2979                            row->par()->GetLayout()).margintype == MARGIN_MANUAL
2980             && textclasslist.Style(bview->buffer()->params.textclass,
2981                               row->par()->GetLayout()).labeltype == LABEL_MANUAL) {
2982                
2983                 /* one more since labels are left aligned */ 
2984                 nlh = NumberOfLabelHfills(bview->buffer(), row) + 1;
2985                 if (nlh && !row->par()->GetLabelWidthString().empty()) {
2986                         fill_label_hfill = LabelFill(bview, row) / nlh;
2987                 }
2988         }
2989                 
2990         // are there any hfills in the row?
2991         float nh = NumberOfHfills(bview->buffer(), row);
2992
2993 #ifndef NEW_TABULAR
2994 /* table stuff -- begin*/
2995         if (row->par()->table) {
2996            w = workWidth(bview) - row->par()->table->WidthOfTable()
2997            - x - RightMargin(bview->buffer(), row);
2998            nh = 0; /* ignore hfills in tables */ 
2999         }
3000 /* table stuff -- end*/
3001 #endif
3002         if (nh)
3003           fill_hfill = w /nh;
3004         else  {
3005                 // is it block, flushleft or flushright? 
3006                 // set x how you need it
3007         int align;
3008 #ifndef NEW_INSETS
3009         if (row->par()->FirstPhysicalPar()->align == LYX_ALIGN_LAYOUT)
3010           align = textclasslist.Style(bview->buffer()->params.textclass, row->par()->GetLayout()).align;
3011         else
3012           align = row->par()->FirstPhysicalPar()->align;
3013 #else
3014         if (row->par()->align == LYX_ALIGN_LAYOUT)
3015           align = textclasslist.Style(bview->buffer()->params.textclass, row->par()->GetLayout()).align;
3016         else
3017           align = row->par()->align;
3018 #endif
3019            
3020         // center displayed insets 
3021            if (row->par()->GetChar(row->pos()) == LyXParagraph::META_INSET
3022                && row->par()->GetInset(row->pos())
3023                && row->par()->GetInset(row->pos())->display())
3024              align = LYX_ALIGN_CENTER;
3025
3026            switch (align) {
3027             case LYX_ALIGN_BLOCK:
3028               ns = NumberOfSeparators(bview->buffer(), row);
3029               if (ns && row->next() && row->next()->par() == row->par() &&
3030                   !(row->next()->par()->IsNewline(row->next()->pos() - 1))
3031                   && !(row->next()->par()->GetChar(row->next()->pos()) == LyXParagraph::META_INSET
3032                        && row->next()->par()->GetInset(row->next()->pos())
3033                        && row->next()->par()->GetInset(row->next()->pos())->display())
3034                   )
3035                 fill_separator = w / ns;
3036               else if (is_rtl)
3037                 x += w;
3038               break;
3039             case LYX_ALIGN_RIGHT:
3040               x += w;
3041               break;
3042             case LYX_ALIGN_CENTER:
3043               x += w / 2;
3044               break;
3045            }
3046         }
3047         if (!bidi)
3048                 return;
3049
3050         ComputeBidiTables(bview->buffer(), row);
3051         if (is_rtl) {
3052                 LyXParagraph::size_type main_body = 
3053                         BeginningOfMainBody(bview->buffer(), row->par());
3054                 LyXParagraph::size_type last = RowLast(row);
3055
3056                 if (main_body > 0 &&
3057                     (main_body-1 > last || 
3058                      !row->par()->IsLineSeparator(main_body-1))) {
3059                         LyXLayout const & layout =
3060                                 textclasslist.Style(bview->buffer()->params.textclass,
3061                                                     row->par()->GetLayout());
3062                         x += lyxfont::width(layout.labelsep,
3063                                             GetFont(bview->buffer(), row->par(), -2));
3064                         if (main_body-1 <= last)
3065                                 x += fill_label_hfill;
3066                 }
3067         }
3068 }
3069       
3070 /* important for the screen */
3071
3072
3073 /* the cursor set functions have a special mechanism. When they
3074 * realize, that you left an empty paragraph, they will delete it.
3075 * They also delete the corresponding row */
3076
3077 void LyXText::CursorRightOneWord(BufferView * bview) const
3078 {
3079         // treat floats, HFills and Insets as words
3080         LyXCursor tmpcursor = cursor;
3081         // CHECK See comment on top of text.C
3082
3083         if (tmpcursor.pos() == tmpcursor.par()->Last()
3084             && tmpcursor.par()->Next()) {
3085                         tmpcursor.par(tmpcursor.par()->Next());
3086                         tmpcursor.pos(0);
3087         } else {
3088                 int steps = 0;
3089
3090                 // Skip through initial nonword stuff.
3091                 while ( tmpcursor.pos() < tmpcursor.par()->Last() &&
3092                         ! tmpcursor.par()->IsWord( tmpcursor.pos() ) ) 
3093                 {
3094                   //    printf("Current pos1 %d", tmpcursor.pos()) ;
3095                         tmpcursor.pos(tmpcursor.pos() + 1);
3096                         ++steps;
3097                 }
3098                 // Advance through word.
3099                 while ( tmpcursor.pos() < tmpcursor.par()->Last() &&
3100                         tmpcursor.par()->IsWord( tmpcursor.pos() ) )
3101                 {
3102                   //     printf("Current pos2 %d", tmpcursor.pos()) ;
3103                         tmpcursor.pos(tmpcursor.pos() + 1);
3104                         ++steps;
3105                 }
3106         }
3107         SetCursor(bview, tmpcursor.par(), tmpcursor.pos());
3108 }
3109
3110
3111 void LyXText::CursorTab(BufferView * bview) const
3112 {
3113 #ifndef NEW_TABULAR
3114     if (cursor.par()->table) {
3115         int cell = NumberOfCell(cursor.par(), cursor.pos());
3116         while(cursor.par()->table->IsContRow(cell)) {
3117             CursorUp(bview);
3118             cell = NumberOfCell(cursor.par(), cursor.pos());
3119         }
3120         if (cursor.par()->table->ShouldBeVeryLastCell(cell))
3121             TableFeatures(bview, LyXTable::APPEND_ROW);
3122     }
3123 #endif
3124     LyXCursor tmpcursor = cursor;
3125     while (tmpcursor.pos() < tmpcursor.par()->Last()
3126            && !tmpcursor.par()->IsNewline(tmpcursor.pos()))
3127         tmpcursor.pos(tmpcursor.pos() + 1);
3128    
3129     if (tmpcursor.pos() == tmpcursor.par()->Last()){
3130         if (tmpcursor.par()->Next()) {
3131             tmpcursor.par(tmpcursor.par()->Next());
3132             tmpcursor.pos(0);
3133         }
3134     } else
3135         tmpcursor.pos(tmpcursor.pos() + 1);
3136     SetCursor(bview, tmpcursor.par(), tmpcursor.pos());
3137 #ifndef NEW_TABULAR
3138     if (cursor.par()->table) {
3139         int cell = NumberOfCell(cursor.par(), cursor.pos());
3140         while (cursor.par()->table->IsContRow(cell) &&
3141                !cursor.par()->table->ShouldBeVeryLastCell(cell)) {
3142             tmpcursor = cursor;
3143             while (tmpcursor.pos() < tmpcursor.par()->Last()
3144                    && !tmpcursor.par()->IsNewline(tmpcursor.pos()))
3145                 tmpcursor.pos(tmpcursor.pos() + 1);
3146    
3147             if (tmpcursor.pos() == tmpcursor.par()->Last()){
3148                 if (tmpcursor.par()->Next()) {
3149                     tmpcursor.par(tmpcursor.par()->Next());
3150                     tmpcursor.pos(0);
3151                 }
3152             } else
3153                 tmpcursor.pos(tmpcursor.pos() + 1);
3154             SetCursor(bview, tmpcursor.par(), tmpcursor.pos());
3155             cell = NumberOfCell(cursor.par(), cursor.pos());
3156         }
3157     }
3158 #endif
3159 }
3160
3161
3162 /* -------> Skip initial whitespace at end of word and move cursor to *start*
3163             of prior word, not to end of next prior word. */
3164
3165 void LyXText::CursorLeftOneWord(BufferView * bview)  const
3166 {
3167         // treat HFills, floats and Insets as words
3168         LyXCursor tmpcursor = cursor;
3169         while (tmpcursor.pos() 
3170                && (tmpcursor.par()->IsSeparator(tmpcursor.pos() - 1) 
3171                    || tmpcursor.par()->IsKomma(tmpcursor.pos() - 1))
3172                && !(tmpcursor.par()->IsHfill(tmpcursor.pos() - 1)
3173 #ifndef NEW_INSETS
3174                     || tmpcursor.par()->IsFloat(tmpcursor.pos() - 1)
3175 #endif
3176                     || tmpcursor.par()->IsInset(tmpcursor.pos() - 1)))
3177                 tmpcursor.pos(tmpcursor.pos() - 1);
3178
3179         if (tmpcursor.pos()
3180             && (tmpcursor.par()->IsInset(tmpcursor.pos() - 1)
3181 #ifndef NEW_INSETS
3182                 || tmpcursor.par()->IsFloat(tmpcursor.pos() - 1)
3183 #endif
3184                 || tmpcursor.par()->IsHfill(tmpcursor.pos() - 1))) {
3185                 tmpcursor.pos(tmpcursor.pos() - 1);
3186         } else if (!tmpcursor.pos()) {
3187                 if (tmpcursor.par()->Previous()){
3188                         tmpcursor.par(tmpcursor.par()->Previous());
3189                         tmpcursor.pos(tmpcursor.par()->Last());
3190                 }
3191         } else {                // Here, tmpcursor != 0 
3192                 while (tmpcursor.pos() > 0 &&
3193                        tmpcursor.par()->IsWord(tmpcursor.pos()-1) )
3194                         tmpcursor.pos(tmpcursor.pos() - 1);
3195         }
3196         SetCursor(bview, tmpcursor.par(), tmpcursor.pos());
3197 }
3198
3199 /* -------> Select current word. This depends on behaviour of CursorLeftOneWord(), so it is
3200                         patched as well. */
3201
3202 void LyXText::SelectWord(BufferView * bview) 
3203 {
3204         // Move cursor to the beginning, when not already there.
3205         if ( cursor.pos()
3206              && !cursor.par()->IsSeparator(cursor.pos()-1)
3207              && !cursor.par()->IsKomma(cursor.pos()-1) )
3208                 CursorLeftOneWord(bview);
3209
3210         // set the sel cursor
3211         sel_cursor = cursor;
3212
3213         while ( cursor.pos() < cursor.par()->Last()
3214                         && !cursor.par()->IsSeparator(cursor.pos())
3215                         && !cursor.par()->IsKomma(cursor.pos()) )
3216                 cursor.pos(cursor.pos() + 1);
3217         SetCursor(bview, cursor.par(), cursor.pos() );
3218         
3219         // finally set the selection
3220         SetSelection();
3221 }
3222
3223
3224 /* -------> Select the word currently under the cursor when:
3225                         1: no selection is currently set,
3226                         2: the cursor is not at the borders of the word. */
3227
3228 bool LyXText::SelectWordWhenUnderCursor(BufferView * bview) 
3229 {
3230         if (!selection &&
3231             cursor.pos() > 0 && cursor.pos() < cursor.par()->Last()
3232             && !cursor.par()->IsSeparator(cursor.pos())
3233             && !cursor.par()->IsKomma(cursor.pos())
3234             && !cursor.par()->IsSeparator(cursor.pos() -1)
3235             && !cursor.par()->IsKomma(cursor.pos() -1) ) {
3236                 SelectWord(bview);
3237                 return true;
3238         }
3239         return false;
3240 }
3241
3242
3243 // This function is only used by the spellchecker for NextWord().
3244 // It doesn't handle LYX_ACCENTs and probably never will.
3245 char * LyXText::SelectNextWord(BufferView * bview, float & value)
3246 {
3247         LyXParagraph * tmppar = cursor.par();
3248         
3249         // If this is not the very first word, skip rest of
3250         // current word because we are probably in the middle
3251         // of a word if there is text here.
3252         if (cursor.pos() || cursor.par()->previous) {
3253                 while (cursor.pos() < cursor.par()->Last()
3254                        && cursor.par()->IsLetter(cursor.pos()))
3255                         cursor.pos(cursor.pos() + 1);
3256         }
3257         // Now, skip until we have real text (will jump paragraphs)
3258         while ((cursor.par()->Last() > cursor.pos()
3259                 && (!cursor.par()->IsLetter(cursor.pos())
3260                     || cursor.par()->getFont(bview->buffer()->params, cursor.pos())
3261                     .latex() == LyXFont::ON))
3262                || (cursor.par()->Last() == cursor.pos() 
3263                    && cursor.par()->Next())){
3264                 if (cursor.pos() == cursor.par()->Last()) {
3265                         cursor.par(cursor.par()->Next());
3266                         cursor.pos(0);
3267                 } else
3268                         cursor.pos(cursor.pos() + 1);
3269         }
3270   
3271         // Update the value if we changed paragraphs
3272         if (cursor.par() != tmppar){
3273                 SetCursor(bview, cursor.par(), cursor.pos());
3274                 value = float(cursor.y())/float(height);
3275         }
3276
3277         // Start the selection from here
3278         sel_cursor = cursor;
3279
3280 #ifdef HAVE_SSTREAM
3281         std::ostringstream latex;
3282 #else
3283         ostrstream latex;
3284 #endif
3285         // and find the end of the word 
3286         // (optional hyphens are part of a word)
3287         while (cursor.pos() < cursor.par()->Last()
3288                && (cursor.par()->IsLetter(cursor.pos())) 
3289                    || (cursor.par()->GetChar(cursor.pos()) == LyXParagraph::META_INSET
3290                        && cursor.par()->GetInset(cursor.pos()) != 0
3291                        && cursor.par()->GetInset(cursor.pos())->Latex(bview->buffer(), latex, false, false) == 0
3292 #ifdef HAVE_SSTREAM
3293                        && latex.str() == "\\-"
3294 #else
3295                        && latex.str() // protect against null pointers         
3296                        && string(latex.str(), 3) == "\\-" // this is not nice at all
3297 #endif
3298                            ))
3299                 cursor.pos(cursor.pos() + 1);
3300
3301 #ifndef HAVE_SSTREAM
3302         delete [] latex.str();
3303 #endif
3304         // Finally, we copy the word to a string and return it
3305         char * str = 0;
3306
3307         if (sel_cursor.pos() < cursor.pos()) {
3308                 str = new char [cursor.pos() - sel_cursor.pos() + 2];
3309                 LyXParagraph::size_type i, j;
3310                 for (i = sel_cursor.pos(), j = 0; i < cursor.pos(); ++i) {
3311                         if (cursor.par()->GetChar(i) != LyXParagraph::META_INSET)
3312                                 str[j++] = cursor.par()->GetChar(i);
3313                 }
3314                 str[j] = '\0';
3315         }
3316         return str;
3317 }
3318
3319
3320 // This one is also only for the spellchecker
3321 void LyXText::SelectSelectedWord(BufferView * bview)
3322 {
3323         // move cursor to the beginning
3324         SetCursor(bview, sel_cursor.par(), sel_cursor.pos());
3325         
3326         // set the sel cursor
3327         sel_cursor = cursor;
3328
3329 #ifdef HAVE_SSTREAM
3330         std::ostringstream latex;
3331 #else
3332         ostrstream latex;
3333 #endif
3334         
3335         // now find the end of the word
3336         while (cursor.pos() < cursor.par()->Last()
3337                && (cursor.par()->IsLetter(cursor.pos())
3338                    || (cursor.par()->GetChar(cursor.pos()) == LyXParagraph::META_INSET
3339                        && cursor.par()->GetInset(cursor.pos()) != 0
3340                        && cursor.par()->GetInset(cursor.pos())->Latex(bview->buffer(), latex, false, false) == 0
3341 #ifdef HAVE_SSTREAM
3342                        && latex.str() == "\\-"
3343 #else
3344                        && string(latex.str(), 3) == "\\-"
3345 #endif
3346                            )))
3347                 cursor.pos(cursor.pos() + 1);
3348         
3349 #ifndef HAVE_SSTREAM
3350         delete [] latex.str();
3351 #endif
3352         SetCursor(bview, cursor.par(), cursor.pos());
3353         
3354         // finally set the selection
3355         SetSelection();
3356 }
3357
3358
3359 /* -------> Delete from cursor up to the end of the current or next word. */
3360 void LyXText::DeleteWordForward(BufferView * bview)
3361 {
3362         if (!cursor.par()->Last())
3363                 CursorRight(bview);
3364         else {
3365                 LyXCursor tmpcursor = cursor;
3366                 tmpcursor.row(0); // ??
3367                 selection = true; // to avoid deletion 
3368                 CursorRightOneWord(bview);
3369                 SetCursor(bview, tmpcursor, tmpcursor.par(), tmpcursor.pos());
3370                 sel_cursor = cursor;
3371                 cursor = tmpcursor;
3372                 SetSelection(); 
3373                 
3374                 /* -----> Great, CutSelection() gets rid of multiple spaces. */
3375                 CutSelection(bview);
3376         }
3377 }
3378
3379
3380 /* -------> Delete from cursor to start of current or prior word. */
3381 void LyXText::DeleteWordBackward(BufferView * bview)
3382 {
3383        if (!cursor.par()->Last())
3384                CursorLeft(bview);
3385        else {
3386                LyXCursor tmpcursor = cursor;
3387                tmpcursor.row(0); // ??
3388                selection = true; // to avoid deletion 
3389                CursorLeftOneWord(bview);
3390                SetCursor(bview, tmpcursor, tmpcursor.par(), tmpcursor.pos());
3391                sel_cursor = cursor;
3392                cursor = tmpcursor;
3393                SetSelection();
3394                CutSelection(bview);
3395        }
3396 }
3397
3398
3399 /* -------> Kill to end of line. */
3400 void LyXText::DeleteLineForward(BufferView * bview)
3401 {
3402         if (!cursor.par()->Last())
3403                 // Paragraph is empty, so we just go to the right
3404                 CursorRight(bview);
3405         else {
3406                 LyXCursor tmpcursor = cursor;
3407                 // We can't store the row over a regular SetCursor
3408                 // so we set it to 0 and reset it afterwards.
3409                 tmpcursor.row(0); // ??
3410                 selection = true; // to avoid deletion 
3411                 CursorEnd(bview);
3412                 SetCursor(bview, tmpcursor, tmpcursor.par(), tmpcursor.pos());
3413                 sel_cursor = cursor;
3414                 cursor = tmpcursor;
3415                 SetSelection();
3416                 // What is this test for ??? (JMarc)
3417                 if (!selection) {
3418                         DeleteWordForward(bview);
3419                 } else {
3420                         CutSelection(bview);
3421                 }
3422         }
3423 }
3424
3425
3426 // Change the case of a word at cursor position. 
3427 // This function directly manipulates LyXParagraph::text because there
3428 // is no LyXParagraph::SetChar currently. I did what I could to ensure
3429 // that it is correct. I guess part of it should be moved to
3430 // LyXParagraph, but it will have to change for 1.1 anyway. At least
3431 // it does not access outside of the allocated array as the older
3432 // version did. (JMarc) 
3433 void LyXText::ChangeWordCase(BufferView * bview, LyXText::TextCase action) 
3434 {
3435         LyXParagraph * tmppar = cursor.par()->ParFromPos(cursor.pos());
3436
3437         SetUndo(bview->buffer(),Undo::FINISH, tmppar->previous, tmppar->next); 
3438
3439         LyXParagraph::size_type tmppos = 
3440                 cursor.par()->PositionInParFromPos(cursor.pos());
3441         while (tmppos < tmppar->size()) {
3442                 unsigned char c = tmppar->GetChar(tmppos);
3443                 if (IsKommaChar(c) || IsLineSeparatorChar(c))
3444                         break;
3445                 if (c != LyXParagraph::META_INSET) {
3446                         switch (action) {
3447                         case text_lowercase:
3448                                 c = tolower(c);
3449                                 break;
3450                         case text_capitalization:
3451                                 c = toupper(c);
3452                                 action = text_lowercase;
3453                                 break;
3454                         case text_uppercase:
3455                                 c = toupper(c);
3456                                 break;
3457                         }
3458                 }
3459                 
3460                 //tmppar->text[tmppos] = c;
3461                 tmppar->SetChar(tmppos, c);
3462                 ++tmppos;
3463         }
3464         CheckParagraph(bview, tmppar, tmppos);
3465         CursorRightOneWord(bview);
3466 }
3467
3468
3469 void LyXText::Delete(BufferView * bview)
3470 {
3471         // this is a very easy implementation
3472
3473         LyXCursor old_cursor = cursor;
3474         int old_cur_par_id = old_cursor.par()->id();
3475         int old_cur_par_prev_id = old_cursor.par()->previous ?
3476                 old_cursor.par()->previous->id() : 0;
3477         
3478         // just move to the right
3479         CursorRightIntern(bview);
3480
3481         // CHECK Look at the comment here.
3482         // This check is not very good...
3483         // The CursorRightIntern calls DeleteEmptyParagrapgMechanism
3484         // and that can very well delete the par or par->previous in
3485         // old_cursor. Will a solution where we compare paragraph id's
3486         //work better?
3487         if ((cursor.par()->previous ? cursor.par()->previous->id() : 0)
3488             == old_cur_par_prev_id
3489             && cursor.par()->id() != old_cur_par_id)
3490                 return; // delete-empty-paragraph-mechanism has done it
3491
3492         // if you had success make a backspace
3493         if (old_cursor.par() != cursor.par() || old_cursor.pos() != cursor.pos()) {
3494                 LyXCursor tmpcursor = cursor;
3495                 cursor = old_cursor; // to make sure undo gets the right cursor position
3496                 SetUndo(bview->buffer(), Undo::DELETE, 
3497                         cursor.par()->ParFromPos(cursor.pos())->previous, 
3498                         cursor.par()->ParFromPos(cursor.pos())->next); 
3499                 cursor = tmpcursor;
3500                 Backspace(bview);
3501         }
3502 }
3503
3504
3505 void LyXText::Backspace(BufferView * bview)
3506 {
3507 #ifndef NEW_TABULAR
3508         /* table stuff -- begin */
3509         if (cursor.par()->table) {
3510                 BackspaceInTable(bview);
3511                 return;
3512         }
3513         /* table stuff -- end */
3514 #endif
3515         // LyXFont rawtmpfont = current_font;
3516         // LyXFont realtmpfont = real_current_font;
3517         //    We don't need the above variables as calling to SetCursor() with third
3518         //    argument eqaul to false, will not change current_font & real_current_font
3519         
3520         // Get the font that is used to calculate the baselineskip
3521         LyXParagraph::size_type lastpos = cursor.par()->Last();
3522         LyXFont rawparfont = cursor.par()->GetFontSettings(bview->buffer()->params,
3523                                                          lastpos - 1);
3524
3525         if (cursor.pos() == 0) {
3526                 // The cursor is at the beginning of a paragraph, so the the backspace
3527                 // will collapse two paragraphs into one.
3528                 
3529                 // we may paste some paragraphs
3530       
3531                 // is it an empty paragraph?
3532       
3533                 if ((lastpos == 0
3534                      || (lastpos == 1 && cursor.par()->IsSeparator(0)))
3535 #ifndef NEW_INSETS
3536                     && !(cursor.par()->Next() 
3537                          && cursor.par()->footnoteflag == LyXParagraph::NO_FOOTNOTE
3538                          && cursor.par()->Next()->footnoteflag == LyXParagraph::OPEN_FOOTNOTE)
3539 #endif
3540                         ) {
3541                         // This is an empty paragraph and we delete it just by moving the cursor one step
3542                         // left and let the DeleteEmptyParagraphMechanism handle the actual deletion
3543                         // of the paragraph.
3544                         
3545                         if (cursor.par()->previous) {
3546 #ifndef NEW_INSETS
3547                                 LyXParagraph * tmppar = cursor.par()->previous->FirstPhysicalPar();
3548 #else
3549                                 LyXParagraph * tmppar = cursor.par()->previous;
3550 #endif
3551                                 if (cursor.par()->GetLayout() == tmppar->GetLayout()
3552 #ifndef NEW_INSETS
3553                                     && cursor.par()->footnoteflag == tmppar->footnoteflag
3554 #endif
3555                                     && cursor.par()->GetAlign() == tmppar->GetAlign()) {
3556                                         // Inherit botom DTD from the paragraph below.
3557                                         // (the one we are deleting)
3558                                         tmppar->line_bottom = cursor.par()->line_bottom;
3559                                         tmppar->added_space_bottom = cursor.par()->added_space_bottom;
3560                                         tmppar->pagebreak_bottom = cursor.par()->pagebreak_bottom;
3561                                 }
3562                                 
3563                                 CursorLeftIntern(bview);
3564                      
3565                                 // the layout things can change the height of a row !
3566                                 int tmpheight = cursor.row()->height();
3567                                 SetHeightOfRow(bview, cursor.row());
3568                                 if (cursor.row()->height() != tmpheight) {
3569                                         refresh_y = cursor.y() - cursor.row()->baseline();
3570                                         refresh_row = cursor.row();
3571                                         status = LyXText::NEED_MORE_REFRESH;
3572                                 }
3573                                 return;
3574                         }
3575                 }
3576                 
3577                 if (cursor.par()->ParFromPos(cursor.pos())->previous){
3578                         SetUndo(bview->buffer(), Undo::DELETE,
3579                                 cursor.par()->ParFromPos(cursor.pos())->previous->previous,
3580                                 cursor.par()->ParFromPos(cursor.pos())->next);
3581                 }
3582                 
3583                 LyXParagraph * tmppar = cursor.par();
3584                 Row * tmprow = cursor.row();
3585
3586                 // We used to do CursorLeftIntern() here, but it is
3587                 // not a good idea since it triggers the auto-delete
3588                 // mechanism. So we do a CursorLeftIntern()-lite,
3589                 // without the dreaded mechanism. (JMarc)
3590                 if (cursor.par()->Previous()) { 
3591                         // steps into the above paragraph.
3592                         SetCursorIntern(bview, cursor.par()->Previous(), 
3593                                         cursor.par()->Previous()->Last(), false);
3594                 }
3595
3596                 /* Pasting is not allowed, if the paragraphs have different
3597                    layout. I think it is a real bug of all other
3598                    word processors to allow it. It confuses the user.
3599                    Even so with a footnote paragraph and a non-footnote
3600                    paragraph. I will not allow pasting in this case, 
3601                    because the user would be confused if the footnote behaves 
3602                    different wether it is open or closed.
3603                   
3604                    Correction: Pasting is always allowed with standard-layout
3605                 */
3606                 if (cursor.par() != tmppar
3607                     && (cursor.par()->GetLayout() == tmppar->GetLayout()
3608                         || tmppar->GetLayout() == 0 /*standard*/)
3609 #ifndef NEW_INSETS
3610                     && cursor.par()->footnoteflag == tmppar->footnoteflag
3611 #endif
3612 #ifndef NEW_TABULAR
3613                     /* table stuff -- begin*/
3614                     && !cursor.par()->table /* no pasting of tables */ 
3615                     /* table stuff -- end*/
3616 #endif
3617                     && cursor.par()->GetAlign() == tmppar->GetAlign()) {
3618
3619                         RemoveParagraph(tmprow);
3620                         RemoveRow(tmprow);
3621                         cursor.par()->PasteParagraph(bview->buffer()->params);
3622                         
3623                         if (!cursor.pos() || !cursor.par()->IsSeparator(cursor.pos() - 1))
3624                                 ; //cursor.par()->InsertChar(cursor.pos(), ' ');
3625                         // strangely enough it seems that commenting out the line above removes
3626                         // most or all of the segfaults. I will however also try to move the
3627                         // two Remove... lines in front of the PasteParagraph too.
3628                         else
3629                                 if (cursor.pos())
3630                                         cursor.pos(cursor.pos() - 1);
3631                         
3632                         status = LyXText::NEED_MORE_REFRESH;
3633                         refresh_row = cursor.row();
3634                         refresh_y = cursor.y() - cursor.row()->baseline();
3635                         
3636                         // remove the lost paragraph
3637                         // This one is not safe, since the paragraph that the tmprow and the
3638                         // following rows belong to has been deleted by the PasteParagraph
3639                         // above. The question is... could this be moved in front of the
3640                         // PasteParagraph?
3641                         //RemoveParagraph(tmprow);
3642                         //RemoveRow(tmprow);  
3643                         
3644                         // This rebuilds the rows.
3645                         AppendParagraph(bview, cursor.row());
3646                         UpdateCounters(bview, cursor.row());
3647                         
3648                         // the row may have changed, block, hfills etc.
3649                         SetCursor(bview, cursor.par(), cursor.pos(), false);
3650                 }
3651         } else {
3652                 /* this is the code for a normal backspace, not pasting
3653                  * any paragraphs */ 
3654                 SetUndo(bview->buffer(), Undo::DELETE, 
3655                         cursor.par()->ParFromPos(cursor.pos())->previous, 
3656                         cursor.par()->ParFromPos(cursor.pos())->next); 
3657                 // We used to do CursorLeftIntern() here, but it is
3658                 // not a good idea since it triggers the auto-delete
3659                 // mechanism. So we do a CursorLeftIntern()-lite,
3660                 // without the dreaded mechanism. (JMarc)
3661                 SetCursorIntern(bview, cursor.par(), cursor.pos()- 1,
3662                                 false, cursor.boundary());
3663                 
3664                 // some insets are undeletable here
3665                 if (cursor.par()->GetChar(cursor.pos()) == LyXParagraph::META_INSET) {
3666                         if (!cursor.par()->GetInset(cursor.pos())->Deletable())
3667                                 return; 
3668                         // force complete redo when erasing display insets
3669                         // this is a cruel method but safe..... Matthias 
3670                         if (cursor.par()->GetInset(cursor.pos())->display() ||
3671                             cursor.par()->GetInset(cursor.pos())->needFullRow()) {
3672                                 cursor.par()->Erase(cursor.pos());
3673                                 RedoParagraph(bview);
3674                                 return;
3675                         }
3676                 }
3677                 
3678                 Row * row = cursor.row();
3679                 long y = cursor.y() - row->baseline();
3680                 LyXParagraph::size_type z;
3681                 /* remember that a space at the end of a row doesnt count
3682                  * when calculating the fill */ 
3683                 if (cursor.pos() < RowLast(row) ||
3684                     !cursor.par()->IsLineSeparator(cursor.pos())) {
3685                         row->fill(row->fill() + SingleWidth(bview,
3686                                                             cursor.par(),
3687                                                             cursor.pos()));
3688                 }
3689                 
3690                 /* some special code when deleting a newline. This is similar
3691                  * to the behavior when pasting paragraphs */ 
3692                 if (cursor.pos() && cursor.par()->IsNewline(cursor.pos())) {
3693                         cursor.par()->Erase(cursor.pos());
3694                         // refresh the positions
3695                         Row * tmprow = row;
3696                         while (tmprow->next() && tmprow->next()->par() == row->par()) {
3697                                 tmprow = tmprow->next();
3698                                 tmprow->pos(tmprow->pos() - 1);
3699                         }
3700                         if (cursor.par()->IsLineSeparator(cursor.pos() - 1))
3701                                 cursor.pos(cursor.pos() - 1);
3702                         
3703                         if (cursor.pos() < cursor.par()->Last() && !cursor.par()->IsSeparator(cursor.pos())) {
3704                                 cursor.par()->InsertChar(cursor.pos(), ' ');
3705                                 // refresh the positions
3706                                 tmprow = row;
3707                                 while (tmprow->next() && tmprow->next()->par() == row->par()) {
3708                                         tmprow = tmprow->next();
3709                                         tmprow->pos(tmprow->pos() + 1);
3710                                 }
3711                         }
3712                 } else {
3713                         cursor.par()->Erase(cursor.pos());
3714                         
3715                         // refresh the positions
3716                         Row * tmprow = row;
3717                         while (tmprow->next()
3718                                && tmprow->next()->par() == row->par()) {
3719                                 tmprow = tmprow->next();
3720                                 tmprow->pos(tmprow->pos() - 1);
3721                         }
3722
3723                         // delete newlines at the beginning of paragraphs
3724                         while (cursor.par()->Last() &&
3725                                cursor.par()->IsNewline(cursor.pos()) &&
3726                                cursor.pos() == BeginningOfMainBody(bview->buffer(),
3727                                                                    cursor.par())) {
3728                                 cursor.par()->Erase(cursor.pos());
3729                                 // refresh the positions
3730                                 tmprow = row;
3731                                 while (tmprow->next() && 
3732                                        tmprow->next()->par() == row->par()) {
3733                                         tmprow = tmprow->next();
3734                                         tmprow->pos(tmprow->pos() - 1);
3735                                 }
3736                         }
3737                 }
3738                 
3739                 // is there a break one row above
3740                 if (row->previous() && row->previous()->par() == row->par()) {
3741                         z = NextBreakPoint(bview, row->previous(),
3742                                            workWidth(bview));
3743                         if ( z >= row->pos()) {
3744                                 row->pos(z + 1);
3745                                 
3746                                 Row * tmprow = row->previous();
3747                                 
3748                                 // maybe the current row is now empty
3749                                 if (row->pos() >= row->par()->Last()) {
3750                                         // remove it
3751                                         RemoveRow(row);
3752                                         need_break_row = 0;
3753                                 } else {
3754                                         BreakAgainOneRow(bview, row);
3755                                         if (row->next() && row->next()->par() == row->par())
3756                                                 need_break_row = row->next();
3757                                         else
3758                                                 need_break_row = 0;
3759                                 }
3760                                 
3761                                 // set the dimensions of the row above
3762                                 y -= tmprow->height();
3763                                 tmprow->fill(Fill(bview, tmprow,
3764                                                   workWidth(bview)));
3765                                 SetHeightOfRow(bview, tmprow);
3766                                 
3767                                 refresh_y = y;
3768                                 refresh_row = tmprow;
3769                                 status = LyXText::NEED_MORE_REFRESH;
3770                                 SetCursor(bview, cursor.par(), cursor.pos(),
3771                                           false, cursor.boundary());
3772                                 //current_font = rawtmpfont;
3773                                 //real_current_font = realtmpfont;
3774                                 // check, whether the last character's font has changed.
3775                                 if (rawparfont !=
3776                                     cursor.par()->GetFontSettings(bview->buffer()->params,
3777                                                                   cursor.par()->Last() - 1))
3778                                         RedoHeightOfParagraph(bview, cursor);
3779                                 return;
3780                         }
3781                 }
3782                 
3783                 // break the cursor row again
3784                 if (row->next() && row->next()->par() == row->par() &&
3785                     (RowLast(row) == row->par()->Last() - 1 ||
3786                      NextBreakPoint(bview, row, workWidth(bview)) != RowLast(row))) {
3787                         
3788                         /* it can happen that a paragraph loses one row
3789                          * without a real breakup. This is when a word
3790                          * is to long to be broken. Well, I don t care this 
3791                          * hack ;-) */ 
3792                         if (RowLast(row) == row->par()->Last() - 1)
3793                                 RemoveRow(row->next());
3794                         
3795                         refresh_y = y;
3796                         refresh_row = row;
3797                         status = LyXText::NEED_MORE_REFRESH;
3798                         
3799                         BreakAgainOneRow(bview, row);
3800                         SetCursor(bview, cursor.par(), cursor.pos(), false, cursor.boundary());
3801                         // cursor MUST be in row now
3802                         
3803                         need_break_row = row->next();
3804                 } else  {
3805                         // set the dimensions of the row
3806                         row->fill(Fill(bview, row, workWidth(bview)));
3807                         int tmpheight = row->height();
3808                         SetHeightOfRow(bview, row);
3809                         if (tmpheight == row->height())
3810                                 status = LyXText::NEED_VERY_LITTLE_REFRESH;
3811                         else
3812                                 status = LyXText::NEED_MORE_REFRESH;
3813                         refresh_y = y;
3814                         refresh_row = row;
3815                         SetCursor(bview, cursor.par(), cursor.pos(), false, cursor.boundary());
3816                 }
3817         }
3818
3819         // current_font = rawtmpfont;
3820         // real_current_font = realtmpfont;
3821
3822         lastpos = cursor.par()->Last();
3823         if (cursor.pos() == lastpos) {
3824                 if (IsBoundary(bview->buffer(), cursor.par(), cursor.pos()) != cursor.boundary())
3825                         SetCursor(bview, cursor.par(), cursor.pos(), false, !cursor.boundary());
3826                 SetCurrentFont(bview);
3827         }
3828         
3829         // check, wether the last characters font has changed.
3830         if (rawparfont != 
3831             cursor.par()->GetFontSettings(bview->buffer()->params, lastpos - 1)) {
3832                 RedoHeightOfParagraph(bview, cursor);
3833         } else {
3834                 // now the special right address boxes
3835                 if (textclasslist.Style(bview->buffer()->params.textclass,
3836                                         cursor.par()->GetLayout()).margintype == MARGIN_RIGHT_ADDRESS_BOX) {
3837                         RedoDrawingOfParagraph(bview, cursor); 
3838                 }
3839         }
3840 }
3841
3842
3843 void LyXText::GetVisibleRow(BufferView * bview, int y_offset, int x_offset,
3844                             Row * row_ptr, long y, bool cleared)
3845 {
3846         /* returns a printed row */
3847         Painter & pain = bview->painter();
3848         
3849         bool is_rtl = row_ptr->par()->isRightToLeftPar(bview->buffer()->params);
3850         LyXParagraph::size_type last = RowLastPrintable(row_ptr);
3851
3852         LyXParagraph::size_type vpos, pos;
3853         float x, tmpx;
3854         int y_top, y_bottom;
3855         float fill_separator, fill_hfill, fill_label_hfill;
3856
3857         LyXFont font(LyXFont::ALL_SANE);
3858         int maxdesc;
3859         if (row_ptr->height() <= 0) {
3860                 lyxerr << "LYX_ERROR: row.height: "
3861                        << row_ptr->height() << endl;
3862                 return;
3863         }
3864         PrepareToPrint(bview, row_ptr, x, fill_separator,
3865                        fill_hfill, fill_label_hfill);
3866         
3867         if (inset_owner && (x < 0))
3868                 x = 0;
3869         x += x_offset;
3870         
3871         // clear the area where we want to paint/print
3872         int ww;
3873         ww = bview->workWidth();
3874
3875         bool clear_area = true;
3876         Inset * inset = 0;
3877
3878         if ((last == row_ptr->pos()) &&
3879             (row_ptr->par()->GetChar(row_ptr->pos()) == LyXParagraph::META_INSET) &&
3880             (inset=row_ptr->par()->GetInset(row_ptr->pos())))
3881         {
3882                 clear_area = inset->doClearArea();
3883         }
3884         if (cleared) { // we don't need to clear it's already done!!!
3885                 clear_area = true;
3886         } else if (clear_area) {
3887                 int w;
3888                 if (inset_owner)
3889                         w = inset_owner->width(bview, font);
3890                 else
3891                         w = ww;
3892                 pain.fillRectangle(x_offset, y_offset, w, row_ptr->height());
3893         } else if (inset != 0) {
3894                 int h = row_ptr->baseline() - inset->ascent(bview, font);
3895                 if (h > 0) {
3896                         int w;
3897                         if (inset_owner)
3898                                 w = inset_owner->width(bview, font);
3899                         else
3900                                 w = ww;
3901                         pain.fillRectangle(x_offset, y_offset, w, h);
3902                 }
3903                 h += inset->ascent(bview, font) + inset->descent(bview, font);
3904                 if ((row_ptr->height() - h) > 0) {
3905                         int w;
3906                         if (inset_owner)
3907                                 w = inset_owner->width(bview, font);
3908                         else
3909                                 w = ww;
3910                         pain.fillRectangle(x_offset,h, w, row_ptr->height()-h);
3911                 }
3912                 if (!inset_owner && !inset->display() && !inset->needFullRow())
3913                 {
3914                         int w = inset->width(bview, font) + int(x);
3915                         pain.fillRectangle(w, y_offset, ww - w, row_ptr->height());
3916                 }
3917         }
3918         
3919         if (selection) {
3920                 int w;
3921                 if (inset_owner)
3922                         w = inset_owner->width(bview, font);
3923                 else
3924                         w = ww;
3925                 /* selection code */
3926                 if (bidi_same_direction) {
3927                         if (sel_start_cursor.row() == row_ptr &&
3928                             sel_end_cursor.row() == row_ptr) {
3929                                 if (sel_start_cursor.x() < sel_end_cursor.x())
3930                                         pain.fillRectangle(x_offset + sel_start_cursor.x(),
3931                                                            y_offset,
3932                                                            sel_end_cursor.x() - sel_start_cursor.x(),
3933                                                            row_ptr->height(),
3934                                                            LColor::selection);
3935                                 else
3936                                         pain.fillRectangle(x_offset + sel_end_cursor.x(),
3937                                                            y_offset,
3938                                                            sel_start_cursor.x() - sel_end_cursor.x(),
3939                                                            row_ptr->height(),
3940                                                            LColor::selection);
3941                         } else if (sel_start_cursor.row() == row_ptr) {
3942                                 if (is_rtl)
3943                                         pain.fillRectangle(x_offset, y_offset,
3944                                                            sel_start_cursor.x(),
3945                                                            row_ptr->height(),
3946                                                            LColor::selection);
3947                                 else
3948                                         pain.fillRectangle(x_offset + sel_start_cursor.x(),
3949                                                            y_offset,
3950                                                            w - sel_start_cursor.x(),
3951                                                            row_ptr->height(),
3952                                                            LColor::selection);
3953                         } else if (sel_end_cursor.row() == row_ptr) {
3954                                 if (is_rtl)
3955                                         pain.fillRectangle(x_offset + sel_end_cursor.x(),
3956                                                            y_offset,
3957                                                            w - sel_end_cursor.x(),
3958                                                            row_ptr->height(),
3959                                                            LColor::selection);
3960                                 else
3961                                         pain.fillRectangle(x_offset, y_offset,
3962                                                            sel_end_cursor.x(),
3963                                                            row_ptr->height(),
3964                                                            LColor::selection);
3965                         } else if (y > long(sel_start_cursor.y())
3966                                    && y < long(sel_end_cursor.y())) {
3967                                 pain.fillRectangle(x_offset, y_offset, w,
3968                                                    row_ptr->height(),
3969                                                    LColor::selection);
3970                         }
3971                 } else if ( sel_start_cursor.row() != row_ptr &&
3972                             sel_end_cursor.row() != row_ptr &&
3973                             y > long(sel_start_cursor.y())
3974                             && y < long(sel_end_cursor.y())) {
3975                         pain.fillRectangle(x_offset, y_offset, w,
3976                                            row_ptr->height(),
3977                                            LColor::selection);
3978                 } else if (sel_start_cursor.row() == row_ptr ||
3979                            sel_end_cursor.row() == row_ptr) {
3980                         float tmpx = x;
3981 #ifndef NEW_TABULAR
3982                         int cell = 0;
3983                         if (row_ptr->par()->table) {
3984                                 cell = NumberOfCell(row_ptr->par(), row_ptr->pos());
3985                                 tmpx += row_ptr->par()->table->GetBeginningOfTextInCell(cell);
3986                         }
3987 #endif
3988                         if ( (sel_start_cursor.row() != row_ptr && !is_rtl) ||
3989                              (sel_end_cursor.row() != row_ptr && is_rtl))
3990                                 pain.fillRectangle(x_offset, y_offset,
3991                                                    int(tmpx),
3992                                                    row_ptr->height(),
3993                                                    LColor::selection);
3994 #ifndef NEW_TABULAR
3995                         if (row_ptr->par()->table) {
3996                                 float x_old = x;
3997                                 for (vpos = row_ptr->pos(); vpos <= last; ++vpos)  {
3998                                         pos = vis2log(vpos);
3999                                         float old_tmpx = tmpx;
4000                                         if (row_ptr->par()->IsNewline(pos)) {
4001                                                 tmpx = x_old + row_ptr->par()->table->WidthOfColumn(cell);
4002                                                 x_old = tmpx;
4003                                                 ++cell;
4004                                                 tmpx += row_ptr->par()->table->GetBeginningOfTextInCell(cell);
4005                                         } else {
4006                                                 tmpx += SingleWidth(bview, row_ptr->par(), pos);
4007                                         }
4008                                         if ( (sel_start_cursor.row() != row_ptr ||
4009                                               sel_start_cursor.pos() <= pos) &&
4010                                              (sel_end_cursor.row() != row_ptr ||
4011                                               pos < sel_end_cursor.pos()) )
4012                                                 pain.fillRectangle(x_offset + int(old_tmpx),
4013                                                                    y_offset,
4014                                                                    int(tmpx - old_tmpx + 1),
4015                                                                    row_ptr->height(),
4016                                                                    LColor::selection);
4017                                 }
4018                         } else {
4019 #endif
4020                                 LyXParagraph::size_type main_body =
4021                                         BeginningOfMainBody(bview->buffer(),
4022                                                             row_ptr->par());
4023
4024                                 for (vpos = row_ptr->pos(); vpos <= last; ++vpos)  {
4025                                         pos = vis2log(vpos);
4026                                         float old_tmpx = tmpx;
4027                                         if (main_body > 0 && pos == main_body-1) {
4028                                                 tmpx += fill_label_hfill +
4029                                                         lyxfont::width(textclasslist.Style(bview->buffer()->params.textclass,
4030                                                                                            row_ptr->par()->GetLayout()).labelsep,
4031                                                                        GetFont(bview->buffer(),row_ptr->par(), -2));
4032                                                 if (row_ptr->par()->IsLineSeparator(main_body-1))
4033                                                         tmpx -= SingleWidth(bview, row_ptr->par(), main_body-1);
4034                                         }
4035                                         if (HfillExpansion(bview->buffer(), row_ptr, pos)) {
4036                                                 tmpx += SingleWidth(bview, row_ptr->par(), pos);
4037                                                 if (pos >= main_body)
4038                                                         tmpx += fill_hfill;
4039                                                 else 
4040                                                         tmpx += fill_label_hfill;
4041                                         }
4042                                         else if (row_ptr->par()->IsSeparator(pos)) {
4043                                                 tmpx += SingleWidth(bview, row_ptr->par(), pos);
4044                                                 if (pos >= main_body)
4045                                                         tmpx += fill_separator;
4046                                         } else
4047                                                 tmpx += SingleWidth(bview, row_ptr->par(), pos);
4048
4049                                         if ( (sel_start_cursor.row() != row_ptr ||
4050                                               sel_start_cursor.pos() <= pos) &&
4051                                              (sel_end_cursor.row() != row_ptr ||
4052                                               pos < sel_end_cursor.pos()) )
4053                                                 pain.fillRectangle(x_offset + int(old_tmpx),
4054                                                                    y_offset,
4055                                                                    int(tmpx - old_tmpx + 1),
4056                                                                    row_ptr->height(),
4057                                                                    LColor::selection);
4058                                 }
4059 #ifndef NEW_TABULAR
4060                         }
4061 #endif
4062                         if ( (sel_start_cursor.row() != row_ptr && is_rtl) ||
4063                              (sel_end_cursor.row() != row_ptr && !is_rtl) )
4064                                 pain.fillRectangle(x_offset + int(tmpx),
4065                                                    y_offset,
4066                                                    int(ww - tmpx),
4067                                                    row_ptr->height(),
4068                                                    LColor::selection);
4069                 }
4070         }
4071
4072         int box_x = 0;
4073 #ifndef NEW_INSETS
4074         if (row_ptr->par()->footnoteflag == LyXParagraph::OPEN_FOOTNOTE) {
4075                 LyXFont font(LyXFont::ALL_SANE);
4076                 font.setSize(LyXFont::SIZE_FOOTNOTE);
4077                 font.setColor(LColor::footnote);
4078                 
4079                 box_x = LYX_PAPER_MARGIN + lyxfont::width(" wide-tab ", font);
4080                 if (row_ptr->previous() &&
4081                     row_ptr->previous()->par()->footnoteflag != LyXParagraph::OPEN_FOOTNOTE){
4082                         string fs;
4083                         switch (row_ptr->par()->footnotekind) {
4084                         case LyXParagraph::MARGIN:
4085                                 fs = " margin";
4086                                 break;
4087                         case LyXParagraph::FIG:
4088                                 fs = " fig";
4089                                 break;
4090                         case LyXParagraph::TAB:
4091                                 fs = " tab";
4092                                 break;
4093                         case LyXParagraph::WIDE_FIG:
4094                                 fs = " wide-fig";
4095                                 break;
4096                         case LyXParagraph::WIDE_TAB:
4097                                 fs = " wide-tab";
4098                                 break;
4099                         case LyXParagraph::ALGORITHM:
4100                                 fs = " alg";
4101                                 break;
4102                         case LyXParagraph::FOOTNOTE:
4103                                 fs = " foot";
4104                                 break;
4105                         }
4106                         
4107                         pain.fillRectangle(LYX_PAPER_MARGIN,
4108                                            y_offset + 1,
4109                                            box_x - LYX_PAPER_MARGIN,
4110                                            int(lyxfont::maxAscent(font)
4111                                                + lyxfont::maxDescent(font)),
4112                                            LColor::footnotebg);
4113                         
4114                         pain.line(LYX_PAPER_MARGIN, y_offset,
4115                                   workWidth(bview) - LYX_PAPER_MARGIN, y_offset,
4116                                   LColor::footnoteframe);
4117                         
4118                         pain.text(LYX_PAPER_MARGIN,
4119                                   y_offset + int(lyxfont::maxAscent(font)) + 1,
4120                                   fs, font);
4121                         
4122                         pain.line(LYX_PAPER_MARGIN, y_offset,
4123                                   LYX_PAPER_MARGIN,
4124                                   y_offset + int(lyxfont::maxAscent(font)
4125                                                + lyxfont::maxDescent(font)),
4126                                   LColor::footnoteframe);
4127                         
4128                         pain.line(LYX_PAPER_MARGIN,
4129                                   y_offset + int(lyxfont::maxAscent(font)
4130                                                + lyxfont::maxDescent(font)) + 1,
4131                                   box_x,
4132                                   y_offset + int(lyxfont::maxAscent(font)
4133                                                + lyxfont::maxDescent(font)) + 1,
4134                                   LColor::footnoteframe);
4135                         
4136                 }
4137                 
4138                 /* draw the open floats in a red box */
4139                 pain.line(box_x, y_offset,
4140                           box_x, y_offset + row_ptr->height(),
4141                           LColor::footnoteframe);
4142                 
4143                 pain.line(workWidth(bview) - LYX_PAPER_MARGIN,
4144                           y_offset,
4145                           workWidth(bview) - LYX_PAPER_MARGIN,
4146                           y_offset + row_ptr->height(),
4147                           LColor::footnoteframe);
4148
4149
4150                 // Draw appendix lines
4151                 LyXParagraph * p = row_ptr->par()->PreviousBeforeFootnote()->FirstPhysicalPar();
4152                 if (p->appendix){
4153                         pain.line(1, y_offset,
4154                                   1, y_offset + row_ptr->height(),
4155                                   LColor::appendixline);
4156                         pain.line(workWidth(bview) - 2, y_offset,
4157                                   workWidth(bview) - 2,
4158                                   y_offset + row_ptr->height(),
4159                                   LColor::appendixline);
4160                 }
4161
4162                 // Draw minipage line
4163                 bool minipage = p->pextra_type == LyXParagraph::PEXTRA_MINIPAGE;
4164                 if (minipage)
4165                         pain.line(LYX_PAPER_MARGIN/5, y_offset,
4166                                   LYX_PAPER_MARGIN/5, 
4167                                   y_offset + row_ptr->height() - 1,
4168                                   LColor::minipageline);
4169
4170                 // Draw depth lines
4171                 int depth = p->GetDepth();
4172                 for (int i = 1; i <= depth; ++i) {
4173                         int line_x = (LYX_PAPER_MARGIN / 5) * (i + minipage);
4174                         pain.line(line_x, y_offset, line_x,
4175                                   y_offset + row_ptr->height() - 1,
4176                                   LColor::depthbar);
4177                 }
4178         } else if (row_ptr->previous() &&
4179                    row_ptr->previous()->par()->footnoteflag
4180                    == LyXParagraph::OPEN_FOOTNOTE) {
4181                 LyXFont font(LyXFont::ALL_SANE);
4182                 font.setSize(LyXFont::SIZE_FOOTNOTE);
4183                 
4184                 int box_x = LYX_PAPER_MARGIN;
4185                 box_x += lyxfont::width(" wide-tab ", font);
4186                 
4187                 pain.line(box_x, y_offset,
4188                           workWidth(bview) - LYX_PAPER_MARGIN,
4189                           y_offset, LColor::footnote);
4190         }
4191 #endif
4192         // Draw appendix lines
4193 #ifndef NEW_INSETS
4194         LyXParagraph * firstpar = row_ptr->par()->FirstPhysicalPar();
4195 #else
4196         LyXParagraph * firstpar = row_ptr->par();
4197 #endif
4198         if (firstpar->appendix){
4199                 pain.line(1, y_offset,
4200                           1, y_offset + row_ptr->height(),
4201                           LColor::appendixline);
4202                 pain.line(ww - 2, y_offset,
4203                           ww - 2, y_offset + row_ptr->height(),
4204                           LColor::appendixline);
4205         }
4206
4207         // Draw minipage line
4208         bool minipage = firstpar->pextra_type == LyXParagraph::PEXTRA_MINIPAGE;
4209         if (minipage)
4210                 pain.line(LYX_PAPER_MARGIN/5 + box_x, y_offset,
4211                           LYX_PAPER_MARGIN/5 + box_x, 
4212                           y_offset + row_ptr->height() - 1,
4213                           LColor::minipageline);
4214
4215         // Draw depth lines
4216         int depth = firstpar->GetDepth();
4217         if (depth > 0) {
4218                 int next_depth = 0;
4219                 int prev_depth = 0;
4220                 if (row_ptr->next())
4221 #ifndef NEW_INSETS
4222                         if (row_ptr->par()->footnoteflag ==
4223                             row_ptr->next()->par()->footnoteflag)
4224                                 next_depth = row_ptr->next()->par()->GetDepth();
4225                         else if (row_ptr->par()->footnoteflag != LyXParagraph::OPEN_FOOTNOTE)
4226                                 next_depth = depth;
4227 #else
4228                                 next_depth = row_ptr->next()->par()->GetDepth();
4229 #endif
4230                 if (row_ptr->previous())
4231 #ifndef NEW_INSETS
4232                         if (row_ptr->par()->footnoteflag ==
4233                             row_ptr->previous()->par()->footnoteflag)
4234                                 prev_depth = row_ptr->previous()->par()->GetDepth();
4235                         else if (row_ptr->par()->footnoteflag != LyXParagraph::OPEN_FOOTNOTE)
4236                                 prev_depth = depth;
4237 #else
4238                                 prev_depth = row_ptr->previous()->par()->GetDepth();
4239 #endif
4240
4241                 for (int i = 1; i <= depth; ++i) {
4242                         int line_x = (LYX_PAPER_MARGIN / 5) * (i + minipage) + box_x;
4243                         pain.line(line_x, y_offset, line_x,
4244                                   y_offset + row_ptr->height() - 1 - (i - next_depth - 1) * 3,
4245                                   LColor::depthbar);
4246                 
4247                         if (i > prev_depth)
4248                                 pain.fillRectangle(line_x, y_offset, LYX_PAPER_MARGIN / 5, 2,
4249                                                    LColor::depthbar);
4250                         if (i > next_depth)
4251                                 pain.fillRectangle(line_x,
4252                                                    y_offset + row_ptr->height() - 2 - (i - next_depth - 1) * 3,
4253                                                    LYX_PAPER_MARGIN / 5, 2,
4254                                                    LColor::depthbar);
4255                 }
4256         }
4257
4258         
4259         LyXLayout const & layout =
4260                 textclasslist.Style(bview->buffer()->params.textclass,
4261                                     row_ptr->par()->GetLayout());
4262
4263         y_top = 0;
4264         y_bottom = row_ptr->height();
4265         
4266         /* is it a first row? */ 
4267         if (!row_ptr->pos() && (row_ptr->par() == firstpar)) {
4268                 
4269                 /* start of appendix? */
4270                 if (row_ptr->par()->start_of_appendix){
4271                         pain.line(1, y_offset,
4272                                   ww - 2, y_offset,
4273                                   LColor::appendixline);
4274                 }
4275                 
4276                 /* think about the margins */ 
4277                 if (!row_ptr->previous() && bv_owner)
4278                         y_top += LYX_PAPER_MARGIN;
4279                 
4280                 if (row_ptr->par()->pagebreak_top){ /* draw a top pagebreak  */
4281                         LyXFont pb_font;
4282                         pb_font.setColor(LColor::pagebreak).decSize();
4283                         int w = 0, a = 0, d = 0;
4284                         pain.line(0, y_offset + y_top + 2*DefaultHeight(),
4285                                   ww, 
4286                                   y_offset + y_top + 2 * DefaultHeight(),
4287                                   LColor::pagebreak, 
4288                                   Painter::line_onoffdash)
4289                                 .rectText(0,
4290                                           0,
4291                                           _("Page Break (top)"),
4292                                           pb_font,
4293                                           LColor::background,
4294                                           LColor::background, false, w, a, d);
4295                         pain.rectText((ww - w)/2,
4296                                       y_offset + y_top + 2 * DefaultHeight() + d,
4297                                       _("Page Break (top)"),
4298                                       pb_font,
4299                                       LColor::background,
4300                                       LColor::background);
4301                         y_top += 3 * DefaultHeight();
4302                 }
4303                 
4304                 if (row_ptr->par()->added_space_top.kind() == VSpace::VFILL) {
4305                         /* draw a vfill top  */
4306                         pain.line(0, y_offset + 2 + y_top,
4307                                   LYX_PAPER_MARGIN, y_offset + 2 + y_top,
4308                                   LColor::vfillline);
4309                         
4310                         pain.line(0, y_offset + y_top + 3 * DefaultHeight(),
4311                                   LYX_PAPER_MARGIN,
4312                                   y_offset + y_top + 3 * DefaultHeight(),
4313                                   LColor::vfillline);
4314                         
4315                         pain.line(LYX_PAPER_MARGIN / 2, y_offset + 2 + y_top,
4316                                   LYX_PAPER_MARGIN / 2,
4317                                   y_offset + y_top + 3 * DefaultHeight(),
4318                                   LColor::vfillline);
4319                         
4320                         y_top += 3 * DefaultHeight();
4321                 }
4322                 
4323                 /* think about user added space */ 
4324                 y_top += int(row_ptr->par()->added_space_top.inPixels(bview));
4325                 
4326                 /* think about the parskip */ 
4327                 /* some parskips VERY EASY IMPLEMENTATION */ 
4328                 if (bview->buffer()->params.paragraph_separation == BufferParams::PARSEP_SKIP) {
4329                         if (layout.latextype == LATEX_PARAGRAPH
4330                             && firstpar->GetDepth() == 0
4331                             && firstpar->Previous())
4332                                 y_top += bview->buffer()->params.getDefSkip().inPixels(bview);
4333                         else if (firstpar->Previous()
4334                                  && textclasslist.Style(bview->buffer()->params.textclass,
4335                                                         firstpar->Previous()->GetLayout()).latextype == LATEX_PARAGRAPH
4336                                  && firstpar->Previous()->GetDepth() == 0)
4337                                 // is it right to use defskip here, too? (AS) 
4338                                 y_top += bview->buffer()->params.getDefSkip().inPixels(bview);
4339                 }
4340                 
4341                 if (row_ptr->par()->line_top) {      /* draw a top line  */
4342                         y_top +=  lyxfont::ascent('x',
4343                                                   GetFont(bview->buffer(),
4344                                                           row_ptr->par(), 0));
4345                         
4346                         pain.line(0, y_offset + y_top,
4347                                   ww, y_offset + y_top,
4348                                   LColor::topline,
4349                                   Painter::line_solid,
4350                                   Painter::line_thick);
4351                         
4352                         y_top +=  lyxfont::ascent('x',GetFont(bview->buffer(),
4353                                                               row_ptr->par(), 0));
4354                 }
4355                 
4356                 /* should we print a label? */ 
4357                 if (layout.labeltype >= LABEL_STATIC
4358                     && (layout.labeltype != LABEL_STATIC
4359                         || layout.latextype != LATEX_ENVIRONMENT
4360                         || row_ptr->par()->IsFirstInSequence())) {
4361                         font = GetFont(bview->buffer(), row_ptr->par(), -2);
4362                         if (!row_ptr->par()->GetLabelstring().empty()) {
4363                                 tmpx = x;
4364                                 string tmpstring = row_ptr->par()->GetLabelstring();
4365                                 
4366                                 if (layout.labeltype == LABEL_COUNTER_CHAPTER) {
4367                                         if (bview->buffer()->params.secnumdepth >= 0) {
4368                                                 /* this is special code for the chapter layout. This is printed in
4369                                                  * an extra row and has a pagebreak at the top. */
4370                                                 float spacing_val = 1.0;
4371                                                 if (!row_ptr->par()->spacing.isDefault()) {
4372                                                         spacing_val = row_ptr->par()->spacing.getValue();
4373                                                 } else {
4374                                                         spacing_val = bview->buffer()->params.spacing.getValue();
4375                                                 }
4376    
4377                                                 maxdesc = int(lyxfont::maxDescent(font) * layout.spacing.getValue() * spacing_val)
4378                                                         + int(layout.parsep) * DefaultHeight();
4379                                                 if (is_rtl)
4380                                                         tmpx = ww - LeftMargin(bview, row_ptr) - 
4381                                                                 lyxfont::width(tmpstring, font);
4382                                                 pain.text(int(tmpx),
4383                                                           y_offset + row_ptr->baseline() - row_ptr->ascent_of_text() - maxdesc,
4384                                                           tmpstring, font);
4385                                         }
4386                                 } else {
4387                                         if (is_rtl) {
4388                                                 tmpx = ww - LeftMargin(bview, row_ptr)
4389                                                         + lyxfont::width(layout.labelsep, font);
4390 #ifndef NEW_INSETS
4391                                                 if (row_ptr->par()->footnoteflag == LyXParagraph::OPEN_FOOTNOTE)  {
4392                                                         LyXFont font(LyXFont::ALL_SANE);
4393                                                         font.setSize(LyXFont::SIZE_SMALL);
4394                                                         tmpx += lyxfont::width("Mwide-fixM", font);
4395                                                 }
4396 #endif
4397                                         } else
4398                                                 tmpx = x - lyxfont::width(layout.labelsep, font)
4399                                                         - lyxfont::width(tmpstring, font);
4400
4401                                         /* draw it! */
4402                                         pain.text(int(tmpx),
4403                                                   y_offset + row_ptr->baseline(),
4404                                                   tmpstring, font);
4405                                 }
4406                         }
4407                         /* the labels at the top of an environment. More or less for bibliography */ 
4408                 } else if (layout.labeltype == LABEL_TOP_ENVIRONMENT ||
4409                            layout.labeltype == LABEL_BIBLIO ||
4410                            layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT) {
4411                         if (row_ptr->par()->IsFirstInSequence()) {
4412                                 font = GetFont(bview->buffer(),
4413                                                row_ptr->par(), -2);
4414                                 if (!row_ptr->par()->GetLabelstring().empty()) {
4415                                         string tmpstring = row_ptr->par()->GetLabelstring();
4416                                         float spacing_val = 1.0;
4417                                         if (!row_ptr->par()->spacing.isDefault()) {
4418                                                 spacing_val = row_ptr->par()->spacing.getValue();
4419                                         } else {
4420                                                 spacing_val = bview->buffer()->params.spacing.getValue();
4421                                         }
4422    
4423                                         maxdesc = int(lyxfont::maxDescent(font) * layout.spacing.getValue() * spacing_val
4424                                                       + (layout.labelbottomsep * DefaultHeight()));
4425                                         
4426                                         tmpx = x;
4427                                         if (layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT){
4428                                                 tmpx = ( (is_rtl ? LeftMargin(bview, row_ptr) : x)
4429                                                          + ww - RightMargin(bview->buffer(), row_ptr) ) / 2; 
4430                                                 tmpx -= lyxfont::width(tmpstring, font) / 2;
4431                                         } else if (is_rtl)
4432                                                 tmpx = ww - LeftMargin(bview, row_ptr) - 
4433                                                         lyxfont::width(tmpstring, font);
4434                                         pain.text(int(tmpx),
4435                                                   y_offset + row_ptr->baseline()
4436                                                   - row_ptr->ascent_of_text()
4437                                                   - maxdesc,
4438                                                   tmpstring, font);
4439                                 }
4440                         }
4441                 }
4442                 if (layout.labeltype == LABEL_BIBLIO && row_ptr->par()->bibkey) {
4443                         font = GetFont(bview->buffer(), row_ptr->par(), -1);
4444                         if (is_rtl)
4445                                 tmpx = ww - LeftMargin(bview, row_ptr)
4446                                         + lyxfont::width(layout.labelsep, font);
4447                         else
4448                                 tmpx = x - lyxfont::width(layout.labelsep, font)
4449                                         - row_ptr->par()->bibkey->width(bview, font);
4450                         row_ptr->par()->bibkey->draw(bview, font,
4451                                                    y_offset + row_ptr->baseline(), 
4452                                                    tmpx, clear_area);
4453                 }
4454         }
4455         
4456         /* is it a last row? */
4457 #ifndef NEW_INSETS
4458         LyXParagraph * par = row_ptr->par()->LastPhysicalPar();
4459 #else
4460         LyXParagraph * par = row_ptr->par();
4461 #endif
4462         if ((row_ptr->par()->ParFromPos(last + 1) == par) &&
4463             (!row_ptr->next() || (row_ptr->next()->par() != row_ptr->par())))
4464         {
4465                 /* think about the margins */ 
4466                 if (!row_ptr->next() && bv_owner)
4467                         y_bottom -= LYX_PAPER_MARGIN;
4468                 
4469                 /* draw a bottom pagebreak */ 
4470                 if (firstpar->pagebreak_bottom) {
4471                         LyXFont pb_font;
4472                         pb_font.setColor(LColor::pagebreak).decSize();
4473                         int w = 0, a = 0, d = 0;
4474                         pain.line(0,
4475                                   y_offset + y_bottom - 2 * DefaultHeight(), 
4476                                   ww, 
4477                                   y_offset + y_bottom - 2 * DefaultHeight(),
4478                                   LColor::pagebreak,
4479                                   Painter::line_onoffdash)
4480                                 .rectText(0,
4481                                           0,
4482                                           _("Page Break (bottom)"),
4483                                           pb_font,
4484                                           LColor::background,
4485                                           LColor::background, false, w, a, d);
4486                         pain.rectText((ww - w) / 2,
4487                                       y_offset + y_top + 2 * DefaultHeight() + d,
4488                                       _("Page Break (bottom)"),
4489                                       pb_font,
4490                                       LColor::background,
4491                                       LColor::background);
4492                         y_bottom -= 3 * DefaultHeight();
4493                 }
4494                 
4495                 if (firstpar->added_space_bottom.kind() == VSpace::VFILL) {
4496                         /* draw a vfill bottom  */
4497                         pain.line(0, y_offset + y_bottom - 3 * DefaultHeight(),
4498                                   LYX_PAPER_MARGIN,
4499                                   y_offset + y_bottom - 3 * DefaultHeight(),
4500                                   LColor::vfillline);
4501                         pain.line(0, y_offset + y_bottom - 2,
4502                                   LYX_PAPER_MARGIN,
4503                                   y_offset + y_bottom - 2,
4504                                   LColor::vfillline);
4505                         pain.line(LYX_PAPER_MARGIN / 2,
4506                                   y_offset + y_bottom - 3 * DefaultHeight(),
4507                                   LYX_PAPER_MARGIN / 2,
4508                                   y_offset + y_bottom - 2,
4509                                   LColor::vfillline);
4510                         y_bottom -= 3 * DefaultHeight();
4511                 }
4512                 
4513                 /* think about user added space */ 
4514                 y_bottom -= int(firstpar->added_space_bottom.inPixels(bview));
4515                 
4516                 if (firstpar->line_bottom) {
4517                         /* draw a bottom line */
4518                         y_bottom -= lyxfont::ascent('x', GetFont(bview->buffer(),
4519                                                                  par, par->Last() - 1));
4520                         pain.line(0, y_offset + y_bottom,
4521                                   ww, y_offset + y_bottom,
4522                                   LColor::topline, Painter::line_solid,
4523                                   Painter::line_thick);
4524                         y_bottom -= lyxfont::ascent('x', GetFont(bview->buffer(),
4525                                                                  par, par->Last() - 1));
4526                 }
4527
4528                 // draw an endlabel
4529                 int endlabel = row_ptr->par()->GetEndLabel(bview->buffer()->params);
4530                 switch (endlabel) {
4531                 case END_LABEL_BOX:
4532                 case END_LABEL_FILLED_BOX:
4533                 {
4534                         LyXFont font = GetFont(bview->buffer(),
4535                                                row_ptr->par(), last);
4536                         int size = int(0.75 * lyxfont::maxAscent(font));
4537                         int y = (y_offset + row_ptr->baseline()) - size;
4538                         int x = is_rtl ? LYX_PAPER_MARGIN 
4539                                 : ww - LYX_PAPER_MARGIN - size;
4540 #ifndef NEW_INSETS
4541                         if (row_ptr->par()->footnoteflag == LyXParagraph::OPEN_FOOTNOTE)
4542                                 if (is_rtl) {
4543                                         LyXFont font(LyXFont::ALL_SANE);
4544                                         font.setSize(LyXFont::SIZE_SMALL);
4545                                         x += lyxfont::width("Mwide-figM", font);
4546                                 } else
4547                                         x -= LYX_PAPER_MARGIN/2;
4548 #endif
4549                         if (row_ptr->fill() <= size)
4550                                 x += (size - row_ptr->fill() + 1) * (is_rtl ? -1 : 1);
4551                         if (endlabel == END_LABEL_BOX) {
4552                                 pain.line(x, y, x, y + size,
4553                                           LColor::eolmarker);
4554                                 pain.line(x + size, y, x + size , y + size,
4555                                           LColor::eolmarker);
4556                                 pain.line(x, y, x + size, y,
4557                                           LColor::eolmarker);
4558                                 pain.line(x, y + size, x + size, y + size,
4559                                           LColor::eolmarker);
4560                         } else
4561                                 pain.fillRectangle(x, y, size, size,
4562                                                    LColor::eolmarker);
4563                         break;
4564                 }
4565                 case END_LABEL_STATIC:
4566                 {
4567                         LyXTextClass::LayoutList::size_type layout = row_ptr->par()->GetLayout();
4568                         string tmpstring = textclasslist.Style(bview->buffer()->params.textclass,
4569                                                          layout).endlabelstring();
4570                         font = GetFont(bview->buffer(), row_ptr->par(), -2);
4571                         int tmpx = is_rtl ? int(x) - lyxfont::width(tmpstring, font)
4572                                 : ww - RightMargin(bview->buffer(), row_ptr) - row_ptr->fill();
4573                         pain.text( tmpx, y_offset + row_ptr->baseline(), tmpstring, font);
4574                         break;
4575                 }
4576                 case END_LABEL_NO_LABEL:
4577                         break;
4578                 }
4579         }
4580         
4581         /* draw the text in the pixmap */  
4582         
4583         vpos = row_ptr->pos();
4584 #ifndef NEW_TABULAR
4585         /* table stuff -- begin*/
4586         if (row_ptr->par()->table) {
4587                 bool on_off;
4588                 int cell = NumberOfCell(row_ptr->par(), row_ptr->pos());
4589                 float x_old = x;
4590                 x += row_ptr->par()->table->GetBeginningOfTextInCell(cell);
4591                 
4592                 while (vpos <= last)  {
4593                         pos = vis2log(vpos);
4594                         if (row_ptr->par()->IsNewline(pos)) {
4595                                 
4596                                 x = x_old + row_ptr->par()->table->WidthOfColumn(cell);
4597                                 /* draw the table lines, still very simple */
4598                                 on_off = !row_ptr->par()->table->TopLine(cell);
4599                                 if ((!on_off ||
4600                                      !row_ptr->par()->table->TopAlreadyDrawed(cell)) &&
4601                                     !row_ptr->par()->table->IsContRow(cell))
4602                                         pain.line(int(x_old),
4603                                                   y_offset + row_ptr->baseline() - row_ptr->ascent_of_text(),
4604                                                   int(x),
4605                                                   y_offset + row_ptr->baseline() - row_ptr->ascent_of_text(),
4606                                                   LColor::tableline,
4607                                                   on_off ? Painter::line_onoffdash : Painter::line_solid);
4608                                 
4609                                 on_off = !row_ptr->par()->table->BottomLine(cell);
4610                                 if ((!on_off && !row_ptr->par()->table->RowHasContRow(cell)) ||
4611                                     row_ptr->par()->table->VeryLastRow(cell))
4612                                         
4613                                         pain.line(int(x_old),
4614                                                   y_offset + y_bottom - 1,
4615                                                   int(x),
4616                                                   y_offset + y_bottom - 1,
4617                                                   LColor::tableline,
4618                                                   on_off ? Painter::line_onoffdash : Painter::line_solid);
4619                                 
4620                                 on_off = !row_ptr->par()->table->LeftLine(cell);
4621                                 
4622                                 pain.line(int(x_old),
4623                                           y_offset + row_ptr->baseline() - row_ptr->ascent_of_text(),
4624                                           int(x_old),
4625                                           y_offset + y_bottom - 1,
4626                                           LColor::tableline,
4627                                           on_off ? Painter::line_onoffdash : Painter::line_solid);
4628                                 
4629                                 on_off = !row_ptr->par()->table->RightLine(cell);
4630                                 
4631                                 pain.line(int(x) - row_ptr->par()->table->AdditionalWidth(cell),
4632                                           y_offset + row_ptr->baseline() - row_ptr->ascent_of_text(),
4633                                           int(x) - row_ptr->par()->table->AdditionalWidth(cell),
4634                                           y_offset + y_bottom - 1,
4635                                           LColor::tableline,
4636                                           on_off ? Painter::line_onoffdash : Painter::line_solid);
4637                                 
4638                                 x_old = x;
4639                                 /* take care about the alignment and other spaces */
4640                                 ++cell;
4641                                 x += row_ptr->par()->table->GetBeginningOfTextInCell(cell);
4642                                 if (row_ptr->par()->table->IsFirstCell(cell))
4643                                         --cell; // little hack, sorry
4644                                 ++vpos;
4645                         } else if (row_ptr->par()->IsHfill(pos)) {
4646                                 x += 1;
4647                                 
4648                                 pain.line(int(x),
4649                                           y_offset + row_ptr->baseline() - DefaultHeight() / 2,
4650                                           int(x),
4651                                           y_offset + row_ptr->baseline(),
4652                                           LColor::vfillline);
4653                                 
4654                                 x += 2;
4655                                 ++vpos;
4656                         } else if (row_ptr->par()->IsSeparator(pos)) {
4657                                 tmpx = x;
4658                                 x+= SingleWidth(bview, 
4659                                                 row_ptr->par(), pos);
4660                                 ++vpos;
4661                         } else
4662                                 draw(bview, row_ptr, vpos, y_offset, x, clear_area);
4663                 }
4664                 
4665                 /* do not forget the very last cell. This has no NEWLINE so 
4666                  * ignored by the code above*/ 
4667                 if (cell == row_ptr->par()->table->GetNumberOfCells() - 1) {
4668                         x = x_old + row_ptr->par()->table->WidthOfColumn(cell);
4669                         on_off = !row_ptr->par()->table->TopLine(cell);
4670                         if ((!on_off ||
4671                              !row_ptr->par()->table->TopAlreadyDrawed(cell)) &&
4672                             !row_ptr->par()->table->IsContRow(cell))
4673                                 
4674                                 pain.line(int(x_old),
4675                                           y_offset + row_ptr->baseline() - row_ptr->ascent_of_text(),
4676                                           int(x),
4677                                           y_offset + row_ptr->baseline() - row_ptr->ascent_of_text(),
4678                                           LColor::tableline,
4679                                           on_off ? Painter::line_onoffdash : Painter::line_solid);
4680                         on_off = !row_ptr->par()->table->BottomLine(cell);
4681                         if ((!on_off && !row_ptr->par()->table->RowHasContRow(cell)) ||
4682                             row_ptr->par()->table->VeryLastRow(cell))
4683                                 
4684                                 pain.line(int(x_old),
4685                                           y_offset + y_bottom - 1,
4686                                           int(x),
4687                                           y_offset + y_bottom - 1,
4688                                           LColor::tableline,
4689                                           on_off ? Painter::line_onoffdash : Painter::line_solid);
4690                         
4691                         on_off = !row_ptr->par()->table->LeftLine(cell);
4692                         
4693                         pain.line(int(x_old),
4694                                   y_offset + row_ptr->baseline() - row_ptr->ascent_of_text(),
4695                                   int(x_old),
4696                                   y_offset + y_bottom - 1,
4697                                   LColor::tableline,
4698                                   on_off ? Painter::line_onoffdash : Painter::line_solid);
4699                         
4700                         on_off = !row_ptr->par()->table->RightLine(cell);
4701                         
4702                         pain.line(int(x) - row_ptr->par()->table->AdditionalWidth(cell),
4703                                   y_offset + row_ptr->baseline() - row_ptr->ascent_of_text(),
4704                                   int(x) - row_ptr->par()->table->AdditionalWidth(cell),
4705                                   y_offset + y_bottom - 1,
4706                                   LColor::tableline,
4707                                   on_off ? Painter::line_onoffdash : Painter::line_solid);
4708                 }
4709         } else {
4710                 /* table stuff -- end*/
4711 #endif
4712                 LyXParagraph::size_type main_body = 
4713                         BeginningOfMainBody(bview->buffer(), row_ptr->par());
4714                 if (main_body > 0 &&
4715                     (main_body-1 > last || 
4716                      !row_ptr->par()->IsLineSeparator(main_body - 1)))
4717                         main_body = 0;
4718                 
4719                 while (vpos <= last)  {
4720                         pos = vis2log(vpos);
4721                         if (main_body > 0 && pos == main_body - 1) {
4722                                 x += fill_label_hfill
4723                                         + lyxfont::width(layout.labelsep,
4724                                                          GetFont(bview->buffer(),
4725                                                                  row_ptr->par(), -2))
4726                                         - SingleWidth(bview,
4727                                                       row_ptr->par(),
4728                                                       main_body - 1);
4729                         }
4730                         
4731                         if (row_ptr->par() ->IsHfill(pos)) {
4732                                 x += 1;
4733                                 pain.line(int(x),
4734                                           y_offset + row_ptr->baseline() - DefaultHeight() / 2,
4735                                           int(x),
4736                                           y_offset + row_ptr->baseline(),
4737                                           LColor::vfillline);
4738                                 
4739                                 if (HfillExpansion(bview->buffer(),
4740                                                    row_ptr, pos)) {
4741                                         if (pos >= main_body) {
4742                                                 pain.line(int(x),
4743                                                           y_offset + row_ptr->baseline() - DefaultHeight() / 4,
4744                                                           int(x + fill_hfill),
4745                                                           y_offset + row_ptr->baseline() - DefaultHeight() / 4,
4746                                                           LColor::vfillline,
4747                                                           Painter::line_onoffdash);
4748                                                 x += fill_hfill;
4749                                         } else {
4750                                                 pain.line(int(x),
4751                                                           y_offset + row_ptr->baseline() - DefaultHeight() / 4,
4752                                                           int(x + fill_label_hfill),
4753                                                           y_offset + row_ptr->baseline() - DefaultHeight() / 4,
4754                                                           LColor::vfillline,
4755                                                           Painter::line_onoffdash);
4756                                                 
4757                                                 x += fill_label_hfill;
4758                                         }
4759                                         pain.line(int(x),
4760                                                   y_offset + row_ptr->baseline() - DefaultHeight() / 2,
4761                                                   int(x),
4762                                                   y_offset + row_ptr->baseline(),
4763                                                   LColor::vfillline);
4764                                 }
4765                                 x += 2;
4766                                 ++vpos;
4767                         } else if (row_ptr->par()->IsSeparator(pos)) {
4768                                 x += SingleWidth(bview,
4769                                                  row_ptr->par(), pos);
4770                                 if (pos >= main_body)
4771                                         x += fill_separator;
4772                                 ++vpos;
4773                         } else
4774                                 draw(bview, row_ptr, vpos, y_offset, x, clear_area);
4775                 }
4776 #ifndef NEW_TABULAR
4777         }
4778 #endif
4779 }
4780
4781
4782 int LyXText::DefaultHeight() const
4783 {
4784         LyXFont font(LyXFont::ALL_SANE);
4785         return int(lyxfont::maxAscent(font) + lyxfont::maxDescent(font) * 1.5);
4786 }
4787
4788    
4789 /* returns the column near the specified x-coordinate of the row 
4790 * x is set to the real beginning of this column  */ 
4791 int LyXText::GetColumnNearX(BufferView * bview, Row * row, int & x,
4792                             bool & boundary) const
4793 {
4794         float tmpx = 0.0;
4795         float fill_separator, fill_hfill, fill_label_hfill;
4796    
4797         PrepareToPrint(bview, row, tmpx, fill_separator,
4798                        fill_hfill, fill_label_hfill);
4799
4800         LyXParagraph::size_type vc = row->pos();
4801         LyXParagraph::size_type last = RowLastPrintable(row);
4802         LyXParagraph::size_type c = 0;
4803         LyXLayout const & layout =
4804                 textclasslist.Style(bview->buffer()->params.textclass,
4805                                     row->par()->GetLayout());
4806         bool left_side = false;
4807
4808 #ifndef NEW_TABULAR
4809         /* table stuff -- begin */
4810         if (row->par()->table) {
4811                 //the last row doesn't need a newline at the end
4812                 if (row->next() && row->next()->par() == row->par()
4813                     && row->par()->IsNewline(last))
4814                         --last;
4815                 int cell = NumberOfCell(row->par(), row->pos());
4816                 float cell_x = tmpx + row->par()->table->WidthOfColumn(cell);
4817                 tmpx += row->par()->table->GetBeginningOfTextInCell(cell);
4818                 float last_tmpx = tmpx;
4819                 while (vc <= last && tmpx <= x) {
4820                        c = vis2log(vc);
4821                        last_tmpx = tmpx;
4822                        if (row->par()->IsNewline(c)) {
4823                                if (cell_x <= x){
4824                                        ++cell;
4825                                        tmpx = cell_x + row->par()->table->GetBeginningOfTextInCell(cell);
4826                                        cell_x += row->par()->table->WidthOfColumn(cell);
4827                                        ++vc;
4828                                } else
4829                                        break;
4830                        } else {
4831                                tmpx += SingleWidth(bview, row->par(), c);
4832                                ++vc;
4833                        }
4834                 }
4835                 if (vc > row->pos() && !row->par()->IsNewline(c) &&
4836                     (tmpx + last_tmpx) / 2 > x) {
4837                         tmpx = last_tmpx;
4838                         left_side = true;
4839                 }
4840         } else {
4841                 /* table stuff -- end*/
4842 #endif
4843                 LyXParagraph::size_type
4844                         main_body = BeginningOfMainBody(bview->buffer(), row->par());
4845                 float last_tmpx = tmpx;
4846
4847                 if (main_body > 0 &&
4848                     (main_body-1 > last || 
4849                      !row->par()->IsLineSeparator(main_body - 1)))
4850                         main_body = 0;
4851
4852                 while (vc <= last && tmpx <= x) {
4853                         c = vis2log(vc);
4854                         last_tmpx = tmpx;
4855                         if (main_body > 0 && c == main_body-1) {
4856                                 tmpx += fill_label_hfill +
4857                                         lyxfont::width(layout.labelsep,
4858                                                GetFont(bview->buffer(), row->par(), -2));
4859                                 if (row->par()->IsLineSeparator(main_body - 1))
4860                                         tmpx -= SingleWidth(bview, row->par(), main_body-1);
4861                         }
4862              
4863                         if (HfillExpansion(bview->buffer(), row, c)) {
4864                                 x += SingleWidth(bview, row->par(), c);
4865                                 if (c >= main_body)
4866                                         tmpx += fill_hfill;
4867                                 else
4868                                         tmpx += fill_label_hfill;
4869                         }
4870                         else if (row->par()->IsSeparator(c)) {
4871                                 tmpx += SingleWidth(bview, row->par(), c);
4872                                 if (c >= main_body)
4873                                         tmpx+= fill_separator;
4874                         } else
4875                                 tmpx += SingleWidth(bview, row->par(), c);
4876                         ++vc;
4877                 }
4878
4879                 if (vc > row->pos() && (tmpx + last_tmpx) / 2 > x) {
4880                         tmpx = last_tmpx;
4881                         left_side = true;
4882                 }
4883 #ifndef NEW_TABULAR
4884         }
4885 #endif
4886
4887         if (vc > last + 1)  // This shouldn't happen.
4888                 vc = last + 1;
4889
4890         boundary = false;
4891 #if 0 // currently unused
4892         bool lastrow = (!row->next() || row->next()->par() != row->par());
4893         bool rtl = (lastrow)
4894                 ? row->par()->isRightToLeftPar(bview->buffer()->params)
4895                 : false;
4896 #endif
4897         
4898         if (row->pos() > last)  // Row is empty?
4899                 c = row->pos();
4900 #warning This is wrong, please have a look Dekel (Jug)
4901 #if 0
4902         else if (lastrow &&
4903                  ( (rtl && vc == row->pos()&& x < tmpx - 5) ||
4904                    (!rtl && vc == last + 1 && x > tmpx + 5) ))
4905                 c = last + 1;
4906 #endif
4907         else if (vc == row->pos()
4908 #ifndef NEW_TABULAR
4909                  || (row->par()->table
4910                   && vc <= last && row->par()->IsNewline(vc-1))
4911 #endif
4912                 ) {
4913                 c = vis2log(vc);
4914                 if (bidi_level(c) % 2 == 1)
4915                         ++c;
4916         } else {
4917                 c = vis2log(vc - 1);
4918                 bool rtl = (bidi_level(c) % 2 == 1);
4919                 if (left_side == rtl) {
4920                         ++c;
4921                         boundary = IsBoundary(bview->buffer(), row->par(), c);
4922                 }
4923         }
4924
4925         if (
4926 #ifndef NEW_TABULAR
4927                 !row->par()->table &&
4928 #endif
4929                 row->pos() <= last && c > last
4930                 && row->par()->IsNewline(last)) {
4931                 if (bidi_level(last) % 2 == 0)
4932                         tmpx -= SingleWidth(bview, row->par(), last);
4933                 else
4934                         tmpx += SingleWidth(bview, row->par(), last);
4935                 c = last;
4936         }
4937
4938         c -= row->pos();
4939         x = int(tmpx);
4940         return c;
4941 }
4942
4943
4944 #ifndef NEW_INSETS
4945 /* turn the selection into a new environment. If there is no selection,
4946 * create an empty environment */ 
4947 void LyXText::InsertFootnoteEnvironment(BufferView * bview, 
4948                                         LyXParagraph::footnote_kind kind)
4949 {
4950    /* no footnoteenvironment in a footnoteenvironment */ 
4951    if (cursor.par()->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
4952       WriteAlert(_("Impossible operation"), 
4953                  _("You can't insert a float in a float!"), 
4954                  _("Sorry."));
4955      return;
4956    }
4957    /* no marginpars in minipages */
4958    if (kind == LyXParagraph::MARGIN 
4959       && cursor.par()->pextra_type == LyXParagraph::PEXTRA_MINIPAGE) {
4960       WriteAlert(_("Impossible operation"), 
4961                  _("You can't insert a marginpar in a minipage!"), 
4962                  _("Sorry."));
4963       return;
4964    }
4965    
4966    /* this doesnt make sense, if there is no selection */ 
4967    bool dummy_selection = false;
4968    if (!selection) {
4969       sel_start_cursor = cursor;       /* dummy selection  */
4970       sel_end_cursor = cursor;
4971       dummy_selection = true;
4972    }
4973    
4974    LyXParagraph * tmppar;
4975
4976 #ifndef NEW_TABULAR
4977    if (sel_start_cursor.par()->table || sel_end_cursor.par()->table){
4978       WriteAlert(_("Impossible operation"), _("Cannot cut table."), _("Sorry."));
4979       return;
4980    }
4981 #endif
4982    /* a test to make sure there is not already a footnote
4983     * in the selection. */
4984    
4985    tmppar = sel_start_cursor.par()->ParFromPos(sel_start_cursor.pos());
4986    
4987    while (tmppar != sel_end_cursor.par()->ParFromPos(sel_end_cursor.pos()) && 
4988           tmppar->footnoteflag == LyXParagraph::NO_FOOTNOTE)
4989      tmppar = tmppar->next;
4990    
4991    if (tmppar != sel_end_cursor.par()->ParFromPos(sel_end_cursor.pos())
4992        || tmppar->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
4993       WriteAlert(_("Impossible operation"), 
4994                  _("Float would include float!"), 
4995                  _("Sorry."));
4996       return;
4997    }
4998    
4999    /* ok we have a selection. This is always between sel_start_cursor
5000     * and sel_end cursor */
5001
5002    SetUndo(bview->buffer(), Undo::FINISH, 
5003            sel_start_cursor.par()->ParFromPos(sel_start_cursor.pos())->previous, 
5004            sel_end_cursor.par()->ParFromPos(sel_end_cursor.pos())->next); 
5005    
5006    if (sel_end_cursor.pos() > 0 
5007        && sel_end_cursor.par()->IsLineSeparator(sel_end_cursor.pos() - 1))
5008            sel_end_cursor.pos(sel_end_cursor.pos() - 1);
5009    /* please break before a space at the end */
5010    if (sel_start_cursor.par() == sel_end_cursor.par()
5011        && sel_start_cursor.pos() > sel_end_cursor.pos())
5012            sel_start_cursor.pos(sel_start_cursor.pos() - 1);
5013
5014    sel_end_cursor.par()->BreakParagraphConservative(bview->buffer()->params, sel_end_cursor.pos());
5015    
5016    sel_end_cursor.par(sel_end_cursor.par()->Next());
5017    sel_end_cursor.pos(0);
5018    
5019    // don't forget to insert a dummy layout paragraph if necessary
5020    if (sel_start_cursor.par()->GetLayout() != sel_end_cursor.par()->layout){
5021      sel_end_cursor.par()->BreakParagraphConservative(bview->buffer()->params, 0);
5022      sel_end_cursor.par()->layout = LYX_DUMMY_LAYOUT;
5023      sel_end_cursor.par(sel_end_cursor.par()->next);
5024    }
5025    else
5026      sel_end_cursor.par()->layout = LYX_DUMMY_LAYOUT;
5027
5028    cursor = sel_end_cursor;
5029
5030    /* please break behind a space, if there is one. The space should
5031     * be erased too */ 
5032    if (sel_start_cursor.pos() > 0 
5033        && sel_start_cursor.par()->IsLineSeparator(sel_start_cursor.pos() - 1))
5034      sel_start_cursor.pos(sel_start_cursor.pos() - 1);
5035    if (sel_start_cursor.par()->IsLineSeparator(sel_start_cursor.pos())) {
5036       sel_start_cursor.par()->Erase(sel_start_cursor.pos());
5037    }
5038    
5039    sel_start_cursor.par()->BreakParagraphConservative(bview->buffer()->params,
5040                                                     sel_start_cursor.pos());
5041    tmppar = sel_start_cursor.par()->Next();
5042    
5043    if (dummy_selection) {
5044            tmppar->Clear();
5045            if (kind == LyXParagraph::TAB
5046                || kind == LyXParagraph::FIG 
5047                || kind == LyXParagraph::WIDE_TAB
5048                || kind == LyXParagraph::WIDE_FIG 
5049                || kind == LyXParagraph::ALGORITHM) {
5050                    pair<bool, LyXTextClass::size_type> lres =
5051                            textclasslist.NumberOfLayout(bview->buffer()->params.textclass,
5052                                                         "Caption");
5053                    LyXTextClass::size_type lay;
5054                    if (lres.first) {
5055                            // layout fount
5056                            lay = lres.second;
5057                    } else {
5058                            // layout not found
5059                            lay = 0; // use default layout "Standard" (0)
5060                    }
5061                    tmppar->SetLayout(bview->buffer()->params, lay);
5062            }
5063    } else {
5064      if (sel_start_cursor.pos() > 0) {
5065        /* the footnote-environment should begin with a standard layout.
5066         * Imagine you insert a footnote within an enumeration, you 
5067         * certainly do not want an enumerated footnote! */ 
5068        tmppar->Clear();
5069      } else {
5070        /* this is a exception the user would sometimes expect, I hope */
5071        sel_start_cursor.par()->Clear();
5072      }
5073    }
5074    
5075    while (tmppar != sel_end_cursor.par()) {
5076       tmppar->footnoteflag = LyXParagraph::OPEN_FOOTNOTE;
5077       tmppar->footnotekind = kind;
5078       tmppar = tmppar->Next();
5079    }
5080
5081    RedoParagraphs(bview, sel_start_cursor, sel_end_cursor.par()->Next());
5082    
5083    SetCursor(bview, sel_start_cursor.par()->Next(), 0);
5084
5085    ClearSelection();
5086 }
5087 #endif
5088
5089
5090 // returns pointer to a specified row
5091 Row * LyXText::GetRow(LyXParagraph * par,
5092                       LyXParagraph::size_type pos, long & y) const
5093 {
5094         Row * tmprow = firstrow;
5095         y = 0;
5096         
5097         // find the first row of the specified paragraph
5098         while (tmprow->next() && tmprow->par() != par) {
5099                 y += tmprow->height();
5100                 tmprow = tmprow->next();
5101         }
5102         
5103         // now find the wanted row
5104         while (tmprow->pos() < pos
5105                && tmprow->next()
5106                && tmprow->next()->par() == par
5107                && tmprow->next()->pos() <= pos) {
5108                 y += tmprow->height();
5109                 tmprow = tmprow->next();
5110         }
5111         
5112         return tmprow;
5113 }