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