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