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