]> git.lyx.org Git - lyx.git/blob - src/text.C
Dekel's depth bars and assorted fixlets
[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    // CHECK 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                 //CHECK 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         // CHECK There is a bug here! (Asger)
2529         
2530         LyXFont realtmpfont = real_current_font;
2531         LyXFont rawtmpfont = current_font;  /* store the current font.
2532                                      * This is because of the use
2533                                      * of cursor movements. The moving
2534                                      * cursor would refresh the 
2535                                      * current font */
2536
2537         // Get the font that is used to calculate the baselineskip
2538         LyXParagraph::size_type lastpos = cursor.par->Last();
2539         LyXFont rawparfont = cursor.par->GetFontSettings(lastpos - 1);
2540
2541         bool jumped_over_space = false;
2542    
2543         if (!freeSpacing && IsLineSeparatorChar(c)) {
2544                 if ((cursor.pos > 0 
2545                      && cursor.par->IsLineSeparator(cursor.pos - 1))
2546                     || (cursor.pos > 0
2547                         && cursor.par->IsNewline(cursor.pos - 1))
2548                     || (cursor.pos == 0
2549                         && !(cursor.par->Previous()
2550                              && cursor.par->Previous()->footnoteflag
2551                              == LyXParagraph::OPEN_FOOTNOTE))) {
2552                         if (cursor.pos == 0 )
2553                                 owner_->owner()->getMiniBuffer()->Set(_("You cannot insert a space at the beginning of a paragraph.  Please read the Tutorial."));
2554                         else
2555                                 owner_->owner()->getMiniBuffer()->Set(_("You cannot type two spaces this way.  Please read the Tutorial."));
2556                         charInserted();
2557                         return;
2558                 }
2559         } else if (IsNewlineChar(c)) {
2560                 if (cursor.par->FirstPhysicalPar() == cursor.par
2561                     && cursor.pos <= BeginningOfMainBody(cursor.par)) {
2562                         charInserted();
2563                         return;
2564                 }
2565                 /* No newline at first position 
2566                  * of a paragraph or behind labels. 
2567                  * TeX does not allow that. */
2568                 
2569                 if (cursor.pos < cursor.par->Last() &&
2570                     cursor.par->IsLineSeparator(cursor.pos))
2571                         CursorRightIntern(); // newline always after a blank!
2572                 cursor.row->fill = -1;         // to force a new break
2573         }
2574    
2575         // the display inset stuff
2576         if (cursor.row->par->GetChar(cursor.row->pos) == LyXParagraph::META_INSET
2577             && cursor.row->par->GetInset(cursor.row->pos)
2578             && cursor.row->par->GetInset(cursor.row->pos)->display())
2579                 cursor.row->fill = -1; // to force a new break  
2580
2581         // get the cursor row fist
2582         Row * row = cursor.row;
2583         long y = cursor.y - row->baseline;
2584         if (c != LyXParagraph::META_INSET) /* Here case LyXText::InsertInset 
2585                                             * already insertet the character */
2586                 cursor.par->InsertChar(cursor.pos, c);
2587         SetCharFont(cursor.par, cursor.pos, rawtmpfont);
2588
2589         if (!jumped_over_space) {
2590                 // refresh the positions
2591                 Row * tmprow = row;
2592                 while (tmprow->next && tmprow->next->par == row->par) {
2593                         tmprow = tmprow->next;
2594                         tmprow->pos++;
2595                 }
2596         }
2597    
2598         // Is there a break one row above
2599         if ((cursor.par->IsLineSeparator(cursor.pos)
2600              || cursor.par->IsNewline(cursor.pos)
2601              || cursor.row->fill == -1)
2602             && row->previous && row->previous->par == row->par) {
2603                 LyXParagraph::size_type z = NextBreakPoint(row->previous,
2604                                                            paperwidth);
2605                 if ( z >= row->pos) {
2606                         row->pos = z + 1;
2607                         
2608                         // set the dimensions of the row above
2609                         row->previous->fill = Fill(row->previous, paperwidth);
2610
2611                         SetHeightOfRow(row->previous);
2612              
2613                         y -= row->previous->height;
2614                         refresh_y = y;
2615                         refresh_row = row->previous;
2616                         status = LyXText::NEED_MORE_REFRESH;
2617              
2618                         BreakAgainOneRow(row);
2619
2620                         current_font = rawtmpfont;
2621                         real_current_font = realtmpfont;
2622                         SetCursor(cursor.par, cursor.pos + 1, false);
2623                         /* cursor MUST be in row now */
2624              
2625                         if (row->next && row->next->par == row->par)
2626                                 need_break_row = row->next;
2627                         else
2628                                 need_break_row = 0;
2629              
2630                         // check, wether the last characters font has changed. 
2631                         if (cursor.pos && cursor.pos == cursor.par->Last()
2632                             && rawparfont != rawtmpfont)
2633                                 RedoHeightOfParagraph(cursor);
2634                         
2635                         charInserted();
2636                         return;
2637                 }
2638         }
2639    
2640         /* recalculate the fill of the row */ 
2641         if (row->fill >= 0)  /* needed because a newline
2642                               * will set fill to -1. Otherwise
2643                               * we would not get a rebreak! */
2644                 row->fill = Fill(row, paperwidth);
2645         if (row->fill < 0 ) {
2646                 refresh_y = y;
2647                 refresh_row = row; 
2648                 refresh_x = cursor.x;
2649                 refresh_pos = cursor.pos;
2650                 status = LyXText::NEED_MORE_REFRESH;
2651                 BreakAgainOneRow(row); 
2652                 /* will the cursor be in another row now? */ 
2653                 if (RowLast(row) <= cursor.pos + 1 && row->next) {
2654                         if (row->next && row->next->par == row->par)
2655                                 /* this should
2656                                  * always be true */
2657                                 row = row->next;
2658                         BreakAgainOneRow(row);
2659                 }
2660                 current_font = rawtmpfont;
2661                 real_current_font = realtmpfont;
2662                 SetCursor(cursor.par, cursor.pos + 1, false);
2663                 if (row->next && row->next->par == row->par)
2664                         need_break_row = row->next;
2665                 else
2666                         need_break_row = 0;             
2667         } else {
2668                 refresh_y = y;
2669                 refresh_x = cursor.x;
2670                 refresh_row = row;
2671                 refresh_pos = cursor.pos;
2672                 
2673                 int tmpheight = row->height;
2674                 SetHeightOfRow(row);
2675                 if (tmpheight == row->height)
2676                         status = LyXText::NEED_VERY_LITTLE_REFRESH;
2677                 else
2678                         status = LyXText::NEED_MORE_REFRESH;
2679             
2680                 current_font = rawtmpfont;
2681                 real_current_font = realtmpfont;
2682                 SetCursor(cursor.par, cursor.pos + 1, false);
2683         }
2684
2685         /* check, wether the last characters font has changed. */ 
2686         if (cursor.pos && cursor.pos == cursor.par->Last()
2687             && rawparfont != rawtmpfont) {
2688                 RedoHeightOfParagraph(cursor);
2689         } else {
2690                 /* now the special right address boxes */
2691                 if (textclasslist.Style(buffer->params.textclass,
2692                                    cursor.par->GetLayout()).margintype
2693                     == MARGIN_RIGHT_ADDRESS_BOX) {
2694                         RedoDrawingOfParagraph(cursor); 
2695                 }
2696         }
2697
2698         charInserted();
2699 }
2700    
2701
2702 void LyXText::charInserted()
2703 {
2704         // Here we could call FinishUndo for every 20 characters inserted.
2705         // This is from my experience how emacs does it.
2706         static unsigned int counter = 0;
2707         if (counter < 20) {
2708                 ++counter;
2709         } else {
2710                 FinishUndo();
2711                 counter = 0;
2712         }
2713 }
2714
2715 void LyXText::PrepareToPrint(Row * row, float & x,
2716                              float & fill_separator, 
2717                              float & fill_hfill,
2718                              float & fill_label_hfill,
2719                              bool bidi) const
2720 {
2721         float nh, nlh, ns;
2722         
2723         float w = row->fill;
2724         fill_hfill = 0;
2725         fill_label_hfill = 0;
2726         fill_separator = 0;
2727         fill_label_hfill = 0;
2728
2729         bool is_rtl = row->par->isRightToLeftPar();
2730
2731         if (is_rtl) {
2732                 x = RightMargin(row);
2733                 if (row->par->footnoteflag == LyXParagraph::OPEN_FOOTNOTE) {
2734                         LyXFont font(LyXFont::ALL_SANE);
2735                         font.setSize(LyXFont::SIZE_SMALL);
2736                         x += lyxfont::width("Mwide-figM", font);
2737                 }
2738         } else
2739                 x = LeftMargin(row);
2740         
2741         /* is there a manual margin with a manual label */ 
2742         if (textclasslist.Style(buffer->params.textclass,
2743                            row->par->GetLayout()).margintype == MARGIN_MANUAL
2744             && textclasslist.Style(buffer->params.textclass,
2745                               row->par->GetLayout()).labeltype == LABEL_MANUAL) {
2746                
2747                 nlh = NumberOfLabelHfills(row) + 1; /* one more since labels 
2748                                                     * are left aligned*/ 
2749                 if (nlh && !row->par->GetLabelWidthString().empty()) {
2750                         fill_label_hfill = LabelFill(row) / nlh;
2751                 }
2752         }
2753                 
2754         /* are there any hfills in the row? */ 
2755         nh = NumberOfHfills(row);
2756         
2757 /* table stuff -- begin*/
2758         if (row->par->table) {
2759            w = paperwidth - row->par->table->WidthOfTable()
2760            - x - RightMargin(row);
2761            nh = 0; /* ignore hfills in tables */ 
2762         }
2763 /* table stuff -- end*/
2764
2765         if (nh)
2766           fill_hfill = w /nh;
2767         else  {
2768            /* is it block, flushleft or flushright? 
2769             * set x how you need it */
2770         int align;
2771         if (row->par->FirstPhysicalPar()->align == LYX_ALIGN_LAYOUT)
2772           align = textclasslist.Style(buffer->params.textclass, row->par->GetLayout()).align;
2773         else
2774           align = row->par->FirstPhysicalPar()->align;
2775            
2776            /* center displayed insets */ 
2777            if (row->par->GetChar(row->pos) == LyXParagraph::META_INSET
2778                && row->par->GetInset(row->pos)
2779                && row->par->GetInset(row->pos)->display())
2780              align = LYX_ALIGN_CENTER;
2781
2782            switch (align) {
2783             case LYX_ALIGN_BLOCK:
2784               ns = NumberOfSeparators(row);
2785               if (ns && row->next && row->next->par == row->par &&
2786                   !(row->next->par->IsNewline(row->next->pos-1))
2787                   && !(row->next->par->GetChar(row->next->pos) == LyXParagraph::META_INSET
2788                        && row->next->par->GetInset(row->next->pos)
2789                        && row->next->par->GetInset(row->next->pos)->display())
2790                   )
2791                 fill_separator = w / ns;
2792               else if (is_rtl)
2793                 x += w;
2794               break;
2795             case LYX_ALIGN_RIGHT:
2796               x += w;
2797               break;
2798             case LYX_ALIGN_CENTER:
2799               x += w / 2;
2800               break;
2801            }
2802         }
2803         if (!bidi)
2804                 return;
2805
2806         ComputeBidiTables(row);
2807         if (is_rtl) {
2808                 LyXParagraph::size_type main_body = 
2809                         BeginningOfMainBody(row->par);
2810                 LyXParagraph::size_type last = RowLast(row);
2811
2812                 if (main_body > 0 &&
2813                     (main_body-1 > last || 
2814                      !row->par->IsLineSeparator(main_body-1))) {
2815                         LyXLayout const & layout = textclasslist.Style(buffer->params.textclass,
2816                                                                        row->par->GetLayout());
2817                         x += lyxfont::width(layout.labelsep,
2818                                             GetFont(row->par, -2));
2819                         if (main_body-1 <= last)
2820                                 x += fill_label_hfill;
2821                 }
2822         }
2823 }
2824       
2825 /* important for the screen */
2826
2827
2828 /* the cursor set functions have a special mechanism. When they
2829 * realize, that you left an empty paragraph, they will delete it.
2830 * They also delete the corresponding row */
2831
2832 void LyXText::CursorRightOneWord() const
2833 {
2834         // treat floats, HFills and Insets as words
2835         LyXCursor tmpcursor = cursor;
2836         // CHECK See comment on top of text.C
2837
2838         if (tmpcursor.pos == tmpcursor.par->Last()
2839             && tmpcursor.par->Next())
2840         {
2841                         tmpcursor.par = tmpcursor.par->Next();
2842                         tmpcursor.pos = 0;
2843         } else {
2844                 int steps = 0;
2845
2846                 // Skip through initial nonword stuff.
2847                 while ( tmpcursor.pos < tmpcursor.par->Last() &&
2848                         ! tmpcursor.par->IsWord( tmpcursor.pos ) ) 
2849                 {
2850                   //    printf("Current pos1 %d", tmpcursor.pos) ;
2851                         tmpcursor.pos++;
2852                         ++steps;
2853                 }
2854                 // Advance through word.
2855                 while ( tmpcursor.pos < tmpcursor.par->Last() &&
2856                         tmpcursor.par->IsWord( tmpcursor.pos ) )
2857                 {
2858                   //     printf("Current pos2 %d", tmpcursor.pos) ;
2859                         tmpcursor.pos++;
2860                         ++steps;
2861                 }
2862         }
2863         SetCursor(tmpcursor.par, tmpcursor.pos);
2864 }
2865
2866
2867 void LyXText::CursorTab() const
2868 {
2869     if (cursor.par->table) {
2870         int cell = NumberOfCell(cursor.par, cursor.pos);
2871         while(cursor.par->table->IsContRow(cell)) {
2872             CursorUp();
2873             cell = NumberOfCell(cursor.par, cursor.pos);
2874         }
2875         if (cursor.par->table->ShouldBeVeryLastCell(cell))
2876             TableFeatures(LyXTable::APPEND_ROW);
2877     }
2878     LyXCursor tmpcursor = cursor;
2879     while (tmpcursor.pos < tmpcursor.par->Last()
2880            && !tmpcursor.par->IsNewline(tmpcursor.pos))
2881         tmpcursor.pos++;
2882    
2883     if (tmpcursor.pos == tmpcursor.par->Last()){
2884         if (tmpcursor.par->Next()) {
2885             tmpcursor.par = tmpcursor.par->Next();
2886             tmpcursor.pos = 0;
2887         }
2888     }
2889     else
2890         tmpcursor.pos++;
2891     SetCursor(tmpcursor.par, tmpcursor.pos);
2892     if (cursor.par->table) {
2893         int cell = NumberOfCell(cursor.par, cursor.pos);
2894         while (cursor.par->table->IsContRow(cell) &&
2895                !cursor.par->table->ShouldBeVeryLastCell(cell)) {
2896             tmpcursor = cursor;
2897             while (tmpcursor.pos < tmpcursor.par->Last()
2898                    && !tmpcursor.par->IsNewline(tmpcursor.pos))
2899                 tmpcursor.pos++;
2900    
2901             if (tmpcursor.pos == tmpcursor.par->Last()){
2902                 if (tmpcursor.par->Next()) {
2903                     tmpcursor.par = tmpcursor.par->Next();
2904                     tmpcursor.pos = 0;
2905                 }
2906             }
2907             else
2908                 tmpcursor.pos++;
2909             SetCursor(tmpcursor.par, tmpcursor.pos);
2910             cell = NumberOfCell(cursor.par, cursor.pos);
2911         }
2912     }
2913 }
2914
2915
2916 /* -------> Skip initial whitespace at end of word and move cursor to *start*
2917             of prior word, not to end of next prior word. */
2918
2919 void LyXText::CursorLeftOneWord()  const
2920 {
2921         // treat HFills, floats and Insets as words
2922         LyXCursor tmpcursor = cursor;
2923         while (tmpcursor.pos 
2924                && (tmpcursor.par->IsSeparator(tmpcursor.pos - 1) 
2925                    || tmpcursor.par->IsKomma(tmpcursor.pos - 1))
2926                && !(tmpcursor.par->IsHfill(tmpcursor.pos - 1)
2927                     || tmpcursor.par->IsFloat(tmpcursor.pos - 1)
2928                     || tmpcursor.par->IsInset(tmpcursor.pos - 1)))
2929                 tmpcursor.pos--;
2930
2931         if (tmpcursor.pos
2932             && (tmpcursor.par->IsInset(tmpcursor.pos - 1)
2933                 || tmpcursor.par->IsFloat(tmpcursor.pos - 1)
2934                 || tmpcursor.par->IsHfill(tmpcursor.pos - 1))) {
2935                 tmpcursor.pos--;
2936         } else if (!tmpcursor.pos) {
2937                 if (tmpcursor.par->Previous()){
2938                         tmpcursor.par = tmpcursor.par->Previous();
2939                         tmpcursor.pos = tmpcursor.par->Last();
2940                 }
2941         } else {                // Here, tmpcursor != 0 
2942                 while (tmpcursor.pos > 0 &&
2943                        tmpcursor.par->IsWord(tmpcursor.pos-1) )
2944                         tmpcursor.pos-- ;
2945         }
2946         SetCursor(tmpcursor.par, tmpcursor.pos);
2947 }
2948
2949 /* -------> Select current word. This depends on behaviour of CursorLeftOneWord(), so it is
2950                         patched as well. */
2951
2952 void LyXText::SelectWord() 
2953 {
2954         /* Move cursor to the beginning, when not already there. */
2955         if ( cursor.pos
2956              && !cursor.par->IsSeparator(cursor.pos-1)
2957              && !cursor.par->IsKomma(cursor.pos-1) )
2958                 CursorLeftOneWord();
2959
2960         /* set the sel cursor */
2961         sel_cursor = cursor;
2962
2963         while ( cursor.pos < cursor.par->Last()
2964                         && !cursor.par->IsSeparator(cursor.pos)
2965                         && !cursor.par->IsKomma(cursor.pos) )
2966                 cursor.pos++;
2967         SetCursor( cursor.par, cursor.pos );
2968         
2969         /* finally set the selection */ 
2970         SetSelection();
2971 }
2972
2973
2974 /* -------> Select the word currently under the cursor when:
2975                         1: no selection is currently set,
2976                         2: the cursor is not at the borders of the word. */
2977
2978 bool LyXText::SelectWordWhenUnderCursor() 
2979 {
2980         if (!selection &&
2981             cursor.pos > 0 && cursor.pos < cursor.par->Last()
2982             && !cursor.par->IsSeparator(cursor.pos)
2983             && !cursor.par->IsKomma(cursor.pos)
2984             && !cursor.par->IsSeparator(cursor.pos -1)
2985             && !cursor.par->IsKomma(cursor.pos -1) ) {
2986                 SelectWord();
2987                 return true;
2988         }
2989         return false;
2990 }
2991
2992
2993 // This function is only used by the spellchecker for NextWord().
2994 // It doesn't handle LYX_ACCENTs and probably never will.
2995 char * LyXText::SelectNextWord(float & value)
2996 {
2997         LyXParagraph * tmppar = cursor.par;
2998         
2999         // If this is not the very first word, skip rest of
3000         // current word because we are probably in the middle
3001         // of a word if there is text here.
3002         if (cursor.pos || cursor.par->previous) {
3003                 while (cursor.pos < cursor.par->Last()
3004                        && cursor.par->IsLetter(cursor.pos))
3005                         cursor.pos++;
3006         }
3007         // Now, skip until we have real text (will jump paragraphs)
3008         while ((cursor.par->Last() > cursor.pos
3009                 && (!cursor.par->IsLetter(cursor.pos)
3010                     || cursor.par->getFont(cursor.pos).latex() == LyXFont::ON))
3011                || (cursor.par->Last() == cursor.pos
3012                    && cursor.par->Next())){
3013                 if (cursor.pos == cursor.par->Last()) {
3014                         cursor.par = cursor.par->Next();
3015                         cursor.pos = 0;
3016                 }
3017                 else
3018                         cursor.pos++;
3019         }
3020   
3021         // Update the value if we changed paragraphs
3022         if (cursor.par != tmppar){
3023                 SetCursor(cursor.par, cursor.pos);
3024                 value = float(cursor.y)/float(height);
3025         }
3026
3027         /* Start the selection from here */
3028         sel_cursor = cursor;
3029
3030 #ifdef HAVE_SSTREAM
3031         std::ostringstream latex;
3032 #else
3033         ostrstream latex;
3034 #endif
3035         /* and find the end of the word 
3036            (optional hyphens are part of a word) */
3037         while (cursor.pos < cursor.par->Last()
3038                && (cursor.par->IsLetter(cursor.pos)) 
3039                    || (cursor.par->GetChar(cursor.pos) == LyXParagraph::META_INSET
3040                        && cursor.par->GetInset(cursor.pos) != 0
3041                        && cursor.par->GetInset(cursor.pos)->Latex(latex, false, false) == 0
3042 #ifdef HAVE_SSTREAM
3043                        && latex.str() == "\\-"
3044 #else
3045                 && string(latex.str(), 3) == "\\-" // this is not nice at all
3046 #endif
3047                            ))
3048                 cursor.pos++;
3049
3050 #ifndef HAVE_SSTREAM
3051         delete [] latex.str();
3052 #endif
3053         // Finally, we copy the word to a string and return it
3054         char * str = 0;
3055
3056         if (sel_cursor.pos < cursor.pos) {
3057                 str = new char [cursor.pos - sel_cursor.pos + 2];
3058                 LyXParagraph::size_type i, j;
3059                 for (i = sel_cursor.pos, j = 0; i < cursor.pos; ++i) {
3060                         if (cursor.par->GetChar(i) != LyXParagraph::META_INSET)
3061                                 str[j++] = cursor.par->GetChar(i);
3062                 }
3063                 str[j] = '\0';
3064         }
3065         return str;
3066 }
3067
3068
3069 // This one is also only for the spellchecker
3070 void LyXText::SelectSelectedWord()
3071 {
3072         /* move cursor to the beginning */
3073         SetCursor(sel_cursor.par, sel_cursor.pos);
3074         
3075         /* set the sel cursor */
3076         sel_cursor = cursor;
3077
3078 #ifdef HAVE_SSTREAM
3079         std::ostringstream latex;
3080 #else
3081         ostrstream latex;
3082 #endif
3083         
3084         /* now find the end of the word */
3085         while (cursor.pos < cursor.par->Last()
3086                && (cursor.par->IsLetter(cursor.pos)
3087                    || (cursor.par->GetChar(cursor.pos) == LyXParagraph::META_INSET
3088                        && cursor.par->GetInset(cursor.pos) != 0
3089                        && cursor.par->GetInset(cursor.pos)->Latex(latex, false, false) == 0
3090 #ifdef HAVE_SSTREAM
3091                        && latex.str() == "\\-"
3092 #else
3093                        && string(latex.str(), 3) == "\\-"
3094 #endif
3095                            )))
3096                 cursor.pos++;
3097         
3098 #ifndef HAVE_SSTREAM
3099         delete [] latex.str();
3100 #endif
3101         SetCursor(cursor.par, cursor.pos);
3102         
3103         /* finally set the selection */ 
3104         SetSelection();
3105 }
3106
3107
3108 /* -------> Delete from cursor up to the end of the current or next word. */
3109 void LyXText::DeleteWordForward()
3110 {
3111         LyXCursor tmpcursor = cursor;
3112         
3113         if (!cursor.par->Last())
3114                 CursorRight();
3115         // CHECK See comment on top of text.C
3116         else {
3117                 /* -------> Skip initial non-word stuff. */
3118                 while ( cursor.pos < cursor.par->Last() 
3119                         && (cursor.par->IsSeparator(cursor.pos)
3120                             || cursor.par->IsKomma(cursor.pos)) )
3121                         cursor.pos++;
3122                 
3123                 SetCursorIntern(cursor.par, cursor.pos);
3124                 selection = True; // to avoid deletion 
3125                 CursorRightOneWord();
3126                 sel_cursor = cursor;
3127                 cursor = tmpcursor;
3128                 SetSelection(); 
3129                 
3130                 /* -----> Great, CutSelection() gets rid of multiple spaces. */
3131                 CutSelection();
3132         }
3133 }
3134
3135
3136 /* -------> Delete from cursor to start of current or prior word. */
3137 void LyXText::DeleteWordBackward()
3138 {
3139        LyXCursor tmpcursor = cursor;
3140        if (!cursor.par->Last())
3141          CursorLeft();
3142        // CHECK See comment on top of text.C
3143        else{
3144          selection = true; // to avoid deletion 
3145          CursorLeftOneWord();
3146          sel_cursor = cursor;
3147          cursor = tmpcursor;
3148          SetSelection();
3149          CutSelection();
3150        }
3151 }
3152
3153
3154 /* -------> Kill to end of line. */
3155 void LyXText::DeleteLineForward()
3156 {
3157         LyXCursor tmpcursor = cursor;
3158         if (!cursor.par->Last())
3159                 CursorRight();
3160         // CHECK See comment on top of text.C
3161         else {
3162                 CursorEnd();
3163                 sel_cursor = cursor;
3164                 cursor = tmpcursor;
3165                 SetSelection();
3166                 if (selection == false) {
3167                         DeleteWordForward();
3168                 } else {
3169                         CutSelection();
3170                 }
3171         }
3172 }
3173
3174
3175 // Change the case of a word at cursor position. The meaning of action
3176 // is:
3177 // 0  change to lowercase
3178 // 1  capitalize word
3179 // 2  change to uppercase
3180 // This function directly manipulates LyXParagraph::text because there
3181 // is no LyXParagraph::SetChar currently. I did what I could to ensure
3182 // that it is correct. I guess part of it should be moved to
3183 // LyXParagraph, but it will have to change for 1.1 anyway. At least
3184 // it does not access outside of the allocated array as the older
3185 // version did. (JMarc) 
3186 void LyXText::ChangeWordCase(LyXText::TextCase action) 
3187 {
3188         LyXParagraph * tmppar = cursor.par->ParFromPos(cursor.pos);
3189
3190         SetUndo(Undo::FINISH, tmppar->previous, tmppar->next); 
3191
3192         LyXParagraph::size_type tmppos = 
3193                 cursor.par->PositionInParFromPos(cursor.pos);
3194         while (tmppos < tmppar->size()) {
3195                 unsigned char c = tmppar->GetChar(tmppos);
3196                 if (IsKommaChar(c) || IsLineSeparatorChar(c))
3197                         break;
3198                 if (c != LyXParagraph::META_INSET) {
3199                         switch (action) {
3200                         case text_lowercase:
3201                                 c = tolower(c);
3202                                 break;
3203                         case text_capitalization:
3204                                 c = toupper(c);
3205                                 action = text_lowercase;
3206                                 break;
3207                         case text_uppercase:
3208                                 c = toupper(c);
3209                                 break;
3210                         }
3211                 }
3212                 
3213                 //tmppar->text[tmppos] = c;
3214                 tmppar->SetChar(tmppos, c);
3215                 ++tmppos;
3216         }
3217         CheckParagraph(tmppar, tmppos);
3218         CursorRightOneWord();
3219 }
3220
3221
3222 void LyXText::Delete()
3223 {
3224         // this is a very easy implementation
3225
3226         LyXCursor old_cursor = cursor;
3227         int old_cur_par_id = old_cursor.par->id();
3228         int old_cur_par_prev_id = old_cursor.par->previous ?
3229                 old_cursor.par->previous->id() : 0;
3230         
3231         // just move to the right
3232         CursorRightIntern();
3233
3234         // CHECK Look at the comment here.
3235         // This check is not very good...
3236         // The CursorRightIntern calls DeleteEmptyParagrapgMechanism
3237         // and that can very well delete the par or par->previous in
3238         // old_cursor. Will a solution where we compare paragraph id's
3239         //work better?
3240         if ((cursor.par->previous ? cursor.par->previous->id() : 0)
3241             == old_cur_par_prev_id
3242             && cursor.par->id() != old_cur_par_id)
3243                 return; // delete-empty-paragraph-mechanism has done it
3244
3245         // if you had success make a backspace
3246         if (old_cursor.par != cursor.par || old_cursor.pos != cursor.pos) {
3247                 LyXCursor tmpcursor = cursor;
3248                 cursor = old_cursor; // to make sure undo gets the right cursor position
3249                 SetUndo(Undo::DELETE, 
3250                         cursor.par->ParFromPos(cursor.pos)->previous, 
3251                         cursor.par->ParFromPos(cursor.pos)->next); 
3252                 cursor = tmpcursor;
3253                 Backspace();
3254         }
3255 }
3256
3257
3258 void LyXText::Backspace()
3259 {
3260         /* table stuff -- begin */
3261         if (cursor.par->table) {
3262                 BackspaceInTable();
3263                 return;
3264         }
3265         /* table stuff -- end */
3266         
3267         LyXFont rawtmpfont = current_font;
3268         LyXFont realtmpfont = real_current_font;
3269    
3270         // Get the font that is used to calculate the baselineskip
3271         int const lastpos = cursor.par->Last();
3272         LyXFont rawparfont = cursor.par->GetFontSettings(lastpos - 1);
3273
3274         if (cursor.pos == 0) {
3275                 // The cursor is at the beginning of a paragraph, so the the backspace
3276                 // will collapse two paragraphs into one.
3277                 
3278                 // we may paste some paragraphs
3279       
3280                 // is it an empty paragraph?
3281       
3282                 if ((lastpos == 0
3283                      || (lastpos == 1 && cursor.par->IsSeparator(0)))
3284                     && !(cursor.par->Next() 
3285                          && cursor.par->footnoteflag == LyXParagraph::NO_FOOTNOTE
3286                          && cursor.par->Next()->footnoteflag == LyXParagraph::OPEN_FOOTNOTE)) {
3287                         // This is an empty paragraph and we delete it just by moving the cursor one step
3288                         // left and let the DeleteEmptyParagraphMechanism handle the actual deletion
3289                         // of the paragraph.
3290                         
3291                         if (cursor.par->previous) {
3292                                 LyXParagraph * tmppar = cursor.par->previous->FirstPhysicalPar();
3293                                 if (cursor.par->GetLayout() == tmppar->GetLayout()
3294                                     && cursor.par->footnoteflag == tmppar->footnoteflag
3295                                     && cursor.par->GetAlign() == tmppar->GetAlign()) {
3296                                         // Inherit botom DTD from the paragraph below.
3297                                         // (the one we are deleting)
3298                                         tmppar->line_bottom = cursor.par->line_bottom;
3299                                         tmppar->added_space_bottom = cursor.par->added_space_bottom;
3300                                         tmppar->pagebreak_bottom = cursor.par->pagebreak_bottom;
3301                                 }
3302                                 
3303                                 CursorLeftIntern();
3304                      
3305                                 // the layout things can change the height of a row !
3306                                 int tmpheight = cursor.row->height;
3307                                 SetHeightOfRow(cursor.row);
3308                                 if (cursor.row->height != tmpheight) {
3309                                         refresh_y = cursor.y - cursor.row->baseline;
3310                                         refresh_row = cursor.row;
3311                                         status = LyXText::NEED_MORE_REFRESH;
3312                                 }
3313                                 return;
3314                         }
3315                 }
3316                 
3317                 if (cursor.par->ParFromPos(cursor.pos)->previous){
3318                         SetUndo(Undo::DELETE,
3319                                 cursor.par->ParFromPos(cursor.pos)->previous->previous,
3320                                 cursor.par->ParFromPos(cursor.pos)->next);
3321                 }
3322                 
3323                 LyXParagraph * tmppar = cursor.par;
3324                 Row * tmprow = cursor.row;
3325
3326                 // We used to do CursorLeftIntern() here, but it is
3327                 // not a good idea since it triggers the auto-delete
3328                 // mechanism. So we do a CursorLeftIntern()-lite,
3329                 // without the dreaded mechanism. (JMarc)
3330                 if (cursor.par->Previous()) { 
3331                         // steps into the above paragraph.
3332                         SetCursorIntern(cursor.par->Previous(), 
3333                                         cursor.par->Previous()->Last());
3334                 }
3335
3336                 /* Pasting is not allowed, if the paragraphs have different
3337                    layout. I think it is a real bug of all other
3338                    word processors to allow it. It confuses the user.
3339                    Even so with a footnote paragraph and a non-footnote
3340                    paragraph. I will not allow pasting in this case, 
3341                    because the user would be confused if the footnote behaves 
3342                    different wether it is open or closed.
3343                   
3344                    Correction: Pasting is always allowed with standard-layout
3345                 */
3346                 if (cursor.par != tmppar
3347                     && (cursor.par->GetLayout() == tmppar->GetLayout()
3348                         || tmppar->GetLayout() == 0 /*standard*/)
3349                     && cursor.par->footnoteflag == tmppar->footnoteflag
3350                     /* table stuff -- begin*/
3351                     && !cursor.par->table /* no pasting of tables */ 
3352                     /* table stuff -- end*/
3353                     && cursor.par->GetAlign() == tmppar->GetAlign()) {
3354
3355                         RemoveParagraph(tmprow);
3356                         RemoveRow(tmprow);
3357                         cursor.par->PasteParagraph();
3358                         
3359                         if (!cursor.pos || !cursor.par->IsSeparator(cursor.pos - 1))
3360                                 ; //cursor.par->InsertChar(cursor.pos, ' ');
3361                         // strangely enough it seems that commenting out the line above removes
3362                         // most or all of the segfaults. I will however also try to move the
3363                         // two Remove... lines in front of the PasteParagraph too.
3364                         else
3365                                 if (cursor.pos)
3366                                         cursor.pos--;
3367                         
3368                         status = LyXText::NEED_MORE_REFRESH;
3369                         refresh_row = cursor.row;
3370                         refresh_y = cursor.y - cursor.row->baseline;
3371                         
3372                         // remove the lost paragraph
3373                         // This one is not safe, since the paragraph that the tmprow and the
3374                         // following rows belong to has been deleted by the PasteParagraph
3375                         // above. The question is... could this be moved in front of the
3376                         // PasteParagraph?
3377                         //RemoveParagraph(tmprow);
3378                         //RemoveRow(tmprow);  
3379                         
3380                         AppendParagraph(cursor.row); // This rebuilds the rows.
3381                         UpdateCounters(cursor.row);
3382                         
3383                         // the row may have changed, block, hfills etc.
3384                         SetCursor(cursor.par, cursor.pos);
3385                 }
3386         } else {
3387                 /* this is the code for a normal backspace, not pasting
3388                  * any paragraphs */ 
3389                 SetUndo(Undo::DELETE, 
3390                         cursor.par->ParFromPos(cursor.pos)->previous, 
3391                         cursor.par->ParFromPos(cursor.pos)->next); 
3392                 // We used to do CursorLeftIntern() here, but it is
3393                 // not a good idea since it triggers the auto-delete
3394                 // mechanism. So we do a CursorLeftIntern()-lite,
3395                 // without the dreaded mechanism. (JMarc)
3396                 SetCursorIntern(cursor.par, cursor.pos - 1);
3397                 
3398                 // some insets are undeletable here
3399                 if (cursor.par->GetChar(cursor.pos) == LyXParagraph::META_INSET) {
3400                         if (!cursor.par->GetInset(cursor.pos)->Deletable())
3401                                 return; 
3402                         // force complete redo when erasing display insets
3403                         // this is a cruel method but safe..... Matthias 
3404                         if (cursor.par->GetInset(cursor.pos)->display()){
3405                                 cursor.par->Erase(cursor.pos);
3406                                 RedoParagraph();
3407                                 return;
3408                         }
3409                 }
3410                 
3411                 Row * row = cursor.row;
3412                 long y = cursor.y - row->baseline;
3413                 LyXParagraph::size_type z;
3414                 /* remember that a space at the end of a row doesnt count
3415                  * when calculating the fill */ 
3416                 if (cursor.pos < RowLast(row) ||
3417                     !cursor.par->IsLineSeparator(cursor.pos)) {
3418                         row->fill += SingleWidth(cursor.par, cursor.pos);
3419                 }
3420                 
3421                 /* some special code when deleting a newline. This is similar
3422                  * to the behavior when pasting paragraphs */ 
3423                 if (cursor.pos && cursor.par->IsNewline(cursor.pos)) {
3424                         cursor.par->Erase(cursor.pos);
3425                         // refresh the positions
3426                         Row * tmprow = row;
3427                         while (tmprow->next && tmprow->next->par == row->par) {
3428                                 tmprow = tmprow->next;
3429                                 tmprow->pos--;
3430                         }
3431                         if (cursor.par->IsLineSeparator(cursor.pos - 1))
3432                                 cursor.pos--;
3433                         
3434                         if (cursor.pos < cursor.par->Last() && !cursor.par->IsSeparator(cursor.pos)) {
3435                                 cursor.par->InsertChar(cursor.pos, ' ');
3436                                 // refresh the positions
3437                                 tmprow = row;
3438                                 while (tmprow->next && tmprow->next->par == row->par) {
3439                                         tmprow = tmprow->next;
3440                                         tmprow->pos++;
3441                                 }
3442                         }
3443                 } else {
3444                         cursor.par->Erase(cursor.pos);
3445                         
3446                         // refresh the positions
3447                         Row * tmprow = row;
3448                         while (tmprow->next && tmprow->next->par == row->par) {
3449                                 tmprow = tmprow->next;
3450                                 tmprow->pos--;
3451                         }
3452
3453                         // delete newlines at the beginning of paragraphs
3454                         while (cursor.par->Last() &&
3455                                cursor.par->IsNewline(cursor.pos) &&
3456                                cursor.pos == BeginningOfMainBody(cursor.par)) {
3457                                 cursor.par->Erase(cursor.pos);
3458                                 // refresh the positions
3459                                 tmprow = row;
3460                                 while (tmprow->next && 
3461                                        tmprow->next->par == row->par) {
3462                                         tmprow = tmprow->next;
3463                                         tmprow->pos--;
3464                                 }
3465                         }
3466                 }
3467                 
3468                 // is there a break one row above
3469                 if (row->previous && row->previous->par == row->par) {
3470                         z = NextBreakPoint(row->previous, paperwidth);
3471                         if ( z >= row->pos) {
3472                                 row->pos = z + 1;
3473                                 
3474                                 Row * tmprow = row->previous;
3475                                 
3476                                 // maybe the current row is now empty
3477                                 if (row->pos >= row->par->Last()) {
3478                                         // remove it
3479                                         RemoveRow(row);
3480                                         need_break_row = 0;
3481                                 } else {
3482                                         BreakAgainOneRow(row);
3483                                         if (row->next && row->next->par == row->par)
3484                                                 need_break_row = row->next;
3485                                         else
3486                                                 need_break_row = 0;
3487                                 }
3488                                 
3489                                 // set the dimensions of the row above
3490                                 y -= tmprow->height;
3491                                 tmprow->fill = Fill(tmprow, paperwidth);
3492                                 SetHeightOfRow(tmprow);
3493                                 
3494                                 refresh_y = y;
3495                                 refresh_row = tmprow;
3496                                 status = LyXText::NEED_MORE_REFRESH;
3497                                 current_font = rawtmpfont;
3498                                 real_current_font = realtmpfont;
3499                                 SetCursor(cursor.par, cursor.pos, false);
3500                                 // check, whether the last character's font has changed.
3501                                 rawtmpfont = cursor.par->GetFontSettings(cursor.par->Last() - 1);
3502                                 if (rawparfont != rawtmpfont)
3503                                         RedoHeightOfParagraph(cursor);
3504                                 return;
3505                         }
3506                 }
3507                 
3508                 // break the cursor row again
3509                 z = NextBreakPoint(row, paperwidth);
3510                 
3511                 if (z != RowLast(row) || 
3512                     (row->next && row->next->par == row->par &&
3513                      RowLast(row) == row->par->Last() - 1)){
3514                         
3515                         /* it can happen that a paragraph loses one row
3516                          * without a real breakup. This is when a word
3517                          * is to long to be broken. Well, I don t care this 
3518                          * hack ;-) */ 
3519                         if (row->next && row->next->par == row->par &&
3520                             RowLast(row) == row->par->Last() - 1)
3521                                 RemoveRow(row->next);
3522                         
3523                         refresh_y = y;
3524                         refresh_row = row;
3525                         status = LyXText::NEED_MORE_REFRESH;
3526                         
3527                         BreakAgainOneRow(row);
3528                         current_font = rawtmpfont; 
3529                         real_current_font = realtmpfont;
3530                         SetCursor(cursor.par, cursor.pos, false);
3531                         // cursor MUST be in row now
3532                         
3533                         if (row->next && row->next->par == row->par)
3534                                 need_break_row = row->next;
3535                         else
3536                                 need_break_row = 0;
3537                 } else  {
3538                         // set the dimensions of the row
3539                         row->fill = Fill(row, paperwidth);
3540                         int tmpheight = row->height;
3541                         SetHeightOfRow(row);
3542                         if (tmpheight == row->height)
3543                                 status = LyXText::NEED_VERY_LITTLE_REFRESH;
3544                         else
3545                                 status = LyXText::NEED_MORE_REFRESH;
3546                         refresh_y = y;
3547                         refresh_row = row;
3548                         current_font = rawtmpfont; 
3549                         real_current_font = realtmpfont;
3550                         SetCursor(cursor.par, cursor.pos, false);
3551                 }
3552         }
3553         // restore the current font
3554         // That is what a user expects!
3555         current_font = rawtmpfont; 
3556         real_current_font = realtmpfont;
3557         
3558         // check, wether the last characters font has changed.
3559         rawtmpfont = cursor.par->GetFontSettings(cursor.par->Last() - 1);
3560         if (rawparfont != rawtmpfont) {
3561                 RedoHeightOfParagraph(cursor);
3562         } else {
3563                 // now the special right address boxes
3564                 if (textclasslist.Style(buffer->params.textclass,
3565                                         cursor.par->GetLayout()).margintype == MARGIN_RIGHT_ADDRESS_BOX) {
3566                         RedoDrawingOfParagraph(cursor); 
3567                 }
3568         }
3569 }
3570
3571
3572 void LyXText::GetVisibleRow(int offset, Row * row_ptr, long y)
3573 {
3574         /* returns a printed row */
3575         Painter & pain = owner_->painter();
3576         
3577         bool is_rtl = row_ptr->par->isRightToLeftPar();
3578         LyXParagraph::size_type last = RowLastPrintable(row_ptr);
3579
3580         LyXParagraph::size_type vpos, pos;
3581         float x, tmpx;
3582         int y_top, y_bottom;
3583         float fill_separator, fill_hfill, fill_label_hfill;
3584         LyXParagraph * par, * firstpar;
3585         LyXFont font;
3586         int maxdesc;
3587         if (row_ptr->height <= 0) {
3588                 lyxerr << "LYX_ERROR: row.height: " << row_ptr->height << endl;
3589                 return;
3590         }
3591         PrepareToPrint(row_ptr, x, fill_separator,
3592                        fill_hfill, fill_label_hfill);
3593         
3594         // clear the area where we want to paint/print
3595         pain.fillRectangle(0, offset, paperwidth, row_ptr->height);
3596         
3597         if (selection) {
3598                 /* selection code */
3599                 if (bidi_same_direction) {
3600                         if (sel_start_cursor.row == row_ptr &&
3601                             sel_end_cursor.row == row_ptr) {
3602                                 if (sel_start_cursor.x < sel_end_cursor.x)
3603                                         pain.fillRectangle(sel_start_cursor.x, offset,
3604                                                            sel_end_cursor.x - sel_start_cursor.x,
3605                                                            row_ptr->height,
3606                                                            LColor::selection);
3607                                 else
3608                                         pain.fillRectangle(sel_end_cursor.x, offset,
3609                                                            sel_start_cursor.x - sel_end_cursor.x,
3610                                                            row_ptr->height,
3611                                                            LColor::selection);
3612                         } else if (sel_start_cursor.row == row_ptr) {
3613                                 if (is_rtl)
3614                                         pain.fillRectangle(0, offset,
3615                                                            sel_start_cursor.x,
3616                                                            row_ptr->height,
3617                                                            LColor::selection);
3618                                 else
3619                                         pain.fillRectangle(sel_start_cursor.x, offset,
3620                                                            paperwidth - sel_start_cursor.x,
3621                                                            row_ptr->height,
3622                                                            LColor::selection);
3623                         } else if (sel_end_cursor.row == row_ptr) {
3624                                 if (is_rtl)
3625                                         pain.fillRectangle(sel_end_cursor.x, offset,
3626                                                            paperwidth - sel_end_cursor.x,
3627                                                            row_ptr->height,
3628                                                            LColor::selection);
3629                                 else
3630                                         pain.fillRectangle(0, offset,
3631                                                            sel_end_cursor.x,
3632                                                            row_ptr->height,
3633                                                            LColor::selection);
3634                         } else if (y > long(sel_start_cursor.y)
3635                                    && y < long(sel_end_cursor.y)) {
3636                                 pain.fillRectangle(0, offset,
3637                                                    paperwidth, row_ptr->height,
3638                                                    LColor::selection);
3639                         }
3640                 } else if ( sel_start_cursor.row != row_ptr &&
3641                             sel_end_cursor.row != row_ptr &&
3642                             y > long(sel_start_cursor.y)
3643                             && y < long(sel_end_cursor.y)) {
3644                         pain.fillRectangle(0, offset,
3645                                            paperwidth, row_ptr->height,
3646                                            LColor::selection);
3647                 } else if (sel_start_cursor.row == row_ptr ||
3648                            sel_end_cursor.row == row_ptr) {
3649                         float tmpx = x;
3650                         int cell = 0;
3651                         if (row_ptr->par->table) {
3652                                 cell = NumberOfCell(row_ptr->par, row_ptr->pos);
3653                                 tmpx += row_ptr->par->table->GetBeginningOfTextInCell(cell);
3654                         }
3655                         if ( (sel_start_cursor.row != row_ptr && !is_rtl) ||
3656                              (sel_end_cursor.row != row_ptr && is_rtl))
3657                                 pain.fillRectangle(0, offset,
3658                                                    tmpx, row_ptr->height,
3659                                                    LColor::selection);
3660                         if (row_ptr->par->table) {
3661                                 float x_old = x;
3662                                 for (vpos = row_ptr->pos; vpos <= last; ++vpos)  {
3663                                         pos = vis2log(vpos);
3664                                         float old_tmpx = tmpx;
3665                                         if (row_ptr->par->IsNewline(pos)) {
3666                                                 tmpx = x_old + row_ptr->par->table->WidthOfColumn(cell);
3667                                                 x_old = tmpx;
3668                                                 ++cell;
3669                                                 tmpx += row_ptr->par->table->GetBeginningOfTextInCell(cell);
3670                                         } else {
3671                                                 tmpx += SingleWidth(row_ptr->par, pos);
3672                                         }
3673                                         if ( (sel_start_cursor.row != row_ptr ||
3674                                               sel_start_cursor.pos <= pos) &&
3675                                              (sel_end_cursor.row != row_ptr ||
3676                                               pos < sel_end_cursor.pos) )
3677                                                 pain.fillRectangle(old_tmpx, offset,
3678                                                                    tmpx - old_tmpx + 1,
3679                                                                    row_ptr->height,
3680                                                                    LColor::selection);
3681                                 }
3682                         } else {
3683                                 LyXParagraph::size_type main_body =
3684                                         BeginningOfMainBody(row_ptr->par);
3685
3686                                 for (vpos = row_ptr->pos; vpos <= last; ++vpos)  {
3687                                         pos = vis2log(vpos);
3688                                         float old_tmpx = tmpx;
3689                                         if (main_body > 0 && pos == main_body-1) {
3690                                                 tmpx += fill_label_hfill +
3691                                                         lyxfont::width(textclasslist.Style(buffer->params.textclass,
3692                                                                                            row_ptr->par->GetLayout()).labelsep,
3693                                                                        GetFont(row_ptr->par, -2));
3694                                                 if (row_ptr->par->IsLineSeparator(main_body-1))
3695                                                         tmpx -= SingleWidth(row_ptr->par, main_body-1);
3696                                         }
3697                                         if (HfillExpansion(row_ptr, pos)) {
3698                                                 tmpx += SingleWidth(row_ptr->par, pos);
3699                                                 if (pos >= main_body)
3700                                                         tmpx += fill_hfill;
3701                                                 else 
3702                                                         tmpx += fill_label_hfill;
3703                                         }
3704                                         else if (row_ptr->par->IsSeparator(pos)) {
3705                                                 tmpx += SingleWidth(row_ptr->par, pos);
3706                                                 if (pos >= main_body)
3707                                                         tmpx += fill_separator;
3708                                         } else
3709                                                 tmpx += SingleWidth(row_ptr->par, pos);
3710
3711                                         if ( (sel_start_cursor.row != row_ptr ||
3712                                               sel_start_cursor.pos <= pos) &&
3713                                              (sel_end_cursor.row != row_ptr ||
3714                                               pos < sel_end_cursor.pos) )
3715                                                 pain.fillRectangle(old_tmpx, offset,
3716                                                                    tmpx - old_tmpx + 1,
3717                                                                    row_ptr->height,
3718                                                            LColor::selection);
3719                                 }
3720                         }
3721                         if ( (sel_start_cursor.row != row_ptr && is_rtl) ||
3722                              (sel_end_cursor.row != row_ptr && !is_rtl) )
3723                                 pain.fillRectangle(tmpx, offset,
3724                                                    paperwidth - tmpx,
3725                                                    row_ptr->height,
3726                                                    LColor::selection);
3727                 }
3728         }
3729
3730         if (row_ptr->par->appendix){
3731                 pain.line(1, offset,
3732                           1, offset + row_ptr->height,
3733                           LColor::appendixline);
3734                 pain.line(paperwidth - 2, offset,
3735                           paperwidth - 2, offset + row_ptr->height,
3736                           LColor::appendixline);
3737         }
3738
3739         int depth = row_ptr->par->GetDepth();
3740         if (depth > 0) {
3741                 int next_depth = (row_ptr->next)
3742                         ? next_depth = row_ptr->next->par->GetDepth() : 0; 
3743                 int prev_depth = (row_ptr->previous)
3744                         ? row_ptr->previous->par->GetDepth() : 0;
3745
3746                 for (int i = 1; i <= depth; ++i)
3747                         pain.line(4*i, offset,
3748                                   4*i, offset + row_ptr->height - 1 - (i-next_depth-1)*3,
3749                                   LColor::depthbar);
3750
3751                 for (int i = prev_depth + 1; i <= depth; ++i)
3752                         pain.fillRectangle(4*i, offset,
3753                                            4, 2,
3754                                            LColor::depthbar);
3755
3756                 for (int i = next_depth + 1; i <= depth; ++i)
3757                         pain.fillRectangle(4*i, offset + row_ptr->height - 2 - (i-next_depth-1)*3,
3758                                            4, 2,
3759                                            LColor::depthbar);
3760         }
3761         
3762         if (row_ptr->par->pextra_type == LyXParagraph::PEXTRA_MINIPAGE) {
3763                 /* draw a marker at the left margin! */ 
3764                 LyXFont font = GetFont(row_ptr->par, 0);
3765                 int asc = lyxfont::maxAscent(font);
3766                 int x = (LYX_PAPER_MARGIN - lyxfont::width('|', font)) / 2;
3767                 int y1 = (offset + row_ptr->baseline);
3768                 int y2 = (offset + row_ptr->baseline) - asc;
3769                 pain.line(x, y1, x, y2, LColor::minipageline);
3770         }       
3771         if (row_ptr->par->footnoteflag == LyXParagraph::OPEN_FOOTNOTE) {
3772                 LyXFont font(LyXFont::ALL_SANE);
3773                 font.setSize(LyXFont::SIZE_FOOTNOTE);
3774                 font.setColor(LColor::footnote);
3775                 
3776                 int box_x = LYX_PAPER_MARGIN;
3777                 box_x += lyxfont::width(" wide-tab ", font);
3778                 if (row_ptr->previous && 
3779                     row_ptr->previous->par->footnoteflag != LyXParagraph::OPEN_FOOTNOTE){
3780                         string fs;
3781                         switch (row_ptr->par->footnotekind) {
3782                         case LyXParagraph::MARGIN:
3783                                 fs = " margin";
3784                                 break;
3785                         case LyXParagraph::FIG:
3786                                 fs = " fig";
3787                                 break;
3788                         case LyXParagraph::TAB:
3789                                 fs = " tab";
3790                                 break;
3791                         case LyXParagraph::WIDE_FIG:
3792                                 fs = " wide-fig";
3793                                 break;
3794                         case LyXParagraph::WIDE_TAB:
3795                                 fs = " wide-tab";
3796                                 break;
3797                         case LyXParagraph::ALGORITHM:
3798                                 fs = " alg";
3799                                 break;
3800                         case LyXParagraph::FOOTNOTE:
3801                                 fs = " foot";
3802                                 break;
3803                         }
3804                         
3805                         pain.fillRectangle(LYX_PAPER_MARGIN,
3806                                            offset + 1,
3807                                            box_x - LYX_PAPER_MARGIN,
3808                                            int(lyxfont::maxAscent(font)
3809                                                + lyxfont::maxDescent(font)),
3810                                            LColor::footnotebg);
3811                         
3812                         pain.line(LYX_PAPER_MARGIN, offset,
3813                                   paperwidth - LYX_PAPER_MARGIN, offset,
3814                                   LColor::footnoteframe);
3815                         
3816                         pain.text(LYX_PAPER_MARGIN,
3817                                   offset + int(lyxfont::maxAscent(font)) + 1,
3818                                   fs, font);
3819                         
3820                         pain.line(LYX_PAPER_MARGIN, offset,
3821                                   LYX_PAPER_MARGIN,
3822                                   offset + int(lyxfont::maxAscent(font)
3823                                                + lyxfont::maxDescent(font)),
3824                                   LColor::footnoteframe);
3825                         
3826                         pain.line(LYX_PAPER_MARGIN,
3827                                   offset + int(lyxfont::maxAscent(font)
3828                                                + lyxfont::maxDescent(font)) + 1,
3829                                   box_x,
3830                                   offset + int(lyxfont::maxAscent(font)
3831                                                + lyxfont::maxDescent(font)) + 1,
3832                                   LColor::footnoteframe);
3833                         
3834                 }
3835                 
3836                 /* draw the open floats in a red box */
3837                 pain.line(box_x, offset,
3838                           box_x, offset + row_ptr->height,
3839                           LColor::footnoteframe);
3840                 
3841                 pain.line(paperwidth - LYX_PAPER_MARGIN,
3842                           offset,
3843                           paperwidth - LYX_PAPER_MARGIN,
3844                           offset + row_ptr->height,
3845                           LColor::footnoteframe);
3846         } else if (row_ptr->previous &&
3847                    row_ptr->previous->par->footnoteflag
3848                    == LyXParagraph::OPEN_FOOTNOTE) {
3849                 LyXFont font(LyXFont::ALL_SANE);
3850                 font.setSize(LyXFont::SIZE_FOOTNOTE);
3851                 
3852                 int box_x = LYX_PAPER_MARGIN;
3853                 box_x += lyxfont::width(" wide-tab ", font);
3854                 
3855                 pain.line(box_x, offset,
3856                           paperwidth - LYX_PAPER_MARGIN,
3857                           offset, LColor::footnote);
3858         }
3859         
3860         LyXLayout const & layout =
3861                 textclasslist.Style(buffer->params.textclass,
3862                                     row_ptr->par->GetLayout());
3863         firstpar = row_ptr->par->FirstPhysicalPar();
3864         
3865         y_top = 0;
3866         y_bottom = row_ptr->height;
3867         
3868         /* is it a first row? */ 
3869         if (row_ptr->pos == 0
3870             && row_ptr->par == firstpar) {
3871                 
3872                 /* start of appendix? */
3873                 if (row_ptr->par->start_of_appendix){
3874                         pain.line(1, offset,
3875                                   paperwidth - 2, offset,
3876                                   LColor::appendixline);
3877                 }
3878                 
3879                 /* think about the margins */ 
3880                 if (!row_ptr->previous)
3881                         y_top += LYX_PAPER_MARGIN;
3882                 
3883                 if (row_ptr->par->pagebreak_top){ /* draw a top pagebreak  */
3884                         LyXFont pb_font;
3885                         pb_font.setColor(LColor::pagebreak).decSize();
3886                         int w = 0, a = 0, d = 0;
3887                         pain.line(0, offset + y_top + 2*DefaultHeight(),
3888                                   paperwidth, 
3889                                   offset + y_top + 2*DefaultHeight(),
3890                                   LColor::pagebreak, 
3891                                   Painter::line_onoffdash)
3892                                 .rectText(0,
3893                                           0,
3894                                           _("Page Break (top)"),
3895                                           pb_font,
3896                                           LColor::background,
3897                                           LColor::background, false, w, a, d);
3898                         pain.rectText((paperwidth - w)/2,
3899                                       offset +y_top + 2*DefaultHeight() +d,
3900                                       _("Page Break (top)"),
3901                                       pb_font,
3902                                       LColor::background,
3903                                       LColor::background);
3904                         y_top += 3 * DefaultHeight();
3905                 }
3906                 
3907                 if (row_ptr->par->added_space_top.kind() == VSpace::VFILL) {
3908                         /* draw a vfill top  */
3909                         pain.line(0, offset + 2 + y_top,
3910                                   LYX_PAPER_MARGIN, offset + 2 + y_top,
3911                                   LColor::vfillline);
3912                         
3913                         pain.line(0, offset + y_top + 3 * DefaultHeight(),
3914                                   LYX_PAPER_MARGIN,
3915                                   offset + y_top + 3 * DefaultHeight(),
3916                                   LColor::vfillline);
3917                         
3918                         pain.line(LYX_PAPER_MARGIN / 2, offset + 2 + y_top,
3919                                   LYX_PAPER_MARGIN / 2,
3920                                   offset + y_top + 3 * DefaultHeight(),
3921                                   LColor::vfillline);
3922                         
3923                         y_top += 3 * DefaultHeight();
3924                 }
3925                 
3926                 /* think about user added space */ 
3927                 y_top += int(row_ptr->par->added_space_top.inPixels(owner_));
3928                 
3929                 /* think about the parskip */ 
3930                 /* some parskips VERY EASY IMPLEMENTATION */ 
3931                 if (buffer->params.paragraph_separation == BufferParams::PARSEP_SKIP) {
3932                         if (layout.latextype == LATEX_PARAGRAPH
3933                             && firstpar->GetDepth() == 0
3934                             && firstpar->Previous())
3935                                 y_top += buffer->params.getDefSkip().inPixels(owner_);
3936                         else if (firstpar->Previous()
3937                                  && textclasslist.Style(buffer->params.textclass,
3938                                                         firstpar->Previous()->GetLayout()).latextype == LATEX_PARAGRAPH
3939                                  && firstpar->Previous()->GetDepth() == 0)
3940                                 // is it right to use defskip here, too? (AS) 
3941                                 y_top += buffer->params.getDefSkip().inPixels(owner_);
3942                 }
3943                 
3944                 if (row_ptr->par->line_top) {      /* draw a top line  */
3945                         y_top +=  lyxfont::ascent('x', GetFont(row_ptr->par, 0));
3946                         
3947                         pain.line(0, offset + y_top,
3948                                   paperwidth, offset + y_top,
3949                                   LColor::topline,
3950                                   Painter::line_solid,
3951                                   Painter::line_thick);
3952                         
3953                         y_top +=  lyxfont::ascent('x', GetFont(row_ptr->par, 0));
3954                 }
3955                 
3956                 /* should we print a label? */ 
3957                 if (layout.labeltype >= LABEL_STATIC
3958                     && (layout.labeltype != LABEL_STATIC
3959                         || layout.latextype != LATEX_ENVIRONMENT
3960                         || row_ptr->par->IsFirstInSequence())) {
3961                         font = GetFont(row_ptr->par, -2);
3962                         if (!row_ptr->par->GetLabelstring().empty()) {
3963                                 tmpx = x;
3964                                 string tmpstring = row_ptr->par->GetLabelstring();
3965                                 
3966                                 if (layout.labeltype == LABEL_COUNTER_CHAPTER) {
3967                                         if (buffer->params.secnumdepth >= 0) {
3968                                                 /* this is special code for the chapter layout. This is printed in
3969                                                  * an extra row and has a pagebreak at the top. */
3970                                                 float spacing_val = 1.0;
3971                                                 if (!row_ptr->par->spacing.isDefault()) {
3972                                                         spacing_val = row_ptr->par->spacing.getValue();
3973                                                 } else {
3974                                                         spacing_val = buffer->params.spacing.getValue();
3975                                                 }
3976    
3977                                                 maxdesc = int(lyxfont::maxDescent(font) * layout.spacing.getValue() * spacing_val)
3978                                                         + int(layout.parsep) * DefaultHeight();
3979                                                 if (is_rtl)
3980                                                         tmpx = paperwidth - LeftMargin(row_ptr) - 
3981                                                                 lyxfont::width(tmpstring, font);
3982                                                 pain.text(int(tmpx),
3983                                                           offset + row_ptr->baseline - row_ptr->ascent_of_text - maxdesc,
3984                                                           tmpstring, font);
3985                                         }
3986                                 } else {
3987                                         if (is_rtl) {
3988                                                 tmpx = paperwidth - LeftMargin(row_ptr)
3989                                                         + lyxfont::width(layout.labelsep, font);
3990                                                 if (row_ptr->par->footnoteflag == LyXParagraph::OPEN_FOOTNOTE)  {
3991                                                         LyXFont font(LyXFont::ALL_SANE);
3992                                                         font.setSize(LyXFont::SIZE_SMALL);
3993                                                         tmpx += lyxfont::width("Mwide-fixM", font);
3994                                                 }
3995                                         } else
3996                                                 tmpx = x - lyxfont::width(layout.labelsep, font)
3997                                                         - lyxfont::width(tmpstring, font);
3998
3999                                         /* draw it! */
4000                                         pain.text(int(tmpx),
4001                                                   offset + row_ptr->baseline,
4002                                                   tmpstring, font);
4003                                 }
4004                         }
4005                         /* the labels at the top of an environment. More or less for bibliography */ 
4006                 } else if (layout.labeltype == LABEL_TOP_ENVIRONMENT ||
4007                            layout.labeltype == LABEL_BIBLIO ||
4008                            layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT) {
4009                         if (row_ptr->par->IsFirstInSequence()) {
4010                                 font = GetFont(row_ptr->par, -2);
4011                                 if (!row_ptr->par->GetLabelstring().empty()) {
4012                                         string tmpstring = row_ptr->par->GetLabelstring();
4013                                         float spacing_val = 1.0;
4014                                         if (!row_ptr->par->spacing.isDefault()) {
4015                                                 spacing_val = row_ptr->par->spacing.getValue();
4016                                         } else {
4017                                                 spacing_val = buffer->params.spacing.getValue();
4018                                         }
4019    
4020                                         maxdesc = int(lyxfont::maxDescent(font) * layout.spacing.getValue() * spacing_val
4021                                                       + (layout.labelbottomsep * DefaultHeight()));
4022                                         
4023                                         tmpx = x;
4024                                         if (layout.labeltype == LABEL_CENTERED_TOP_ENVIRONMENT){
4025                                                 tmpx = ( (is_rtl ? LeftMargin(row_ptr) : x)
4026                                                          + paperwidth - RightMargin(row_ptr) ) / 2; 
4027                                                 tmpx -= lyxfont::width(tmpstring, font) / 2;
4028                                         } else if (is_rtl)
4029                                                 tmpx = paperwidth - LeftMargin(row_ptr) - 
4030                                                         lyxfont::width(tmpstring, font);
4031                                         pain.text(int(tmpx),
4032                                                   offset + row_ptr->baseline
4033                                                   - row_ptr->ascent_of_text
4034                                                   - maxdesc,
4035                                                   tmpstring, font);
4036                                 }
4037                         }
4038                 }
4039                 if (layout.labeltype == LABEL_BIBLIO && row_ptr->par->bibkey) {
4040                         font = GetFont(row_ptr->par, -1);
4041                         if (is_rtl)
4042                                 tmpx = paperwidth - LeftMargin(row_ptr)
4043                                         + lyxfont::width(layout.labelsep, font);
4044                         else
4045                                 tmpx = x - lyxfont::width(layout.labelsep, font)
4046                                         - row_ptr->par->bibkey->width(owner_->painter(), font);
4047                         row_ptr->par->bibkey->draw(pain,
4048                                                    font,
4049                                                    offset + row_ptr->baseline, 
4050                                                    tmpx);
4051                 }
4052         }
4053         
4054         /* is it a last row? */
4055         par = row_ptr->par->LastPhysicalPar();
4056         if (row_ptr->par->ParFromPos(last + 1) == par
4057             && (!row_ptr->next || row_ptr->next->par != row_ptr->par)) {     
4058                 
4059                 /* think about the margins */ 
4060                 if (!row_ptr->next)
4061                         y_bottom -= LYX_PAPER_MARGIN;
4062                 
4063                 /* draw a bottom pagebreak */ 
4064                 if (firstpar->pagebreak_bottom) {
4065                         LyXFont pb_font;
4066                         pb_font.setColor(LColor::pagebreak).decSize();
4067                         int w = 0, a = 0, d = 0;
4068                         pain.line(0,
4069                                   offset + y_bottom - 2 * DefaultHeight(), 
4070                                   paperwidth, 
4071                                   offset + y_bottom - 2 * DefaultHeight(),
4072                                   LColor::pagebreak,
4073                                   Painter::line_onoffdash)
4074                                 .rectText(0,
4075                                           0,
4076                                           _("Page Break (bottom)"),
4077                                           pb_font,
4078                                           LColor::background,
4079                                           LColor::background, false, w, a, d);
4080                         pain.rectText((paperwidth - w)/2,
4081                                       offset +y_top + 2*DefaultHeight() +d,
4082                                       _("Page Break (bottom)"),
4083                                       pb_font,
4084                                       LColor::background,
4085                                       LColor::background);
4086                         y_bottom -= 3 * DefaultHeight();
4087                 }
4088                 
4089                 if (firstpar->added_space_bottom.kind() == VSpace::VFILL) {
4090                         /* draw a vfill bottom  */
4091                         pain.line(0, offset + y_bottom - 3 * DefaultHeight(),
4092                                   LYX_PAPER_MARGIN,
4093                                   offset + y_bottom - 3 * DefaultHeight(),
4094                                   LColor::vfillline);
4095                         pain.line(0, offset + y_bottom - 2,
4096                                   LYX_PAPER_MARGIN,
4097                                   offset + y_bottom - 2,
4098                                   LColor::vfillline);
4099                         pain.line(LYX_PAPER_MARGIN / 2,
4100                                   offset + y_bottom - 3 * DefaultHeight(),
4101                                   LYX_PAPER_MARGIN / 2,
4102                                   offset + y_bottom - 2,
4103                                   LColor::vfillline);
4104                         y_bottom -= 3* DefaultHeight();
4105                 }
4106                 
4107                 /* think about user added space */ 
4108                 y_bottom -= int(firstpar->added_space_bottom.inPixels(owner_));
4109                 
4110                 if (firstpar->line_bottom) {
4111                         /* draw a bottom line */
4112                         y_bottom -= lyxfont::ascent('x', GetFont(par, par->Last() - 1));
4113                         pain.line(0, offset + y_bottom,
4114                                   paperwidth, offset + y_bottom,
4115                                   LColor::topline, Painter::line_solid,
4116                                   Painter::line_thick);
4117                         y_bottom -= lyxfont::ascent('x', GetFont(par, par->Last() - 1));
4118                 }
4119
4120                 // draw an endlabel
4121                 int endlabel = row_ptr->par->GetEndLabel();
4122                 if (endlabel == END_LABEL_BOX ||
4123                     endlabel == END_LABEL_FILLED_BOX) {
4124                         LyXFont font = GetFont(row_ptr->par, last);
4125                         int size = int(0.75 * lyxfont::maxAscent(font));
4126                         int y = (offset + row_ptr->baseline) - size;
4127                         int x = is_rtl ? LYX_PAPER_MARGIN 
4128                                 : paperwidth - LYX_PAPER_MARGIN - size;
4129                         if (row_ptr->par->footnoteflag == LyXParagraph::OPEN_FOOTNOTE)
4130                                 if (is_rtl) {
4131                                         LyXFont font(LyXFont::ALL_SANE);
4132                                         font.setSize(LyXFont::SIZE_SMALL);
4133                                         x += lyxfont::width("Mwide-figM", font);
4134                                 } else
4135                                         x -= LYX_PAPER_MARGIN/2;
4136                         if (row_ptr->fill <= size)
4137                                 x += (size - row_ptr->fill + 1) * (is_rtl ? -1 : 1);
4138                         if (endlabel == END_LABEL_BOX) {
4139                                 pain.line(x, y, x, y + size,
4140                                           LColor::eolmarker);
4141                                 pain.line(x + size, y, x + size , y + size,
4142                                           LColor::eolmarker);
4143                                 pain.line(x, y, x + size, y,
4144                                           LColor::eolmarker);
4145                                 pain.line(x, y + size, x + size, y + size,
4146                                           LColor::eolmarker);
4147                         } else
4148                                 pain.fillRectangle(x, y, size, size,
4149                                                    LColor::eolmarker);
4150                 }
4151         }
4152         
4153         /* draw the text in the pixmap */  
4154         
4155         vpos = row_ptr->pos;
4156         /* table stuff -- begin*/
4157         if (row_ptr->par->table) {
4158                 bool on_off;
4159                 int cell = NumberOfCell(row_ptr->par, row_ptr->pos);
4160                 float x_old = x;
4161                 x += row_ptr->par->table->GetBeginningOfTextInCell(cell);
4162                 
4163                 while (vpos <= last)  {
4164                         pos = vis2log(vpos);
4165                         if (row_ptr->par->IsNewline(pos)) {
4166                                 
4167                                 x = x_old + row_ptr->par->table->WidthOfColumn(cell);
4168                                 /* draw the table lines, still very simple */
4169                                 on_off = !row_ptr->par->table->TopLine(cell);
4170                                 if ((!on_off ||
4171                                      !row_ptr->par->table->TopAlreadyDrawed(cell)) &&
4172                                     !row_ptr->par->table->IsContRow(cell))
4173                                         pain.line(int(x_old),
4174                                                   offset + row_ptr->baseline - row_ptr->ascent_of_text,
4175                                                   int(x),
4176                                                   offset + row_ptr->baseline - row_ptr->ascent_of_text,
4177                                                   LColor::tableline,
4178                                                   on_off ? Painter::line_onoffdash : Painter::line_solid);
4179                                 
4180                                 on_off = !row_ptr->par->table->BottomLine(cell);
4181                                 if ((!on_off && !row_ptr->par->table->RowHasContRow(cell)) ||
4182                                     row_ptr->par->table->VeryLastRow(cell))
4183                                         
4184                                         pain.line(int(x_old),
4185                                                   offset + y_bottom - 1,
4186                                                   int(x),
4187                                                   offset + y_bottom - 1,
4188                                                   LColor::tableline,
4189                                                   on_off ? Painter::line_onoffdash : Painter::line_solid);
4190                                 
4191                                 on_off = !row_ptr->par->table->LeftLine(cell);
4192                                 
4193                                 pain.line(int(x_old),
4194                                           offset + row_ptr->baseline - row_ptr->ascent_of_text,
4195                                           int(x_old),
4196                                           offset + y_bottom - 1,
4197                                           LColor::tableline,
4198                                           on_off ? Painter::line_onoffdash : Painter::line_solid);
4199                                 
4200                                 on_off = !row_ptr->par->table->RightLine(cell);
4201                                 
4202                                 pain.line(int(x) - row_ptr->par->table->AdditionalWidth(cell),
4203                                           offset + row_ptr->baseline - row_ptr->ascent_of_text,
4204                                           int(x) - row_ptr->par->table->AdditionalWidth(cell),
4205                                           offset + y_bottom - 1,
4206                                           LColor::tableline,
4207                                           on_off ? Painter::line_onoffdash : Painter::line_solid);
4208                                 
4209                                 x_old = x;
4210                                 /* take care about the alignment and other spaces */
4211                                 ++cell;
4212                                 x += row_ptr->par->table->GetBeginningOfTextInCell(cell);
4213                                 if (row_ptr->par->table->IsFirstCell(cell))
4214                                         --cell; // little hack, sorry
4215                                 ++vpos;
4216                         } else if (row_ptr->par->IsHfill(pos)) {
4217                                 x += 1;
4218                                 
4219                                 pain.line(int(x),
4220                                           offset + row_ptr->baseline - DefaultHeight() / 2,
4221                                           int(x),
4222                                           offset + row_ptr->baseline,
4223                                           LColor::vfillline);
4224                                 
4225                                 x += 2;
4226                                 ++vpos;
4227                         } else if (row_ptr->par->IsSeparator(pos)) {
4228                                 tmpx = x;
4229                                 x+= SingleWidth(row_ptr->par, pos);
4230                                 ++vpos;
4231                         } else
4232                                 draw(row_ptr, vpos, offset, x);
4233                 }
4234                 
4235                 /* do not forget the very last cell. This has no NEWLINE so 
4236                  * ignored by the code above*/ 
4237                 if (cell == row_ptr->par->table->GetNumberOfCells()-1){
4238                         x = x_old + row_ptr->par->table->WidthOfColumn(cell);
4239                         on_off = !row_ptr->par->table->TopLine(cell);
4240                         if ((!on_off ||
4241                              !row_ptr->par->table->TopAlreadyDrawed(cell)) &&
4242                             !row_ptr->par->table->IsContRow(cell))
4243                                 
4244                                 pain.line(int(x_old),
4245                                           offset + row_ptr->baseline - row_ptr->ascent_of_text,
4246                                           int(x),
4247                                           offset + row_ptr->baseline - row_ptr->ascent_of_text,
4248                                           LColor::tableline,
4249                                           on_off ? Painter::line_onoffdash : Painter::line_solid);
4250                         on_off = !row_ptr->par->table->BottomLine(cell);
4251                         if ((!on_off && !row_ptr->par->table->RowHasContRow(cell)) ||
4252                             row_ptr->par->table->VeryLastRow(cell))
4253                                 
4254                                 pain.line(int(x_old),
4255                                           offset + y_bottom - 1,
4256                                           int(x),
4257                                           offset + y_bottom - 1,
4258                                           LColor::tableline,
4259                                           on_off ? Painter::line_onoffdash : Painter::line_solid);
4260                         
4261                         on_off = !row_ptr->par->table->LeftLine(cell);
4262                         
4263                         pain.line(int(x_old),
4264                                   offset + row_ptr->baseline - row_ptr->ascent_of_text,
4265                                   int(x_old),
4266                                   offset + y_bottom - 1,
4267                                   LColor::tableline,
4268                                   on_off ? Painter::line_onoffdash : Painter::line_solid);
4269                         
4270                         on_off = !row_ptr->par->table->RightLine(cell);
4271                         
4272                         pain.line(int(x) - row_ptr->par->table->AdditionalWidth(cell),
4273                                   offset + row_ptr->baseline - row_ptr->ascent_of_text,
4274                                   int(x) - row_ptr->par->table->AdditionalWidth(cell),
4275                                   offset + y_bottom - 1,
4276                                   LColor::tableline,
4277                                   on_off ? Painter::line_onoffdash : Painter::line_solid);
4278                 }
4279         } else {
4280                 /* table stuff -- end*/
4281                 LyXParagraph::size_type main_body = 
4282                         BeginningOfMainBody(row_ptr->par);
4283                 if (main_body > 0 &&
4284                     (main_body-1 > last || 
4285                      !row_ptr->par->IsLineSeparator(main_body-1)))
4286                         main_body = 0;
4287                 
4288                 while (vpos <= last)  {
4289                         pos = vis2log(vpos);
4290                         if (main_body > 0 && pos == main_body-1) {
4291                                 x += fill_label_hfill
4292                                         + lyxfont::width(layout.labelsep, GetFont(row_ptr->par, -2))
4293                                         - SingleWidth(row_ptr->par, main_body-1);
4294                         }
4295                         
4296                         if (row_ptr->par->IsHfill(pos)) {
4297                                 x += 1;
4298                                 pain.line(int(x),
4299                                           offset + row_ptr->baseline - DefaultHeight() / 2,
4300                                           int(x),
4301                                           offset + row_ptr->baseline,
4302                                           LColor::vfillline);
4303                                 
4304                                 if (HfillExpansion(row_ptr, pos)) {
4305                                         if (pos >= main_body) {
4306                                                 pain.line(int(x),
4307                                                           offset + row_ptr->baseline - DefaultHeight() / 4,
4308                                                           int(x + fill_hfill),
4309                                                           offset + row_ptr->baseline - DefaultHeight() / 4,
4310                                                           LColor::vfillline,
4311                                                           Painter::line_onoffdash);
4312                                                 x += fill_hfill;
4313                                         } else {
4314                                                 pain.line(int(x),
4315                                                           offset + row_ptr->baseline - DefaultHeight() / 4,
4316                                                           int(x + fill_label_hfill),
4317                                                           offset + row_ptr->baseline - DefaultHeight() / 4,
4318                                                           LColor::vfillline,
4319                                                           Painter::line_onoffdash);
4320                                                 
4321                                                 x += fill_label_hfill;
4322                                         }
4323                                         pain.line(int(x),
4324                                                   offset + row_ptr->baseline - DefaultHeight() / 2,
4325                                                   int(x),
4326                                                   offset + row_ptr->baseline,
4327                                                   LColor::vfillline);
4328                                 }
4329                                 x += 2;
4330                                 ++vpos;
4331                         } else if (row_ptr->par->IsSeparator(pos)) {
4332                                 x += SingleWidth(row_ptr->par, pos);
4333                                 if (pos >= main_body)
4334                                         x += fill_separator;
4335                                 ++vpos;
4336                         } else
4337                                 draw(row_ptr, vpos, offset, x);
4338                 }
4339         }
4340 }
4341
4342
4343 int LyXText::DefaultHeight() const
4344 {
4345         LyXFont font(LyXFont::ALL_SANE);
4346         return int(lyxfont::maxAscent(font) + lyxfont::maxDescent(font) * 1.5);
4347 }
4348
4349    
4350 /* returns the column near the specified x-coordinate of the row 
4351 * x is set to the real beginning of this column  */ 
4352 int LyXText::GetColumnNearX(Row * row, int & x) const
4353 {
4354         float tmpx = 0.0;
4355         float fill_separator, fill_hfill, fill_label_hfill;
4356    
4357         PrepareToPrint(row, tmpx, fill_separator,
4358                        fill_hfill, fill_label_hfill);
4359
4360         LyXParagraph::size_type vc = row->pos;
4361         LyXParagraph::size_type last = RowLastPrintable(row);
4362         LyXParagraph::size_type c = 0;
4363         LyXLayout const & layout = textclasslist.Style(buffer->params.textclass,
4364                                                        row->par->GetLayout());
4365         /* table stuff -- begin */
4366         if (row->par->table) {
4367                 //the last row doesn't need a newline at the end
4368                 if (row->next && row->next->par == row->par
4369                     && row->par->IsNewline(last))
4370                         last--;
4371                 int cell = NumberOfCell(row->par, row->pos);
4372                 float x_old = tmpx;
4373                 bool ready = false;
4374                 tmpx += row->par->table->GetBeginningOfTextInCell(cell);
4375                 while (vc <= last
4376                        && (c = vis2log(vc)) >= 0
4377                        && tmpx + (SingleWidth(row->par, c)/2) <= x
4378                        && !ready){
4379                         if (row->par->IsNewline(c)) {
4380                                 if (x_old + row->par->table->WidthOfColumn(cell) <= x){
4381                                         tmpx = x_old + row->par->table->WidthOfColumn(cell);
4382                                         x_old = tmpx;
4383                                         ++cell;
4384                                         tmpx += row->par->table->GetBeginningOfTextInCell(cell);
4385                                         ++vc;
4386                                 } else
4387                                         ready = true;
4388                         } else {
4389                                 tmpx += SingleWidth(row->par, c);
4390                                 ++vc;
4391                         }
4392                 }
4393         } else {
4394                 /* table stuff -- end*/
4395                 LyXParagraph::size_type main_body = BeginningOfMainBody(row->par);
4396                 float last_tmpx = tmpx;
4397
4398                 if (main_body > 0 &&
4399                     (main_body-1 > last || 
4400                      !row->par->IsLineSeparator(main_body-1)))
4401                         main_body = 0;
4402
4403                 while (vc <= last && tmpx <= x) {
4404                         c = vis2log(vc);
4405                         last_tmpx = tmpx;
4406                         if (main_body > 0 && c == main_body-1) {
4407                                 tmpx += fill_label_hfill +
4408                                         lyxfont::width(layout.labelsep,
4409                                                GetFont(row->par, -2));
4410                                 if (row->par->IsLineSeparator(main_body-1))
4411                                         tmpx -= SingleWidth(row->par, main_body-1);
4412                         }
4413              
4414                         if (HfillExpansion(row, c)) {
4415                                 x += SingleWidth(row->par, c);
4416                                 if (c >= main_body)
4417                                         tmpx += fill_hfill;
4418                                 else
4419                                         tmpx += fill_label_hfill;
4420                         }
4421                         else if (row->par->IsSeparator(c)) {
4422                                 tmpx += SingleWidth(row->par, c);
4423                                 if (c >= main_body)
4424                                         tmpx+= fill_separator;
4425                         } else
4426                                 tmpx += SingleWidth(row->par, c);
4427                         ++vc;
4428                 }
4429
4430                 if (vc > row->pos && (tmpx+last_tmpx)/2 > x) {
4431                         vc--;
4432                         tmpx = last_tmpx;
4433                 }
4434         }
4435
4436         if (vc > last + 1)  // This shouldn't happen.
4437                 vc = last+1;
4438
4439         if (row->pos > last)  // Row is empty?
4440                 c = row->pos;
4441         else if (vc > last ||
4442                  (vc - 1 >= row->pos &&
4443                   ( (row->par->IsSeparator(vis2log(vc)) && vis2log(vc) != last)
4444                     || (row->par->table && row->par->IsNewline(vc) )
4445                    ))) {
4446                 c = vis2log(vc - 1);
4447                 if (bidi_level(c) % 2 == 0)
4448                         ++c;
4449         } else {
4450                 c = vis2log(vc);
4451                 if (bidi_level(c) % 2 == 1)
4452                         ++c;
4453         }
4454
4455         if (!row->par->table && row->pos <= last && c > last
4456             && row->par->IsNewline(last)) {
4457                 if (bidi_level(last) % 2 == 0)
4458                         tmpx -= SingleWidth(row->par, last);
4459                 else
4460                         tmpx += SingleWidth(row->par, last);
4461                 c = last;
4462         }
4463
4464         c -= row->pos;
4465         x = int(tmpx);
4466         return c;
4467 }
4468
4469    
4470 /* turn the selection into a new environment. If there is no selection,
4471 * create an empty environment */ 
4472 void LyXText::InsertFootnoteEnvironment(LyXParagraph::footnote_kind kind)
4473 {
4474    /* no footnoteenvironment in a footnoteenvironment */ 
4475    if (cursor.par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
4476       WriteAlert(_("Impossible operation"), 
4477                  _("You can't insert a float in a float!"), 
4478                  _("Sorry."));
4479      return;
4480    }
4481    /* no marginpars in minipages */
4482    if (kind == LyXParagraph::MARGIN 
4483       && cursor.par->pextra_type == LyXParagraph::PEXTRA_MINIPAGE) {
4484       WriteAlert(_("Impossible operation"), 
4485                  _("You can't insert a marginpar in a minipage!"), 
4486                  _("Sorry."));
4487       return;
4488    }
4489    
4490    /* this doesnt make sense, if there is no selection */ 
4491    bool dummy_selection = false;
4492    if (!selection) {
4493       sel_start_cursor = cursor;       /* dummy selection  */
4494       sel_end_cursor = cursor;
4495       dummy_selection = true;
4496    }
4497    
4498    LyXParagraph *tmppar;
4499
4500    if (sel_start_cursor.par->table || sel_end_cursor.par->table){
4501       WriteAlert(_("Impossible operation"), _("Cannot cut table."), _("Sorry."));
4502       return;
4503    }
4504      
4505    /* a test to make sure there is not already a footnote
4506     * in the selection. */
4507    
4508    tmppar = sel_start_cursor.par->ParFromPos(sel_start_cursor.pos);
4509    
4510    while (tmppar != sel_end_cursor.par->ParFromPos(sel_end_cursor.pos) && 
4511           tmppar->footnoteflag == LyXParagraph::NO_FOOTNOTE)
4512      tmppar = tmppar->next;
4513    
4514    if (tmppar != sel_end_cursor.par->ParFromPos(sel_end_cursor.pos)
4515        || tmppar->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
4516       WriteAlert(_("Impossible operation"), 
4517                  _("Float would include float!"), 
4518                  _("Sorry."));
4519       return;
4520    }
4521    
4522    /* ok we have a selection. This is always between sel_start_cursor
4523     * and sel_end cursor */
4524
4525    SetUndo(Undo::FINISH, 
4526            sel_start_cursor.par->ParFromPos(sel_start_cursor.pos)->previous, 
4527            sel_end_cursor.par->ParFromPos(sel_end_cursor.pos)->next); 
4528    
4529    if (sel_end_cursor.pos > 0 
4530        && sel_end_cursor.par->IsLineSeparator(sel_end_cursor.pos - 1))
4531      sel_end_cursor.pos--;             /* please break before a space at
4532                                         * the end */
4533    if (sel_start_cursor.par == sel_end_cursor.par
4534        && sel_start_cursor.pos > sel_end_cursor.pos)
4535      sel_start_cursor.pos--;
4536
4537    sel_end_cursor.par->BreakParagraphConservative(sel_end_cursor.pos);
4538    
4539    sel_end_cursor.par = sel_end_cursor.par->Next();
4540    sel_end_cursor.pos = 0;
4541    
4542    // don't forget to insert a dummy layout paragraph if necessary
4543    if (sel_start_cursor.par->GetLayout() != sel_end_cursor.par->layout){
4544      sel_end_cursor.par->BreakParagraphConservative(0);
4545      sel_end_cursor.par->layout = LYX_DUMMY_LAYOUT;
4546      sel_end_cursor.par = sel_end_cursor.par->next;
4547    }
4548    else
4549      sel_end_cursor.par->layout = LYX_DUMMY_LAYOUT;
4550
4551    cursor = sel_end_cursor;
4552
4553    /* please break behind a space, if there is one. The space should
4554     * be erased too */ 
4555    if (sel_start_cursor.pos > 0 
4556        && sel_start_cursor.par->IsLineSeparator(sel_start_cursor.pos - 1))
4557      sel_start_cursor.pos--;
4558    if (sel_start_cursor.par->IsLineSeparator(sel_start_cursor.pos)) {
4559       sel_start_cursor.par->Erase(sel_start_cursor.pos);
4560    }
4561    
4562    sel_start_cursor.par->BreakParagraphConservative(sel_start_cursor.pos);
4563    tmppar = sel_start_cursor.par->Next();
4564    
4565    if (dummy_selection) {
4566            tmppar->Clear();
4567            if (kind == LyXParagraph::TAB
4568                || kind == LyXParagraph::FIG 
4569                || kind == LyXParagraph::WIDE_TAB
4570                || kind == LyXParagraph::WIDE_FIG 
4571                || kind == LyXParagraph::ALGORITHM) {
4572                    pair<bool, LyXTextClass::size_type> lres =
4573                            textclasslist.NumberOfLayout(buffer->params.textclass,
4574                                                         "Caption");
4575                    LyXTextClass::size_type lay;
4576                    if (lres.first) {
4577                            // layout fount
4578                            lay = lres.second;
4579                    } else {
4580                            // layout not found
4581                            lay = 0; // use default layout "Standard" (0)
4582                    }
4583                    tmppar->SetLayout(lay);
4584            }
4585    }
4586    else {
4587      if (sel_start_cursor.pos > 0) {
4588        /* the footnote-environment should begin with a standard layout.
4589         * Imagine you insert a footnote within an enumeration, you 
4590         * certainly do not want an enumerated footnote! */ 
4591        tmppar->Clear();
4592      }
4593      else {
4594        /* this is a exception the user would sometimes expect, I hope */
4595        sel_start_cursor.par->Clear();
4596      }
4597    }
4598    
4599    while (tmppar != sel_end_cursor.par) {
4600       tmppar->footnoteflag = LyXParagraph::OPEN_FOOTNOTE;
4601       tmppar->footnotekind = kind;
4602       tmppar = tmppar->Next();
4603    } 
4604
4605    RedoParagraphs(sel_start_cursor, sel_end_cursor.par->Next());
4606    
4607    SetCursor(sel_start_cursor.par->Next(), 0);
4608
4609    ClearSelection();
4610 }
4611    
4612
4613 // returns pointer to a specified row
4614 Row * LyXText::GetRow(LyXParagraph * par,
4615                       LyXParagraph::size_type pos, long & y) const
4616 {
4617         Row * tmprow = firstrow;
4618         y = 0;
4619         
4620         // find the first row of the specified paragraph
4621         while (tmprow->next && tmprow->par != par) {
4622                 y += tmprow->height;
4623                 tmprow = tmprow->next;
4624         }
4625         
4626         // now find the wanted row
4627         while (tmprow->pos < pos
4628                && tmprow->next
4629                && tmprow->next->par == par
4630                && tmprow->next->pos <= pos) {
4631                 y += tmprow->height;
4632                 tmprow = tmprow->next;
4633         }
4634         
4635         return tmprow;
4636 }