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