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