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