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