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