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