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