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