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