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