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