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