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