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