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