]> git.lyx.org Git - lyx.git/blob - src/text.C
Collapse all those LFUN_XYZ_APPLY to a single LFUN_INSET_APPLY.
[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-2001 The LyX Team.
8  *
9  * ====================================================== */
10
11 #include <config.h>
12
13 #include "lyxtext.h"
14 #include "lyxrow.h"
15 #include "paragraph.h"
16 #include "gettext.h"
17 #include "bufferparams.h"
18 #include "buffer.h"
19 #include "debug.h"
20 #include "intl.h"
21 #include "lyxrc.h"
22 #include "encoding.h"
23 #include "frontends/LyXView.h"
24 #include "frontends/Painter.h"
25 #include "frontends/font_metrics.h"
26 #include "frontends/screen.h"
27 #include "frontends/WorkArea.h"
28 #include "bufferview_funcs.h"
29 #include "BufferView.h"
30 #include "language.h"
31 #include "ParagraphParameters.h"
32 #include "undo_funcs.h"
33 #include "WordLangTuple.h"
34 #include "paragraph_funcs.h"
35 #include "rowpainter.h"
36
37 #include "insets/insettext.h"
38
39 #include "support/textutils.h"
40 #include "support/LAssert.h"
41 #include "support/lstrings.h"
42
43 #include <algorithm>
44
45 using std::max;
46 using std::min;
47 using std::endl;
48 using std::pair;
49 using lyx::pos_type;
50
51 /// top, right, bottom pixel margin
52 extern int const PAPER_MARGIN = 20;
53 /// margin for changebar
54 extern int const CHANGEBAR_MARGIN = 10;
55 /// left margin
56 extern int const LEFT_MARGIN = PAPER_MARGIN + CHANGEBAR_MARGIN;
57
58 extern int bibitemMaxWidth(BufferView *, LyXFont const &);
59
60
61 int LyXText::workWidth(BufferView & bview) const
62 {
63         if (inset_owner) {
64                 // FIXME: pass (const ?) ref
65                 return inset_owner->textWidth(&bview);
66         }
67         return bview.workWidth();
68 }
69
70
71 int LyXText::workWidth(BufferView & bview, Inset * inset) const
72 {
73         Paragraph * par = inset->parOwner();
74         lyx::Assert(par);
75
76         pos_type pos = par->getPositionOfInset(inset);
77         lyx::Assert(pos != -1);
78
79         LyXLayout_ptr const & layout = par->layout();
80
81         if (layout->margintype != MARGIN_RIGHT_ADDRESS_BOX) {
82                 // Optimization here: in most cases, the real row is
83                 // not needed, but only the par/pos values. So we just
84                 // construct a dummy row for leftMargin. (JMarc)
85                 Row dummyrow;
86                 dummyrow.par(par);
87                 dummyrow.pos(pos);
88                 return workWidth(bview) - leftMargin(&bview, &dummyrow);
89         } else {
90                 int dummy_y;
91                 Row * row = getRow(par, pos, dummy_y);
92                 Row * frow = row;
93                 while (frow->previous() && frow->par() == frow->previous()->par())
94                         frow = frow->previous();
95
96                 // FIXME: I don't understand this code - jbl
97
98                 unsigned int maxw = 0;
99                 while (!frow->isParEnd()) {
100                         if ((frow != row) && (maxw < frow->width()))
101                                 maxw = frow->width();
102                         frow = frow->next();
103                 }
104                 if (maxw)
105                         return maxw;
106
107         }
108         return workWidth(bview);
109 }
110
111
112 int LyXText::getRealCursorX(BufferView * bview) const
113 {
114         int x = cursor.x();
115         if (the_locking_inset && (the_locking_inset->getLyXText(bview)!=this))
116                 x = the_locking_inset->getLyXText(bview)->getRealCursorX(bview);
117         return x;
118 }
119
120
121 unsigned char LyXText::transformChar(unsigned char c, Paragraph * par,
122                         pos_type pos) const
123 {
124         if (!Encodings::is_arabic(c))
125                 if (lyxrc.font_norm_type == LyXRC::ISO_8859_6_8 && IsDigit(c))
126                         return c + (0xb0 - '0');
127                 else
128                         return c;
129
130         unsigned char const prev_char = pos > 0 ? par->getChar(pos-1) : ' ';
131         unsigned char next_char = ' ';
132
133         for (pos_type i = pos+1; i < par->size(); ++i)
134                 if (!Encodings::IsComposeChar_arabic(par->getChar(i))) {
135                         next_char = par->getChar(i);
136                         break;
137                 }
138
139         if (Encodings::is_arabic(next_char)) {
140                 if (Encodings::is_arabic(prev_char) &&
141                         !Encodings::is_arabic_special(prev_char))
142                         return Encodings::TransformChar(c, Encodings::FORM_MEDIAL);
143                 else
144                         return Encodings::TransformChar(c, Encodings::FORM_INITIAL);
145         } else {
146                 if (Encodings::is_arabic(prev_char) &&
147                         !Encodings::is_arabic_special(prev_char))
148                         return Encodings::TransformChar(c, Encodings::FORM_FINAL);
149                 else
150                         return Encodings::TransformChar(c, Encodings::FORM_ISOLATED);
151         }
152 }
153
154 // This is the comments that some of the warnings below refers to.
155 // There are some issues in this file and I don't think they are
156 // really related to the FIX_DOUBLE_SPACE patch. I'd rather think that
157 // this is a problem that has been here almost from day one and that a
158 // larger userbase with differenct access patters triggers the bad
159 // behaviour. (segfaults.) What I think happen is: In several places
160 // we store the paragraph in the current cursor and then moves the
161 // cursor. This movement of the cursor will delete paragraph at the
162 // old position if it is now empty. This will make the temporary
163 // pointer to the old cursor paragraph invalid and dangerous to use.
164 // And is some cases this will trigger a segfault. I have marked some
165 // of the cases where this happens with a warning, but I am sure there
166 // are others in this file and in text2.C. There is also a note in
167 // Delete() that you should read. In Delete I store the paragraph->id
168 // instead of a pointer to the paragraph. I am pretty sure this faulty
169 // use of temporary pointers to paragraphs that might have gotten
170 // invalidated (through a cursor movement) before they are used, are
171 // the cause of the strange crashes we get reported often.
172 //
173 // It is very tiresom to change this code, especially when it is as
174 // hard to read as it is. Help to fix all the cases where this is done
175 // would be greately appreciated.
176 //
177 // Lgb
178
179 int LyXText::singleWidth(BufferView * bview, Paragraph * par,
180                          pos_type pos) const
181 {
182         char const c = par->getChar(pos);
183         return singleWidth(bview, par, pos, c);
184 }
185
186
187 int LyXText::singleWidth(BufferView * bview, Paragraph * par,
188                          pos_type pos, char c) const
189 {
190         LyXFont const font = getFont(bview->buffer(), par, pos);
191
192         // The most common case is handled first (Asger)
193         if (IsPrintable(c)) {
194                 if (font.language()->RightToLeft()) {
195                         if (font.language()->lang() == "arabic" &&
196                             (lyxrc.font_norm_type == LyXRC::ISO_8859_6_8 ||
197                              lyxrc.font_norm_type == LyXRC::ISO_10646_1))
198                                 if (Encodings::IsComposeChar_arabic(c))
199                                         return 0;
200                                 else
201                                         c = transformChar(c, par, pos);
202                         else if (font.language()->lang() == "hebrew" &&
203                                  Encodings::IsComposeChar_hebrew(c))
204                                 return 0;
205                 }
206                 return font_metrics::width(c, font);
207
208         } else if (IsHfillChar(c)) {
209                 // Because of the representation as vertical lines
210                 return 3;
211         } else if (c == Paragraph::META_INSET) {
212                 Inset * tmpinset = par->getInset(pos);
213                 if (tmpinset) {
214 #if 1
215                         // this IS needed otherwise on initialitation we don't get the fill
216                         // of the row right (ONLY on initialization if we read a file!)
217                         // should be changed! (Jug 20011204)
218                         tmpinset->update(bview, font);
219 #endif
220                         return tmpinset->width(bview, font);
221                 } else
222                         return 0;
223
224         } else if (IsSeparatorChar(c))
225                 c = ' ';
226         else if (IsNewlineChar(c))
227                 c = 'n';
228         return font_metrics::width(c, font);
229 }
230
231
232 void LyXText::computeBidiTables(Buffer const * buf, Row * row) const
233 {
234         bidi_same_direction = true;
235         if (!lyxrc.rtl_support) {
236                 bidi_start = -1;
237                 return;
238         }
239
240         Inset * inset = row->par()->inInset();
241         if (inset && inset->owner() &&
242             inset->owner()->lyxCode() == Inset::ERT_CODE) {
243                 bidi_start = -1;
244                 return;
245         }
246
247         bidi_start = row->pos();
248         bidi_end = row->lastPrintablePos();
249
250         if (bidi_start > bidi_end) {
251                 bidi_start = -1;
252                 return;
253         }
254
255         if (bidi_end + 2 - bidi_start >
256             static_cast<pos_type>(log2vis_list.size())) {
257                 pos_type new_size =
258                         (bidi_end + 2 - bidi_start < 500) ?
259                         500 : 2 * (bidi_end + 2 - bidi_start);
260                 log2vis_list.resize(new_size);
261                 vis2log_list.resize(new_size);
262                 bidi_levels.resize(new_size);
263         }
264
265         vis2log_list[bidi_end + 1 - bidi_start] = -1;
266         log2vis_list[bidi_end + 1 - bidi_start] = -1;
267
268         pos_type stack[2];
269         bool const rtl_par =
270                 row->par()->isRightToLeftPar(buf->params);
271         int level = 0;
272         bool rtl = false;
273         bool rtl0 = false;
274         pos_type const main_body = row->par()->beginningOfMainBody();
275
276         for (pos_type lpos = bidi_start; lpos <= bidi_end; ++lpos) {
277                 bool is_space = row->par()->isLineSeparator(lpos);
278                 pos_type const pos =
279                         (is_space && lpos + 1 <= bidi_end &&
280                          !row->par()->isLineSeparator(lpos + 1) &&
281                          !row->par()->isNewline(lpos + 1))
282                         ? lpos + 1 : lpos;
283                 LyXFont font = row->par()->getFontSettings(buf->params, pos);
284                 if (pos != lpos && 0 < lpos && rtl0 && font.isRightToLeft() &&
285                     font.number() == LyXFont::ON &&
286                     row->par()->getFontSettings(buf->params, lpos - 1).number()
287                     == LyXFont::ON) {
288                         font = row->par()->getFontSettings(buf->params, lpos);
289                         is_space = false;
290                 }
291
292
293                 bool new_rtl = font.isVisibleRightToLeft();
294                 bool new_rtl0 = font.isRightToLeft();
295                 int new_level;
296
297                 if (lpos == main_body - 1
298                     && row->pos() < main_body - 1
299                     && is_space) {
300                         new_level = (rtl_par) ? 1 : 0;
301                         new_rtl = new_rtl0 = rtl_par;
302                 } else if (new_rtl0)
303                         new_level = (new_rtl) ? 1 : 2;
304                 else
305                         new_level = (rtl_par) ? 2 : 0;
306
307                 if (is_space && new_level >= level) {
308                         new_level = level;
309                         new_rtl = rtl;
310                         new_rtl0 = rtl0;
311                 }
312
313                 int new_level2 = new_level;
314
315                 if (level == new_level && rtl0 != new_rtl0) {
316                         --new_level2;
317                         log2vis_list[lpos - bidi_start] = (rtl) ? 1 : -1;
318                 } else if (level < new_level) {
319                         log2vis_list[lpos - bidi_start] =  (rtl) ? -1 : 1;
320                         if (new_level > rtl_par)
321                                 bidi_same_direction = false;
322                 } else
323                         log2vis_list[lpos - bidi_start] = (new_rtl) ? -1 : 1;
324                 rtl = new_rtl;
325                 rtl0 = new_rtl0;
326                 bidi_levels[lpos - bidi_start] = new_level;
327
328                 while (level > new_level2) {
329                         pos_type old_lpos = stack[--level];
330                         int delta = lpos - old_lpos - 1;
331                         if (level % 2)
332                                 delta = -delta;
333                         log2vis_list[lpos - bidi_start] += delta;
334                         log2vis_list[old_lpos - bidi_start] += delta;
335                 }
336                 while (level < new_level)
337                         stack[level++] = lpos;
338         }
339
340         while (level > 0) {
341                 pos_type const old_lpos = stack[--level];
342                 int delta = bidi_end - old_lpos;
343                 if (level % 2)
344                         delta = -delta;
345                 log2vis_list[old_lpos - bidi_start] += delta;
346         }
347
348         pos_type vpos = bidi_start - 1;
349         for (pos_type lpos = bidi_start;
350              lpos <= bidi_end; ++lpos) {
351                 vpos += log2vis_list[lpos - bidi_start];
352                 vis2log_list[vpos - bidi_start] = lpos;
353                 log2vis_list[lpos - bidi_start] = vpos;
354         }
355 }
356
357
358 // This method requires a previous call to ComputeBidiTables()
359 bool LyXText::isBoundary(Buffer const * buf, Paragraph * par,
360                          pos_type pos) const
361 {
362         if (!lyxrc.rtl_support || pos == 0)
363                 return false;
364
365         if (!bidi_InRange(pos - 1)) {
366                 /// This can happen if pos is the first char of a row.
367                 /// Returning false in this case is incorrect!
368                 return false;
369         }
370
371         bool const rtl = bidi_level(pos - 1) % 2;
372         bool const rtl2 = bidi_InRange(pos)
373                 ? bidi_level(pos) % 2
374                 : par->isRightToLeftPar(buf->params);
375         return rtl != rtl2;
376 }
377
378
379 bool LyXText::isBoundary(Buffer const * buf, Paragraph * par,
380                          pos_type pos, LyXFont const & font) const
381 {
382         if (!lyxrc.rtl_support)
383                 return false;    // This is just for speedup
384
385         bool const rtl = font.isVisibleRightToLeft();
386         bool const rtl2 = bidi_InRange(pos)
387                 ? bidi_level(pos) % 2
388                 : par->isRightToLeftPar(buf->params);
389         return rtl != rtl2;
390 }
391
392
393 int LyXText::leftMargin(BufferView * bview, Row const * row) const
394 {
395         Inset * ins;
396         if ((row->par()->getChar(row->pos()) == Paragraph::META_INSET) &&
397                 (ins=row->par()->getInset(row->pos())) &&
398                 (ins->needFullRow() || ins->display()))
399                 return LEFT_MARGIN;
400
401         LyXTextClass const & tclass =
402                 bview->buffer()->params.getLyXTextClass();
403         LyXLayout_ptr const & layout = row->par()->layout();
404
405         string parindent = layout->parindent;
406
407         int x = LEFT_MARGIN;
408
409         x += font_metrics::signedWidth(tclass.leftmargin(), tclass.defaultfont());
410
411         // this is the way, LyX handles the LaTeX-Environments.
412         // I have had this idea very late, so it seems to be a
413         // later added hack and this is true
414         if (!row->par()->getDepth()) {
415                 if (row->par()->layout() == tclass.defaultLayout()) {
416                         // find the previous same level paragraph
417                         if (row->par()->previous()) {
418                                 Paragraph * newpar = row->par()
419                                         ->depthHook(row->par()->getDepth());
420                                 if (newpar &&
421                                     newpar->layout()->nextnoindent)
422                                         parindent.erase();
423                         }
424                 }
425         } else {
426                 // find the next level paragraph
427
428                 Paragraph * newpar = row->par()->outerHook();
429
430                 // make a corresponding row. Needed to call LeftMargin()
431
432                 // check wether it is a sufficent paragraph
433                 if (newpar && newpar->layout()->isEnvironment()) {
434                         Row dummyrow;
435                         dummyrow.par(newpar);
436                         dummyrow.pos(newpar->size());
437                         x = leftMargin(bview, &dummyrow);
438                 } else {
439                         // this is no longer an error, because this function
440                         // is used to clear impossible depths after changing
441                         // a layout. Since there is always a redo,
442                         // LeftMargin() is always called
443                         row->par()->params().depth(0);
444                 }
445
446                 if (newpar && row->par()->layout() == tclass.defaultLayout()) {
447                         if (newpar->params().noindent())
448                                 parindent.erase();
449                         else {
450                                 parindent = newpar->layout()->parindent;
451                         }
452
453                 }
454         }
455
456         LyXFont const labelfont = getLabelFont(bview->buffer(), row->par());
457         switch (layout->margintype) {
458         case MARGIN_DYNAMIC:
459                 if (!layout->leftmargin.empty()) {
460                         x += font_metrics::signedWidth(layout->leftmargin,
461                                                   tclass.defaultfont());
462                 }
463                 if (!row->par()->getLabelstring().empty()) {
464                         x += font_metrics::signedWidth(layout->labelindent,
465                                                   labelfont);
466                         x += font_metrics::width(row->par()->getLabelstring(),
467                                             labelfont);
468                         x += font_metrics::width(layout->labelsep, labelfont);
469                 }
470                 break;
471         case MARGIN_MANUAL:
472                 x += font_metrics::signedWidth(layout->labelindent, labelfont);
473                 if (row->pos() >= row->par()->beginningOfMainBody()) {
474                         if (!row->par()->getLabelWidthString().empty()) {
475                                 x += font_metrics::width(row->par()->getLabelWidthString(),
476                                                labelfont);
477                                 x += font_metrics::width(layout->labelsep, labelfont);
478                         }
479                 }
480                 break;
481         case MARGIN_STATIC:
482                 x += font_metrics::signedWidth(layout->leftmargin, tclass.defaultfont()) * 4
483                         / (row->par()->getDepth() + 4);
484                 break;
485         case MARGIN_FIRST_DYNAMIC:
486                 if (layout->labeltype == LABEL_MANUAL) {
487                         if (row->pos() >= row->par()->beginningOfMainBody()) {
488                                 x += font_metrics::signedWidth(layout->leftmargin,
489                                                           labelfont);
490                         } else {
491                                 x += font_metrics::signedWidth(layout->labelindent,
492                                                           labelfont);
493                         }
494                 } else if (row->pos()
495                            // Special case to fix problems with
496                            // theorems (JMarc)
497                            || (layout->labeltype == LABEL_STATIC
498                                && layout->latextype == LATEX_ENVIRONMENT
499                                && ! row->par()->isFirstInSequence())) {
500                         x += font_metrics::signedWidth(layout->leftmargin,
501                                                   labelfont);
502                 } else if (layout->labeltype != LABEL_TOP_ENVIRONMENT
503                            && layout->labeltype != LABEL_BIBLIO
504                            && layout->labeltype !=
505                            LABEL_CENTERED_TOP_ENVIRONMENT) {
506                         x += font_metrics::signedWidth(layout->labelindent,
507                                                   labelfont);
508                         x += font_metrics::width(layout->labelsep, labelfont);
509                         x += font_metrics::width(row->par()->getLabelstring(),
510                                             labelfont);
511                 }
512                 break;
513
514         case MARGIN_RIGHT_ADDRESS_BOX:
515         {
516                 // ok, a terrible hack. The left margin depends on the widest
517                 // row in this paragraph. Do not care about footnotes, they
518                 // are *NOT* allowed in the LaTeX realisation of this layout.
519
520                 // find the first row of this paragraph
521                 Row const * tmprow = row;
522                 while (tmprow->previous()
523                        && tmprow->previous()->par() == row->par())
524                         tmprow = tmprow->previous();
525
526                 int minfill = tmprow->fill();
527                 while (tmprow->next() && tmprow->next()->par() == row->par()) {
528                         tmprow = tmprow->next();
529                         if (tmprow->fill() < minfill)
530                                 minfill = tmprow->fill();
531                 }
532
533                 x += font_metrics::signedWidth(layout->leftmargin,
534                         tclass.defaultfont());
535                 x += minfill;
536         }
537         break;
538         }
539
540         if ((workWidth(*bview) > 0) &&
541                 !row->par()->params().leftIndent().zero())
542         {
543                 LyXLength const len = row->par()->params().leftIndent();
544                 int const tw = inset_owner ?
545                         inset_owner->latexTextWidth(bview) : workWidth(*bview);
546                 x += len.inPixels(tw);
547         }
548
549         LyXAlignment align; // wrong type
550
551         if (row->par()->params().align() == LYX_ALIGN_LAYOUT)
552                 align = layout->align;
553         else
554                 align = row->par()->params().align();
555
556         // set the correct parindent
557         if (row->pos() == 0) {
558                 if ((layout->labeltype == LABEL_NO_LABEL
559                      || layout->labeltype == LABEL_TOP_ENVIRONMENT
560                      || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
561                      || (layout->labeltype == LABEL_STATIC
562                          && layout->latextype == LATEX_ENVIRONMENT
563                          && ! row->par()->isFirstInSequence()))
564                     && align == LYX_ALIGN_BLOCK
565                     && !row->par()->params().noindent()
566                         // in tabulars and ert paragraphs are never indented!
567                         && (!row->par()->inInset() || !row->par()->inInset()->owner() ||
568                                 (row->par()->inInset()->owner()->lyxCode() != Inset::TABULAR_CODE &&
569                                  row->par()->inInset()->owner()->lyxCode() != Inset::ERT_CODE))
570                     && (row->par()->layout() != tclass.defaultLayout() ||
571                         bview->buffer()->params.paragraph_separation ==
572                         BufferParams::PARSEP_INDENT)) {
573                         x += font_metrics::signedWidth(parindent,
574                                                   tclass.defaultfont());
575                 } else if (layout->labeltype == LABEL_BIBLIO) {
576                         // ale970405 Right width for bibitems
577                         x += bibitemMaxWidth(bview, tclass.defaultfont());
578                 }
579         }
580
581         return x;
582 }
583
584
585 int LyXText::rightMargin(Buffer const & buf, Row const & row) const
586 {
587         Inset * ins;
588         if ((row.par()->getChar(row.pos()) == Paragraph::META_INSET) &&
589                 (ins=row.par()->getInset(row.pos())) &&
590                 (ins->needFullRow() || ins->display()))
591                 return PAPER_MARGIN;
592
593         LyXTextClass const & tclass = buf.params.getLyXTextClass();
594         LyXLayout_ptr const & layout = row.par()->layout();
595
596         int x = PAPER_MARGIN
597                 + font_metrics::signedWidth(tclass.rightmargin(),
598                                        tclass.defaultfont());
599
600         // this is the way, LyX handles the LaTeX-Environments.
601         // I have had this idea very late, so it seems to be a
602         // later added hack and this is true
603         if (row.par()->getDepth()) {
604                 // find the next level paragraph
605
606                 Paragraph const * newpar = row.par();
607
608                 do {
609                         newpar = newpar->previous();
610                 } while (newpar
611                          && newpar->getDepth() >= row.par()->getDepth());
612
613                 // make a corresponding row. Needed to call LeftMargin()
614
615                 // check wether it is a sufficent paragraph
616                 if (newpar && newpar->layout()->isEnvironment()) {
617                         Row dummyrow;
618                         dummyrow.par(const_cast<Paragraph *>(newpar));
619                         dummyrow.pos(0);
620                         x = rightMargin(buf, dummyrow);
621                 } else {
622                         // this is no longer an error, because this function
623                         // is used to clear impossible depths after changing
624                         // a layout. Since there is always a redo,
625                         // LeftMargin() is always called
626                         row.par()->params().depth(0);
627                 }
628         }
629
630         //lyxerr << "rightmargin: " << layout->rightmargin << endl;
631         x += font_metrics::signedWidth(layout->rightmargin,
632                                        tclass.defaultfont())
633                 * 4 / (row.par()->getDepth() + 4);
634         return x;
635 }
636
637
638 int LyXText::labelEnd(BufferView & bview, Row const & row) const
639 {
640         if (row.par()->layout()->margintype == MARGIN_MANUAL) {
641                 Row tmprow = row;
642                 tmprow.pos(row.par()->size());
643                 // just the beginning of the main body
644                 return leftMargin(&bview, &tmprow);
645         }
646
647         // LabelEnd is only needed if the layout
648         // fills a flushleft label.
649         return 0;
650 }
651
652
653 // get the next breakpoint in a given paragraph
654 pos_type
655 LyXText::nextBreakPoint(BufferView * bview, Row const * row, int width) const
656 {
657         Paragraph * par = row->par();
658
659         if (width < 0)
660                 return par->size();
661
662         pos_type const pos = row->pos();
663
664         // position of the last possible breakpoint
665         // -1 isn't a suitable value, but a flag
666         pos_type last_separator = -1;
667         width -= rightMargin(*bview->buffer(), *row);
668
669         pos_type const main_body = par->beginningOfMainBody();
670         LyXLayout_ptr const & layout = par->layout();
671
672         pos_type i = pos;
673
674         if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX) {
675                 // special code for right address boxes, only newlines count
676                 while (i < par->size()) {
677                         if (par->isNewline(i)) {
678                                 last_separator = i;
679                                 i = par->size() - 1; // this means break
680                                 //x = width;
681                         } else if (par->isInset(i) && par->getInset(i)
682                                 && par->getInset(i)->display()) {
683                                 par->getInset(i)->display(false);
684                         }
685                         ++i;
686                 }
687         } else {
688                 // Last position is an invariant
689                 pos_type const last = par->size();
690                 // this is the usual handling
691                 int x = leftMargin(bview, row);
692                 bool doitonetime = true;
693                 while (doitonetime || ((x < width) && (i < last))) {
694                         doitonetime = false;
695                         char const c = par->getChar(i);
696                         Inset * in = 0;
697                         if (c == Paragraph::META_INSET)
698                                 in = par->getInset(i);
699                         if (IsNewlineChar(c)) {
700                                 last_separator = i;
701                                 x = width; // this means break
702                         } else if (in && !in->isChar()) {
703                                 // check wether a Display() inset is
704                                 // valid here. if not, change it to
705                                 // non-display
706                                 if (in->display() &&
707                                     (layout->isCommand() ||
708                                      (layout->labeltype == LABEL_MANUAL
709                                       && i < par->beginningOfMainBody())))
710                                 {
711                                         // display istn't allowd
712                                         in->display(false);
713                                         x += singleWidth(bview, par, i, c);
714                                 } else if (in->display() || in->needFullRow()) {
715                                         // So break the line here
716                                         if (i == pos) {
717                                                 if (pos < last-1) {
718                                                         last_separator = i;
719                                                         if (par->isLineSeparator(i+1))
720                                                                 ++last_separator;
721                                                 } else
722                                                         last_separator = last; // to avoid extra rows
723                                         } else
724                                                 last_separator = i - 1;
725                                         x = width;  // this means break
726                                 } else {
727                                         x += singleWidth(bview, par, i, c);
728                                         // we have to check this separately as we could have a
729                                         // lineseparator and then the algorithm below would prefer
730                                         // that which IS wrong! We should always break on an inset
731                                         // if it's too long and not on the last separator.
732                                         // Maybe the only exeption is insets used as chars but
733                                         // then we would have to have a special function inside
734                                         // the inset to tell us this. Till then we leave it as
735                                         // it is now. (Jug 20020106)
736                                         if (pos < i && x >= width && last_separator >= 0)
737                                                 last_separator = i - 1;
738                                 }
739                         } else  {
740                                 if (par->isLineSeparator(i))
741                                         last_separator = i;
742                                 x += singleWidth(bview, par, i, c);
743                         }
744                         ++i;
745                         if (i == main_body) {
746                                 x += font_metrics::width(layout->labelsep,
747                                                     getLabelFont(bview->buffer(), par));
748                                 if (par->isLineSeparator(i - 1))
749                                         x-= singleWidth(bview, par, i - 1);
750                                 int left_margin = labelEnd(*bview, *row);
751                                 if (x < left_margin)
752                                         x = left_margin;
753                         }
754                 }
755                 if ((pos+1 < i) && (last_separator < 0) && (x >= width))
756                         last_separator = i - 2;
757                 else if ((pos < i) && (last_separator < 0) && (x >= width))
758                         last_separator = i - 1;
759                 // end of paragraph is always a suitable separator
760                 else if (i == last && x < width)
761                         last_separator = i;
762         }
763
764         // well, if last_separator is still 0, the line isn't breakable.
765         // don't care and cut simply at the end
766         if (last_separator < 0) {
767                 last_separator = i;
768         }
769
770         // manual labels cannot be broken in LaTeX, do not care
771         if (main_body && last_separator < main_body)
772                 last_separator = main_body - 1;
773
774         return last_separator;
775 }
776
777
778 // returns the minimum space a row needs on the screen in pixel
779 int LyXText::fill(BufferView & bview, Row & row, int paper_width) const
780 {
781         if (paper_width < 0)
782                 return 0;
783
784         int w;
785         // get the pure distance
786         pos_type const last = row.lastPrintablePos();
787
788         // special handling of the right address boxes
789         if (row.par()->layout()->margintype == MARGIN_RIGHT_ADDRESS_BOX) {
790                 int const tmpfill = row.fill();
791                 row.fill(0); // the minfill in MarginLeft()
792                 w = leftMargin(&bview, &row);
793                 row.fill(tmpfill);
794         } else
795                 w = leftMargin(&bview, &row);
796
797         Paragraph * par = row.par();
798         LyXLayout_ptr const & layout = par->layout();
799
800         pos_type const main_body = par->beginningOfMainBody();
801         pos_type i = row.pos();
802
803         while (i <= last) {
804                 if (main_body > 0 && i == main_body) {
805                         w += font_metrics::width(layout->labelsep, getLabelFont(bview.buffer(), par));
806                         if (par->isLineSeparator(i - 1))
807                                 w -= singleWidth(&bview, par, i - 1);
808                         int left_margin = labelEnd(bview, row);
809                         if (w < left_margin)
810                                 w = left_margin;
811                 }
812                 w += singleWidth(&bview, par, i);
813                 ++i;
814         }
815         if (main_body > 0 && main_body > last) {
816                 w += font_metrics::width(layout->labelsep, getLabelFont(bview.buffer(), par));
817                 if (last >= 0 && par->isLineSeparator(last))
818                         w -= singleWidth(&bview, par, last);
819                 int const left_margin = labelEnd(bview, row);
820                 if (w < left_margin)
821                         w = left_margin;
822         }
823
824         int const fill = paper_width - w - rightMargin(*bview.buffer(), row);
825         return fill;
826 }
827
828
829 // returns the minimum space a manual label needs on the screen in pixel
830 int LyXText::labelFill(BufferView & bview, Row const & row) const
831 {
832         pos_type last = row.par()->beginningOfMainBody();
833
834         lyx::Assert(last > 0);
835
836         // -1 because a label ends either with a space that is in the label,
837         // or with the beginning of a footnote that is outside the label.
838         --last;
839
840         // a separator at this end does not count
841         if (row.par()->isLineSeparator(last))
842                 --last;
843
844         int w = 0;
845         pos_type i = row.pos();
846         while (i <= last) {
847                 w += singleWidth(&bview, row.par(), i);
848                 ++i;
849         }
850
851         int fill = 0;
852         string const & labwidstr = row.par()->params().labelWidthString();
853         if (!labwidstr.empty()) {
854                 LyXFont const labfont = getLabelFont(bview.buffer(), row.par());
855                 int const labwidth = font_metrics::width(labwidstr, labfont);
856                 fill = max(labwidth - w, 0);
857         }
858
859         return fill;
860 }
861
862
863 LColor::color LyXText::backgroundColor() const
864 {
865         if (inset_owner)
866                 return inset_owner->backgroundColor();
867         else
868                 return LColor::background;
869 }
870
871 void LyXText::setHeightOfRow(BufferView * bview, Row * row) const
872 {
873         // get the maximum ascent and the maximum descent
874         int asc = 0;
875         int desc = 0;
876         float layoutasc = 0;
877         float layoutdesc = 0;
878         float tmptop = 0;
879         LyXFont tmpfont;
880         Inset * tmpinset = 0;
881
882         // ok , let us initialize the maxasc and maxdesc value.
883         // This depends in LaTeX of the font of the last character
884         // in the paragraph. The hack below is necessary because
885         // of the possibility of open footnotes
886
887         // Correction: only the fontsize count. The other properties
888         //  are taken from the layoutfont. Nicer on the screen :)
889         Paragraph * par = row->par();
890         Paragraph * firstpar = row->par();
891
892         LyXLayout_ptr const & layout = firstpar->layout();
893
894         // as max get the first character of this row then it can increase but not
895         // decrease the height. Just some point to start with so we don't have to
896         // do the assignment below too often.
897         LyXFont font = getFont(bview->buffer(), par, row->pos());
898         LyXFont::FONT_SIZE const tmpsize = font.size();
899         font = getLayoutFont(bview->buffer(), par);
900         LyXFont::FONT_SIZE const size = font.size();
901         font.setSize(tmpsize);
902
903         LyXFont labelfont = getLabelFont(bview->buffer(), par);
904
905         float spacing_val = 1.0;
906         if (!row->par()->params().spacing().isDefault()) {
907                 spacing_val = row->par()->params().spacing().getValue();
908         } else {
909                 spacing_val = bview->buffer()->params.spacing.getValue();
910         }
911         //lyxerr << "spacing_val = " << spacing_val << endl;
912
913         int maxasc = int(font_metrics::maxAscent(font) *
914                          layout->spacing.getValue() *
915                          spacing_val);
916         int maxdesc = int(font_metrics::maxDescent(font) *
917                           layout->spacing.getValue() *
918                           spacing_val);
919
920         pos_type const pos_end = row->lastPos();
921         int labeladdon = 0;
922         int maxwidth = 0;
923
924         // Check if any insets are larger
925         for (pos_type pos = row->pos(); pos <= pos_end; ++pos) {
926                 if (row->par()->isInset(pos)) {
927                         tmpfont = getFont(bview->buffer(), row->par(), pos);
928                         tmpinset = row->par()->getInset(pos);
929                         if (tmpinset) {
930 #if 1 // this is needed for deep update on initialitation
931                                 tmpinset->update(bview, tmpfont);
932 #endif
933                                 asc = tmpinset->ascent(bview, tmpfont);
934                                 desc = tmpinset->descent(bview, tmpfont);
935                                 maxwidth += tmpinset->width(bview, tmpfont);
936                                 maxasc = max(maxasc, asc);
937                                 maxdesc = max(maxdesc, desc);
938                         }
939                 } else {
940                         maxwidth += singleWidth(bview, row->par(), pos);
941                 }
942         }
943
944         // Check if any custom fonts are larger (Asger)
945         // This is not completely correct, but we can live with the small,
946         // cosmetic error for now.
947         LyXFont::FONT_SIZE maxsize =
948                 row->par()->highestFontInRange(row->pos(), pos_end, size);
949         if (maxsize > font.size()) {
950                 font.setSize(maxsize);
951
952                 asc = font_metrics::maxAscent(font);
953                 desc = font_metrics::maxDescent(font);
954                 if (asc > maxasc)
955                         maxasc = asc;
956                 if (desc > maxdesc)
957                         maxdesc = desc;
958         }
959
960         // This is nicer with box insets:
961         ++maxasc;
962         ++maxdesc;
963
964         row->ascent_of_text(maxasc);
965
966         // is it a top line?
967         if (!row->pos() && (row->par() == firstpar)) {
968
969                 // some parksips VERY EASY IMPLEMENTATION
970                 if (bview->buffer()->params.paragraph_separation ==
971                         BufferParams::PARSEP_SKIP)
972                 {
973                         if (layout->isParagraph()
974                                 && firstpar->getDepth() == 0
975                                 && firstpar->previous())
976                         {
977                                 maxasc += bview->buffer()->params.getDefSkip().inPixels(*bview);
978                         } else if (firstpar->previous() &&
979                                    firstpar->previous()->layout()->isParagraph() &&
980                                    firstpar->previous()->getDepth() == 0)
981                         {
982                                 // is it right to use defskip here too? (AS)
983                                 maxasc += bview->buffer()->params.getDefSkip().inPixels(*bview);
984                         }
985                 }
986
987                 // the top margin
988                 if (!row->par()->previous() && isTopLevel())
989                         maxasc += PAPER_MARGIN;
990
991                 // add the vertical spaces, that the user added
992                 maxasc += getLengthMarkerHeight(*bview, firstpar->params().spaceTop());
993
994                 // do not forget the DTP-lines!
995                 // there height depends on the font of the nearest character
996                 if (firstpar->params().lineTop())
997
998                         maxasc += 2 * font_metrics::ascent('x', getFont(bview->buffer(),
999                                         firstpar, 0));
1000                 // and now the pagebreaks
1001                 if (firstpar->params().pagebreakTop())
1002                         maxasc += 3 * defaultRowHeight();
1003
1004                 // This is special code for the chapter, since the label of this
1005                 // layout is printed in an extra row
1006                 if (layout->labeltype == LABEL_COUNTER_CHAPTER
1007                         && bview->buffer()->params.secnumdepth >= 0)
1008                 {
1009                         float spacing_val = 1.0;
1010                         if (!row->par()->params().spacing().isDefault()) {
1011                                 spacing_val = row->par()->params().spacing().getValue();
1012                         } else {
1013                                 spacing_val = bview->buffer()->params.spacing.getValue();
1014                         }
1015
1016                         labeladdon = int(font_metrics::maxDescent(labelfont) *
1017                                          layout->spacing.getValue() *
1018                                          spacing_val)
1019                                 + int(font_metrics::maxAscent(labelfont) *
1020                                       layout->spacing.getValue() *
1021                                       spacing_val);
1022                 }
1023
1024                 // special code for the top label
1025                 if ((layout->labeltype == LABEL_TOP_ENVIRONMENT
1026                      || layout->labeltype == LABEL_BIBLIO
1027                      || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
1028                     && row->par()->isFirstInSequence()
1029                     && !row->par()->getLabelstring().empty())
1030                 {
1031                         float spacing_val = 1.0;
1032                         if (!row->par()->params().spacing().isDefault()) {
1033                                 spacing_val = row->par()->params().spacing().getValue();
1034                         } else {
1035                                 spacing_val = bview->buffer()->params.spacing.getValue();
1036                         }
1037
1038                         labeladdon = int(
1039                                 (font_metrics::maxAscent(labelfont) *
1040                                  layout->spacing.getValue() *
1041                                  spacing_val)
1042                                 +(font_metrics::maxDescent(labelfont) *
1043                                   layout->spacing.getValue() *
1044                                   spacing_val)
1045                                 + layout->topsep * defaultRowHeight()
1046                                 + layout->labelbottomsep * defaultRowHeight());
1047                 }
1048
1049                 // and now the layout spaces, for example before and after a section,
1050                 // or between the items of a itemize or enumerate environment
1051
1052                 if (!firstpar->params().pagebreakTop()) {
1053                         Paragraph * prev = row->par()->previous();
1054                         if (prev)
1055                                 prev = row->par()->depthHook(row->par()->getDepth());
1056                         if (prev && prev->layout() == firstpar->layout() &&
1057                                 prev->getDepth() == firstpar->getDepth() &&
1058                                 prev->getLabelWidthString() == firstpar->getLabelWidthString())
1059                         {
1060                                 layoutasc = (layout->itemsep * defaultRowHeight());
1061                         } else if (row->previous()) {
1062                                 tmptop = layout->topsep;
1063
1064                                 if (row->previous()->par()->getDepth() >= row->par()->getDepth())
1065                                         tmptop -= row->previous()->par()->layout()->bottomsep;
1066
1067                                 if (tmptop > 0)
1068                                         layoutasc = (tmptop * defaultRowHeight());
1069                         } else if (row->par()->params().lineTop()) {
1070                                 tmptop = layout->topsep;
1071
1072                                 if (tmptop > 0)
1073                                         layoutasc = (tmptop * defaultRowHeight());
1074                         }
1075
1076                         prev = row->par()->outerHook();
1077                         if (prev)  {
1078                                 maxasc += int(prev->layout()->parsep * defaultRowHeight());
1079                         } else {
1080                                 if (firstpar->previous() &&
1081                                         firstpar->previous()->getDepth() == 0 &&
1082                                         firstpar->previous()->layout() !=
1083                                         firstpar->layout())
1084                                 {
1085                                         // avoid parsep
1086                                 } else if (firstpar->previous()) {
1087                                         maxasc += int(layout->parsep * defaultRowHeight());
1088                                 }
1089                         }
1090                 }
1091         }
1092
1093         // is it a bottom line?
1094         if (row->par() == par
1095                 && (!row->next() || row->next()->par() != row->par())) {
1096                 // the bottom margin
1097                 if (!par->next() && isTopLevel())
1098                         maxdesc += PAPER_MARGIN;
1099
1100                 // add the vertical spaces, that the user added
1101                 maxdesc += getLengthMarkerHeight(*bview, firstpar->params().spaceBottom());
1102
1103                 // do not forget the DTP-lines!
1104                 // there height depends on the font of the nearest character
1105                 if (firstpar->params().lineBottom())
1106                         maxdesc += 2 * font_metrics::ascent('x',
1107                                                        getFont(bview->buffer(),
1108                                                                par,
1109                                                                max(pos_type(0), par->size() - 1)));
1110
1111                 // and now the pagebreaks
1112                 if (firstpar->params().pagebreakBottom())
1113                         maxdesc += 3 * defaultRowHeight();
1114
1115                 // and now the layout spaces, for example before and after
1116                 // a section, or between the items of a itemize or enumerate
1117                 // environment
1118                 if (!firstpar->params().pagebreakBottom()
1119                     && row->par()->next()) {
1120                         Paragraph * nextpar = row->par()->next();
1121                         Paragraph * comparepar = row->par();
1122                         float usual = 0;
1123                         float unusual = 0;
1124
1125                         if (comparepar->getDepth() > nextpar->getDepth()) {
1126                                 usual = (comparepar->layout()->bottomsep * defaultRowHeight());
1127                                 comparepar = comparepar->depthHook(nextpar->getDepth());
1128                                 if (comparepar->layout()!= nextpar->layout()
1129                                         || nextpar->getLabelWidthString() !=
1130                                         comparepar->getLabelWidthString())
1131                                 {
1132                                         unusual = (comparepar->layout()->bottomsep * defaultRowHeight());
1133                                 }
1134                                 if (unusual > usual)
1135                                         layoutdesc = unusual;
1136                                 else
1137                                         layoutdesc = usual;
1138                         } else if (comparepar->getDepth() ==  nextpar->getDepth()) {
1139
1140                                 if (comparepar->layout() != nextpar->layout()
1141                                         || nextpar->getLabelWidthString() !=
1142                                         comparepar->getLabelWidthString())
1143                                         layoutdesc = int(comparepar->layout()->bottomsep * defaultRowHeight());
1144                         }
1145                 }
1146         }
1147
1148         // incalculate the layout spaces
1149         maxasc += int(layoutasc * 2 / (2 + firstpar->getDepth()));
1150         maxdesc += int(layoutdesc * 2 / (2 + firstpar->getDepth()));
1151
1152         // calculate the new height of the text
1153         height -= row->height();
1154
1155         row->height(maxasc + maxdesc + labeladdon);
1156         row->baseline(maxasc + labeladdon);
1157
1158         height += row->height();
1159  
1160         row->top_of_text(row->baseline() - font_metrics::maxAscent(font));
1161
1162         float x = 0;
1163         if (layout->margintype != MARGIN_RIGHT_ADDRESS_BOX) {
1164                 float dummy;
1165                 // this IS needed
1166                 row->width(maxwidth);
1167                 prepareToPrint(bview, row, x, dummy, dummy, dummy, false);
1168         }
1169         row->width(int(maxwidth + x));
1170         if (inset_owner) {
1171                 Row * r = firstrow;
1172                 width = max(0, workWidth(*bview));
1173                 while (r) {
1174                         if (r->width() > width)
1175                                 width = r->width();
1176                         r = r->next();
1177                 }
1178         }
1179 }
1180
1181
1182 // Appends the implicit specified paragraph behind the specified row,
1183 // start at the implicit given position
1184 void LyXText::appendParagraph(BufferView * bview, Row * row) const
1185 {
1186         bool not_ready = true;
1187
1188         // The last character position of a paragraph is an invariant so we can
1189         // safely get it here. (Asger)
1190         pos_type const lastposition = row->par()->size();
1191         do {
1192                 // Get the next breakpoint
1193                 pos_type z = nextBreakPoint(bview, row, workWidth(*bview));
1194
1195                 Row * tmprow = row;
1196
1197                 // Insert the new row
1198                 if (z < lastposition) {
1199                         ++z;
1200                         insertRow(row, row->par(), z);
1201                         row = row->next();
1202
1203                         row->height(0);
1204                 } else
1205                         not_ready = false;
1206
1207                 // Set the dimensions of the row
1208                 // fixed fill setting now by calling inset->update() in
1209                 // SingleWidth when needed!
1210                 tmprow->fill(fill(*bview, *tmprow, workWidth(*bview)));
1211                 setHeightOfRow(bview, tmprow);
1212
1213         } while (not_ready);
1214 }
1215
1216
1217 // Do we even need this at all ? Code that uses  RowPainter *already*
1218 // sets need_break_row when it sees a CHANGED_IN_DRAW, though not
1219 // quite like this
1220 void LyXText::markChangeInDraw(BufferView * bv, Row * row, Row * prev)
1221 {
1222         if (prev && prev->par() == row->par()) {
1223                 breakAgainOneRow(bv, prev);
1224                 if (prev->next() != row) {
1225                         // breakAgainOneRow() has removed row_
1226                         need_break_row = prev;
1227                 } else {
1228                         need_break_row = row;
1229                 }
1230         } else if (!prev) {
1231                 need_break_row = firstrow;
1232         } else {
1233                 need_break_row = prev->next();
1234         }
1235         setCursor(bv, cursor.par(), cursor.pos());
1236         /* FIXME */
1237 }
1238
1239
1240 void LyXText::breakAgain(BufferView * bview, Row * row) const
1241 {
1242         bool not_ready = true;
1243
1244         do  {
1245                 // get the next breakpoint
1246                 pos_type z = nextBreakPoint(bview, row, workWidth(*bview));
1247                 Row * tmprow = row;
1248
1249                 if (z < row->par()->size()) {
1250                         if (!row->next() || (row->next() && row->next()->par() != row->par())) {
1251                                 // insert a new row
1252                                 ++z;
1253                                 insertRow(row, row->par(), z);
1254                                 row = row->next();
1255                                 row->height(0);
1256                         } else  {
1257                                 row = row->next();
1258                                 ++z;
1259                                 if (row->pos() == z)
1260                                         not_ready = false;     // the rest will not change
1261                                 else {
1262                                         row->pos(z);
1263                                 }
1264                         }
1265                 } else {
1266                         // if there are some rows too much, delete them
1267                         // only if you broke the whole paragraph!
1268                         Row * tmprow2 = row;
1269                         while (tmprow2->next() && tmprow2->next()->par() == row->par()) {
1270                                 tmprow2 = tmprow2->next();
1271                         }
1272                         while (tmprow2 != row) {
1273                                 tmprow2 = tmprow2->previous();
1274                                 removeRow(tmprow2->next());
1275                         }
1276                         not_ready = false;
1277                 }
1278
1279                 // set the dimensions of the row
1280                 tmprow->fill(fill(*bview, *tmprow, workWidth(*bview)));
1281                 setHeightOfRow(bview, tmprow);
1282         } while (not_ready);
1283 }
1284
1285
1286 // this is just a little changed version of break again
1287 void LyXText::breakAgainOneRow(BufferView * bview, Row * row)
1288 {
1289         // get the next breakpoint
1290         pos_type z = nextBreakPoint(bview, row, workWidth(*bview));
1291         Row * tmprow = row;
1292
1293         if (z < row->par()->size()) {
1294                 if (!row->next()
1295                     || (row->next() && row->next()->par() != row->par())) {
1296                         // insert a new row
1297                         ++z;
1298                         insertRow(row, row->par(), z);
1299                         row = row->next();
1300                         row->height(0);
1301                 } else  {
1302                         row = row->next();
1303                         ++z;
1304                         if (row->pos() != z)
1305                                 row->pos(z);
1306                 }
1307         } else {
1308                 // if there are some rows too much, delete them
1309                 // only if you broke the whole paragraph!
1310                 Row * tmprow2 = row;
1311                 while (tmprow2->next()
1312                        && tmprow2->next()->par() == row->par()) {
1313                         tmprow2 = tmprow2->next();
1314                 }
1315                 while (tmprow2 != row) {
1316                         tmprow2 = tmprow2->previous();
1317                         removeRow(tmprow2->next());
1318                 }
1319         }
1320
1321         // set the dimensions of the row
1322         tmprow->fill(fill(*bview, *tmprow, workWidth(*bview)));
1323         setHeightOfRow(bview, tmprow);
1324 }
1325
1326
1327 void LyXText::breakParagraph(BufferView * bview, char keep_layout)
1328 {
1329         // allow only if at start or end, or all previous is new text
1330         if (cursor.pos() && cursor.pos() != cursor.par()->size()
1331                 && cursor.par()->isChangeEdited(0, cursor.pos()))
1332                 return;
1333
1334         LyXTextClass const & tclass =
1335                 bview->buffer()->params.getLyXTextClass();
1336         LyXLayout_ptr const & layout = cursor.par()->layout();
1337
1338         // this is only allowed, if the current paragraph is not empty or caption
1339         // and if it has not the keepempty flag aktive
1340         if (cursor.par()->empty()
1341            && layout->labeltype != LABEL_SENSITIVE
1342            && !layout->keepempty)
1343                 return;
1344
1345         setUndo(bview, Undo::FINISH, cursor.par(), cursor.par()->next());
1346
1347         // Always break behind a space
1348         //
1349         // It is better to erase the space (Dekel)
1350         if (cursor.pos() < cursor.par()->size()
1351              && cursor.par()->isLineSeparator(cursor.pos()))
1352            cursor.par()->erase(cursor.pos());
1353         // cursor.pos(cursor.pos() + 1);
1354
1355         // break the paragraph
1356         if (keep_layout)
1357                 keep_layout = 2;
1358         else
1359                 keep_layout = layout->isEnvironment();
1360
1361         // we need to set this before we insert the paragraph. IMO the
1362         // breakParagraph call should return a bool if it inserts the
1363         // paragraph before or behind and we should react on that one
1364         // but we can fix this in 1.3.0 (Jug 20020509)
1365         bool const isempty = (layout->keepempty && cursor.par()->empty());
1366         ::breakParagraph(bview->buffer()->params, cursor.par(), cursor.pos(),
1367                        keep_layout);
1368
1369         // well this is the caption hack since one caption is really enough
1370         if (layout->labeltype == LABEL_SENSITIVE) {
1371                 if (!cursor.pos())
1372                         // set to standard-layout
1373                         cursor.par()->applyLayout(tclass.defaultLayout());
1374                 else
1375                         // set to standard-layout
1376                         cursor.par()->next()->applyLayout(tclass.defaultLayout());
1377         }
1378
1379         // if the cursor is at the beginning of a row without prior newline,
1380         // move one row up!
1381         // This touches only the screen-update. Otherwise we would may have
1382         // an empty row on the screen
1383         if (cursor.pos() && !cursor.row()->par()->isNewline(cursor.row()->pos() - 1)
1384                          && cursor.row()->pos() == cursor.pos())
1385         {
1386                 cursorLeft(bview);
1387         }
1388
1389         status(bview, LyXText::NEED_MORE_REFRESH);
1390         refresh_row = cursor.row();
1391         refresh_y = cursor.y() - cursor.row()->baseline();
1392
1393         // Do not forget the special right address boxes
1394         if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX) {
1395                 while (refresh_row->previous() &&
1396                        refresh_row->previous()->par() == refresh_row->par())
1397                 {
1398                         refresh_row = refresh_row->previous();
1399                         refresh_y -= refresh_row->height();
1400                 }
1401         }
1402         removeParagraph(cursor.row());
1403
1404         // set the dimensions of the cursor row
1405         cursor.row()->fill(fill(*bview, *cursor.row(), workWidth(*bview)));
1406
1407         setHeightOfRow(bview, cursor.row());
1408
1409         while (!cursor.par()->next()->empty()
1410           && cursor.par()->next()->isNewline(0))
1411            cursor.par()->next()->erase(0);
1412
1413         insertParagraph(bview, cursor.par()->next(), cursor.row());
1414
1415         updateCounters(bview);
1416
1417         // This check is necessary. Otherwise the new empty paragraph will
1418         // be deleted automatically. And it is more friendly for the user!
1419         if (cursor.pos() || isempty)
1420                 setCursor(bview, cursor.par()->next(), 0);
1421         else
1422                 setCursor(bview, cursor.par(), 0);
1423
1424         if (cursor.row()->next())
1425                 breakAgain(bview, cursor.row()->next());
1426
1427         need_break_row = 0;
1428 }
1429
1430
1431 // Just a macro to make some thing easier.
1432 void LyXText::redoParagraph(BufferView * bview) const
1433 {
1434         clearSelection();
1435         redoParagraphs(bview, cursor, cursor.par()->next());
1436         setCursorIntern(bview, cursor.par(), cursor.pos());
1437 }
1438
1439
1440 // insert a character, moves all the following breaks in the
1441 // same Paragraph one to the right and make a rebreak
1442 void LyXText::insertChar(BufferView * bview, char c)
1443 {
1444         setUndo(bview, Undo::INSERT, cursor.par(), cursor.par()->next());
1445
1446         // When the free-spacing option is set for the current layout,
1447         // disable the double-space checking
1448
1449         bool const freeSpacing = cursor.row()->par()->layout()->free_spacing ||
1450                 cursor.row()->par()->isFreeSpacing();
1451
1452         if (lyxrc.auto_number) {
1453                 static string const number_operators = "+-/*";
1454                 static string const number_unary_operators = "+-";
1455                 static string const number_seperators = ".,:";
1456
1457                 if (current_font.number() == LyXFont::ON) {
1458                         if (!IsDigit(c) && !contains(number_operators, c) &&
1459                             !(contains(number_seperators, c) &&
1460                               cursor.pos() >= 1 &&
1461                               cursor.pos() < cursor.par()->size() &&
1462                               getFont(bview->buffer(),
1463                                       cursor.par(),
1464                                       cursor.pos()).number() == LyXFont::ON &&
1465                               getFont(bview->buffer(),
1466                                       cursor.par(),
1467                                       cursor.pos() - 1).number() == LyXFont::ON)
1468                            )
1469                                 number(bview); // Set current_font.number to OFF
1470                 } else if (IsDigit(c) &&
1471                            real_current_font.isVisibleRightToLeft()) {
1472                         number(bview); // Set current_font.number to ON
1473
1474                         if (cursor.pos() > 0) {
1475                                 char const c = cursor.par()->getChar(cursor.pos() - 1);
1476                                 if (contains(number_unary_operators, c) &&
1477                                     (cursor.pos() == 1 ||
1478                                      cursor.par()->isSeparator(cursor.pos() - 2) ||
1479                                      cursor.par()->isNewline(cursor.pos() - 2))
1480                                   ) {
1481                                         setCharFont(bview->buffer(),
1482                                                     cursor.par(),
1483                                                     cursor.pos() - 1,
1484                                                     current_font);
1485                                 } else if (contains(number_seperators, c) &&
1486                                            cursor.pos() >= 2 &&
1487                                            getFont(bview->buffer(),
1488                                                    cursor.par(),
1489                                                    cursor.pos() - 2).number() == LyXFont::ON) {
1490                                         setCharFont(bview->buffer(),
1491                                                     cursor.par(),
1492                                                     cursor.pos() - 1,
1493                                                     current_font);
1494                                 }
1495                         }
1496                 }
1497         }
1498
1499
1500         // First check, if there will be two blanks together or a blank at
1501         // the beginning of a paragraph.
1502         // I decided to handle blanks like normal characters, the main
1503         // difference are the special checks when calculating the row.fill
1504         // (blank does not count at the end of a row) and the check here
1505
1506         // The bug is triggered when we type in a description environment:
1507         // The current_font is not changed when we go from label to main text
1508         // and it should (along with realtmpfont) when we type the space.
1509         // CHECK There is a bug here! (Asger)
1510
1511         LyXFont realtmpfont = real_current_font;
1512         LyXFont rawtmpfont = current_font;
1513         // store the current font.  This is because of the use of cursor
1514         // movements. The moving cursor would refresh the current font
1515
1516         // Get the font that is used to calculate the baselineskip
1517         pos_type const lastpos = cursor.par()->size();
1518         LyXFont rawparfont =
1519                 cursor.par()->getFontSettings(bview->buffer()->params,
1520                                               lastpos - 1);
1521
1522         bool jumped_over_space = false;
1523
1524         if (!freeSpacing && IsLineSeparatorChar(c)) {
1525                 if ((cursor.pos() > 0
1526                      && cursor.par()->isLineSeparator(cursor.pos() - 1))
1527                     || (cursor.pos() > 0
1528                         && cursor.par()->isNewline(cursor.pos() - 1))
1529                     || (cursor.pos() == 0)) {
1530                         static bool sent_space_message = false;
1531                         if (!sent_space_message) {
1532                                 if (cursor.pos() == 0)
1533                                         bview->owner()->message(_("You cannot insert a space at the beginning of a paragraph. Please read the Tutorial."));
1534                                 else
1535                                         bview->owner()->message(_("You cannot type two spaces this way. Please read the Tutorial."));
1536                                 sent_space_message = true;
1537                         }
1538                         charInserted();
1539                         return;
1540                 }
1541         } else if (IsNewlineChar(c)) {
1542                 if (cursor.pos() <= cursor.par()->beginningOfMainBody()) {
1543                         charInserted();
1544                         return;
1545                 }
1546                 // No newline at first position of a paragraph or behind labels.
1547                 // TeX does not allow that
1548
1549                 if (cursor.pos() < cursor.par()->size() &&
1550                     cursor.par()->isLineSeparator(cursor.pos()))
1551                         // newline always after a blank!
1552                         cursorRight(bview);
1553                 cursor.row()->fill(-1);        // to force a new break
1554         }
1555
1556         // the display inset stuff
1557         if (cursor.row()->par()->isInset(cursor.row()->pos())) {
1558                 Inset * inset = cursor.row()->par()->getInset(cursor.row()->pos());
1559                 if (inset && (inset->display() || inset->needFullRow())) {
1560                         // force a new break
1561                         cursor.row()->fill(-1); // to force a new break
1562                 }
1563         }
1564
1565         // get the cursor row fist
1566         Row * row = cursor.row();
1567         int y = cursor.y() - row->baseline();
1568         if (c != Paragraph::META_INSET) {
1569                 // Here case LyXText::InsertInset  already insertet the character
1570                 cursor.par()->insertChar(cursor.pos(), c);
1571         }
1572         setCharFont(bview->buffer(), cursor.par(), cursor.pos(), rawtmpfont);
1573
1574         if (!jumped_over_space) {
1575                 // refresh the positions
1576                 Row * tmprow = row;
1577                 while (tmprow->next() && tmprow->next()->par() == row->par()) {
1578                         tmprow = tmprow->next();
1579                         tmprow->pos(tmprow->pos() + 1);
1580                 }
1581         }
1582
1583         // Is there a break one row above
1584         if (row->previous() && row->previous()->par() == row->par()
1585             && (cursor.par()->isLineSeparator(cursor.pos())
1586                 || cursor.par()->isNewline(cursor.pos())
1587                 || ((cursor.pos() < cursor.par()->size()) &&
1588                     cursor.par()->isInset(cursor.pos()+1))
1589                 || cursor.row()->fill() == -1))
1590         {
1591                 pos_type z = nextBreakPoint(bview,
1592                                                            row->previous(),
1593                                                            workWidth(*bview));
1594                 if (z >= row->pos()) {
1595                         row->pos(z + 1);
1596
1597                         // set the dimensions of the row above
1598                         row->previous()->fill(fill(*bview,
1599                                                    *row->previous(),
1600                                                    workWidth(*bview)));
1601
1602                         setHeightOfRow(bview, row->previous());
1603
1604                         y -= row->previous()->height();
1605                         refresh_y = y;
1606                         refresh_row = row->previous();
1607                         status(bview, LyXText::NEED_MORE_REFRESH);
1608
1609                         breakAgainOneRow(bview, row);
1610
1611                         current_font = rawtmpfont;
1612                         real_current_font = realtmpfont;
1613                         setCursor(bview, cursor.par(), cursor.pos() + 1,
1614                                   false, cursor.boundary());
1615                         // cursor MUST be in row now.
1616
1617                         if (row->next() && row->next()->par() == row->par())
1618                                 need_break_row = row->next();
1619                         else
1620                                 need_break_row = 0;
1621
1622                         // check, wether the last characters font has changed.
1623                         if (cursor.pos() && cursor.pos() == cursor.par()->size()
1624                             && rawparfont != rawtmpfont)
1625                                 redoHeightOfParagraph(bview, cursor);
1626
1627                         charInserted();
1628                         return;
1629                 }
1630         }
1631
1632         // recalculate the fill of the row
1633         if (row->fill() >= 0) {
1634                 // needed because a newline will set fill to -1. Otherwise
1635                 // we would not get a rebreak!
1636                 row->fill(fill(*bview, *row, workWidth(*bview)));
1637         }
1638
1639         if (c == Paragraph::META_INSET || row->fill() < 0) {
1640                 refresh_y = y;
1641                 refresh_row = row;
1642                 status(bview, LyXText::NEED_MORE_REFRESH);
1643                 breakAgainOneRow(bview, row);
1644                 // will the cursor be in another row now?
1645                 if (row->lastPos() <= cursor.pos() + 1 && row->next()) {
1646                         if (row->next() && row->next()->par() == row->par())
1647                                 // this should always be true
1648                                 row = row->next();
1649                         breakAgainOneRow(bview, row);
1650                 }
1651                 current_font = rawtmpfont;
1652                 real_current_font = realtmpfont;
1653
1654                 setCursor(bview, cursor.par(), cursor.pos() + 1, false,
1655                           cursor.boundary());
1656                 if (isBoundary(bview->buffer(), cursor.par(), cursor.pos())
1657                     != cursor.boundary())
1658                         setCursor(bview, cursor.par(), cursor.pos(), false,
1659                           !cursor.boundary());
1660                 if (row->next() && row->next()->par() == row->par())
1661                         need_break_row = row->next();
1662                 else
1663                         need_break_row = 0;
1664         } else {
1665                 refresh_y = y;
1666                 refresh_row = row;
1667
1668                 int const tmpheight = row->height();
1669                 setHeightOfRow(bview, row);
1670                 if (tmpheight == row->height())
1671                         status(bview, LyXText::NEED_VERY_LITTLE_REFRESH);
1672                 else
1673                         status(bview, LyXText::NEED_MORE_REFRESH);
1674
1675                 current_font = rawtmpfont;
1676                 real_current_font = realtmpfont;
1677                 setCursor(bview, cursor.par(), cursor.pos() + 1, false,
1678                           cursor.boundary());
1679         }
1680
1681         // check, wether the last characters font has changed.
1682         if (cursor.pos() && cursor.pos() == cursor.par()->size()
1683             && rawparfont != rawtmpfont) {
1684                 redoHeightOfParagraph(bview, cursor);
1685         } else {
1686                 // now the special right address boxes
1687                 if (cursor.par()->layout()->margintype
1688                     == MARGIN_RIGHT_ADDRESS_BOX) {
1689                         redoDrawingOfParagraph(bview, cursor);
1690                 }
1691         }
1692
1693         charInserted();
1694 }
1695
1696
1697 void LyXText::charInserted()
1698 {
1699         // Here we could call FinishUndo for every 20 characters inserted.
1700         // This is from my experience how emacs does it.
1701         static unsigned int counter;
1702         if (counter < 20) {
1703                 ++counter;
1704         } else {
1705                 finishUndo();
1706                 counter = 0;
1707         }
1708 }
1709
1710
1711 void LyXText::prepareToPrint(BufferView * bview,
1712                              Row * row, float & x,
1713                              float & fill_separator,
1714                              float & fill_hfill,
1715                              float & fill_label_hfill,
1716                              bool bidi) const
1717 {
1718         float nlh;
1719         float ns;
1720
1721         float w = row->fill();
1722         fill_hfill = 0;
1723         fill_label_hfill = 0;
1724         fill_separator = 0;
1725         fill_label_hfill = 0;
1726
1727         bool const is_rtl =
1728                 row->par()->isRightToLeftPar(bview->buffer()->params);
1729         if (is_rtl) {
1730                 x = (workWidth(*bview) > 0)
1731                         ? rightMargin(*bview->buffer(), *row) : 0;
1732         } else
1733                 x = (workWidth(*bview) > 0)
1734                         ? leftMargin(bview, row) : 0;
1735
1736         // is there a manual margin with a manual label
1737         LyXLayout_ptr const & layout = row->par()->layout();
1738
1739         if (layout->margintype == MARGIN_MANUAL
1740             && layout->labeltype == LABEL_MANUAL) {
1741                 // one more since labels are left aligned
1742                 nlh = row->numberOfLabelHfills() + 1;
1743                 if (nlh && !row->par()->getLabelWidthString().empty()) {
1744                         fill_label_hfill = labelFill(*bview, *row) / nlh;
1745                 }
1746         }
1747
1748         // are there any hfills in the row?
1749         float const nh = row->numberOfHfills();
1750
1751         if (nh) {
1752                 if (w > 0)
1753                         fill_hfill = w / nh;
1754         // we don't have to look at the alignment if it is ALIGN_LEFT and
1755         // if the row is already larger then the permitted width as then
1756         // we force the LEFT_ALIGN'edness!
1757         } else if (static_cast<int>(row->width()) < workWidth(*bview)) {
1758                 // is it block, flushleft or flushright?
1759                 // set x how you need it
1760                 int align;
1761                 if (row->par()->params().align() == LYX_ALIGN_LAYOUT) {
1762                         align = layout->align;
1763                 } else {
1764                         align = row->par()->params().align();
1765                 }
1766
1767                 // center displayed insets
1768                 Inset * inset;
1769                 if (row->par()->isInset(row->pos())
1770                     && (inset=row->par()->getInset(row->pos()))
1771                     && (inset->display())) // || (inset->scroll() < 0)))
1772                     align = (inset->lyxCode() == Inset::MATHMACRO_CODE)
1773                         ? LYX_ALIGN_BLOCK : LYX_ALIGN_CENTER;
1774                 // ERT insets should always be LEFT ALIGNED on screen
1775                 inset = row->par()->inInset();
1776                 if (inset && inset->owner() &&
1777                         inset->owner()->lyxCode() == Inset::ERT_CODE)
1778                 {
1779                         align = LYX_ALIGN_LEFT;
1780                 }
1781
1782                 switch (align) {
1783             case LYX_ALIGN_BLOCK:
1784                         ns = row->numberOfSeparators();
1785                         if (ns && row->next() && row->next()->par() == row->par() &&
1786                             !(row->next()->par()->isNewline(row->next()->pos() - 1))
1787                             && !(row->next()->par()->isInset(row->next()->pos())
1788                                  && row->next()->par()->getInset(row->next()->pos())
1789                                  && row->next()->par()->getInset(row->next()->pos())->display())
1790                                 )
1791                         {
1792                                 fill_separator = w / ns;
1793                         } else if (is_rtl) {
1794                                 x += w;
1795                         }
1796                         break;
1797             case LYX_ALIGN_RIGHT:
1798                         x += w;
1799                         break;
1800             case LYX_ALIGN_CENTER:
1801                         x += w / 2;
1802                         break;
1803                 }
1804         }
1805         if (!bidi)
1806                 return;
1807
1808         computeBidiTables(bview->buffer(), row);
1809         if (is_rtl) {
1810                 pos_type main_body = row->par()->beginningOfMainBody();
1811                 pos_type last = row->lastPos();
1812
1813                 if (main_body > 0 &&
1814                     (main_body - 1 > last ||
1815                      !row->par()->isLineSeparator(main_body - 1))) {
1816                         x += font_metrics::width(layout->labelsep,
1817                                             getLabelFont(bview->buffer(), row->par()));
1818                         if (main_body - 1 <= last)
1819                                 x += fill_label_hfill;
1820                 }
1821         }
1822 }
1823
1824
1825 // important for the screen
1826
1827
1828 // the cursor set functions have a special mechanism. When they
1829 // realize, that you left an empty paragraph, they will delete it.
1830 // They also delete the corresponding row
1831
1832 void LyXText::cursorRightOneWord(BufferView * bview) const
1833 {
1834         // treat floats, HFills and Insets as words
1835         LyXCursor tmpcursor = cursor;
1836         // CHECK See comment on top of text.C
1837
1838         if (tmpcursor.pos() == tmpcursor.par()->size()
1839             && tmpcursor.par()->next()) {
1840                         tmpcursor.par(tmpcursor.par()->next());
1841                         tmpcursor.pos(0);
1842         } else {
1843                 int steps = 0;
1844
1845                 // Skip through initial nonword stuff.
1846                 while (tmpcursor.pos() < tmpcursor.par()->size() &&
1847                        ! tmpcursor.par()->isWord(tmpcursor.pos())) {
1848                   //    printf("Current pos1 %d", tmpcursor.pos()) ;
1849                         tmpcursor.pos(tmpcursor.pos() + 1);
1850                         ++steps;
1851                 }
1852                 // Advance through word.
1853                 while (tmpcursor.pos() < tmpcursor.par()->size() &&
1854                         tmpcursor.par()->isWord(tmpcursor.pos())) {
1855                   //     printf("Current pos2 %d", tmpcursor.pos()) ;
1856                         tmpcursor.pos(tmpcursor.pos() + 1);
1857                         ++steps;
1858                 }
1859         }
1860         setCursor(bview, tmpcursor.par(), tmpcursor.pos());
1861 }
1862
1863
1864 void LyXText::cursorTab(BufferView * bview) const
1865 {
1866         LyXCursor tmpcursor = cursor;
1867         while (tmpcursor.pos() < tmpcursor.par()->size()
1868            && !tmpcursor.par()->isNewline(tmpcursor.pos()))
1869         tmpcursor.pos(tmpcursor.pos() + 1);
1870
1871         if (tmpcursor.pos() == tmpcursor.par()->size()) {
1872                 if (tmpcursor.par()->next()) {
1873                         tmpcursor.par(tmpcursor.par()->next());
1874                         tmpcursor.pos(0);
1875                 }
1876         } else
1877                 tmpcursor.pos(tmpcursor.pos() + 1);
1878         setCursor(bview, tmpcursor.par(), tmpcursor.pos());
1879 }
1880
1881
1882 // Skip initial whitespace at end of word and move cursor to *start*
1883 // of prior word, not to end of next prior word.
1884 void LyXText::cursorLeftOneWord(BufferView * bview)  const
1885 {
1886         LyXCursor tmpcursor = cursor;
1887         cursorLeftOneWord(tmpcursor);
1888         setCursor(bview, tmpcursor.par(), tmpcursor.pos());
1889 }
1890
1891
1892 void LyXText::cursorLeftOneWord(LyXCursor & cur) const
1893 {
1894         // treat HFills, floats and Insets as words
1895         cur = cursor;
1896         while (cur.pos()
1897                && (cur.par()->isSeparator(cur.pos() - 1)
1898                    || cur.par()->isKomma(cur.pos() - 1))
1899                && !(cur.par()->isHfill(cur.pos() - 1)
1900                     || cur.par()->isInset(cur.pos() - 1)))
1901                 cur.pos(cur.pos() - 1);
1902
1903         if (cur.pos()
1904             && (cur.par()->isInset(cur.pos() - 1)
1905                 || cur.par()->isHfill(cur.pos() - 1))) {
1906                 cur.pos(cur.pos() - 1);
1907         } else if (!cur.pos()) {
1908                 if (cur.par()->previous()) {
1909                         cur.par(cur.par()->previous());
1910                         cur.pos(cur.par()->size());
1911                 }
1912         } else {                // Here, cur != 0
1913                 while (cur.pos() > 0 &&
1914                        cur.par()->isWord(cur.pos() - 1))
1915                         cur.pos(cur.pos() - 1);
1916         }
1917 }
1918
1919
1920 // Select current word. This depends on behaviour of
1921 // CursorLeftOneWord(), so it is patched as well.
1922 void LyXText::getWord(LyXCursor & from, LyXCursor & to,
1923                       word_location const loc) const
1924 {
1925         // first put the cursor where we wana start to select the word
1926         from = cursor;
1927         switch (loc) {
1928         case WHOLE_WORD_STRICT:
1929                 if (cursor.pos() == 0 || cursor.pos() == cursor.par()->size()
1930                     || cursor.par()->isSeparator(cursor.pos())
1931                     || cursor.par()->isKomma(cursor.pos())
1932                     || cursor.par()->isSeparator(cursor.pos() - 1)
1933                     || cursor.par()->isKomma(cursor.pos() - 1)) {
1934                         to = from;
1935                         return;
1936                 }
1937                 // no break here, we go to the next
1938
1939         case WHOLE_WORD:
1940                 // Move cursor to the beginning, when not already there.
1941                 if (from.pos() && !from.par()->isSeparator(from.pos() - 1)
1942                     && !from.par()->isKomma(from.pos() - 1))
1943                         cursorLeftOneWord(from);
1944                 break;
1945         case PREVIOUS_WORD:
1946                 // always move the cursor to the beginning of previous word
1947                 cursorLeftOneWord(from);
1948                 break;
1949         case NEXT_WORD:
1950                 lyxerr << "LyXText::getWord: NEXT_WORD not implemented yet\n";
1951                 break;
1952         case PARTIAL_WORD:
1953                 break;
1954         }
1955         to = from;
1956         while (to.pos() < to.par()->size()
1957                && !to.par()->isSeparator(to.pos())
1958                && !to.par()->isKomma(to.pos())
1959                && !to.par()->isHfill(to.pos())
1960                && !to.par()->isInset(to.pos()))
1961         {
1962                 to.pos(to.pos() + 1);
1963         }
1964 }
1965
1966
1967 void LyXText::selectWord(BufferView * bview, word_location const loc)
1968 {
1969         LyXCursor from;
1970         LyXCursor to;
1971         getWord(from, to, loc);
1972         if (cursor != from)
1973                 setCursor(bview, from.par(), from.pos());
1974         if (to == from)
1975                 return;
1976         selection.cursor = cursor;
1977         setCursor(bview, to.par(), to.pos());
1978         setSelection(bview);
1979 }
1980
1981
1982 // Select the word currently under the cursor when no
1983 // selection is currently set
1984 bool LyXText::selectWordWhenUnderCursor(BufferView * bview,
1985                                         word_location const loc)
1986 {
1987         if (!selection.set()) {
1988                 selectWord(bview, loc);
1989                 return selection.set();
1990         }
1991         return false;
1992 }
1993
1994
1995 void LyXText::acceptChange(BufferView * bv)
1996 {
1997         if (!selection.set() && cursor.par()->size())
1998                 return;
1999
2000         bv->hideCursor();
2001  
2002         if (selection.start.par() == selection.end.par()) {
2003                 LyXCursor & startc = selection.start;
2004                 LyXCursor & endc = selection.end;
2005                 setUndo(bv, Undo::INSERT, startc.par(), startc.par()->next());
2006                 startc.par()->acceptChange(startc.pos(), endc.pos());
2007                 finishUndo();
2008                 clearSelection();
2009                 redoParagraphs(bv, startc, startc.par()->next());
2010                 setCursorIntern(bv, startc.par(), 0);
2011         }
2012 #warning handle multi par selection
2013 }
2014
2015
2016 void LyXText::rejectChange(BufferView * bv)
2017 {
2018         if (!selection.set() && cursor.par()->size())
2019                 return;
2020  
2021         bv->hideCursor();
2022  
2023         if (selection.start.par() == selection.end.par()) {
2024                 LyXCursor & startc = selection.start;
2025                 LyXCursor & endc = selection.end;
2026                 setUndo(bv, Undo::INSERT, startc.par(), startc.par()->next());
2027                 startc.par()->rejectChange(startc.pos(), endc.pos());
2028                 finishUndo();
2029                 clearSelection();
2030                 redoParagraphs(bv, startc, startc.par()->next());
2031                 setCursorIntern(bv, startc.par(), 0);
2032         }
2033 #warning handle multi par selection
2034 }
2035
2036  
2037 // This function is only used by the spellchecker for NextWord().
2038 // It doesn't handle LYX_ACCENTs and probably never will.
2039 WordLangTuple const
2040 LyXText::selectNextWordToSpellcheck(BufferView * bview, float & value) const
2041 {
2042         if (the_locking_inset) {
2043                 WordLangTuple word = the_locking_inset->selectNextWordToSpellcheck(bview, value);
2044                 if (!word.word().empty()) {
2045                         value += float(cursor.y());
2046                         value /= float(height);
2047                         return word;
2048                 }
2049                 // we have to go on checking so move cursor to the next char
2050                 if (cursor.pos() == cursor.par()->size()) {
2051                         if (!cursor.par()->next())
2052                                 return word;
2053                         cursor.par(cursor.par()->next());
2054                         cursor.pos(0);
2055                 } else
2056                         cursor.pos(cursor.pos() + 1);
2057         }
2058         Paragraph * tmppar = cursor.par();
2059
2060         // If this is not the very first word, skip rest of
2061         // current word because we are probably in the middle
2062         // of a word if there is text here.
2063         if (cursor.pos() || cursor.par()->previous()) {
2064                 while (cursor.pos() < cursor.par()->size()
2065                        && cursor.par()->isLetter(cursor.pos()))
2066                         cursor.pos(cursor.pos() + 1);
2067         }
2068
2069         // Now, skip until we have real text (will jump paragraphs)
2070         while (1) {
2071                 Paragraph * cpar(cursor.par());
2072                 pos_type const cpos(cursor.pos());
2073  
2074                 if (cpos == cpar->size()) {
2075                         if (cpar->next()) {
2076                                 cursor.par(cpar->next());
2077                                 cursor.pos(0);
2078                                 continue;
2079                         }
2080                         break;
2081                 }
2082
2083                 bool const is_bad_inset(cpar->isInset(cpos)
2084                         && !cpar->getInset(cpos)->allowSpellcheck()); 
2085  
2086                 if (cpar->isLetter(cpos) && !isDeletedText(*cpar, cpos)
2087                         && !is_bad_inset)
2088                         break;
2089  
2090                 cursor.pos(cpos + 1);
2091         }
2092  
2093         // now check if we hit an inset so it has to be a inset containing text!
2094         if (cursor.pos() < cursor.par()->size() &&
2095             cursor.par()->isInset(cursor.pos())) {
2096                 // lock the inset!
2097                 cursor.par()->getInset(cursor.pos())->edit(bview);
2098                 // now call us again to do the above trick
2099                 // but obviously we have to start from down below ;)
2100                 return bview->text->selectNextWordToSpellcheck(bview, value);
2101         }
2102
2103         // Update the value if we changed paragraphs
2104         if (cursor.par() != tmppar) {
2105                 setCursor(bview, cursor.par(), cursor.pos());
2106                 value = float(cursor.y())/float(height);
2107         }
2108
2109         // Start the selection from here
2110         selection.cursor = cursor;
2111
2112         string lang_code(
2113                 getFont(bview->buffer(), cursor.par(), cursor.pos())
2114                         .language()->code());
2115         // and find the end of the word (insets like optional hyphens
2116         // and ligature break are part of a word)
2117         while (cursor.pos() < cursor.par()->size()
2118                && cursor.par()->isLetter(cursor.pos())
2119                && !isDeletedText(*cursor.par(), cursor.pos()))
2120                 cursor.pos(cursor.pos() + 1);
2121
2122         // Finally, we copy the word to a string and return it
2123         string str;
2124         if (selection.cursor.pos() < cursor.pos()) {
2125                 pos_type i;
2126                 for (i = selection.cursor.pos(); i < cursor.pos(); ++i) {
2127                         if (!cursor.par()->isInset(i))
2128                                 str += cursor.par()->getChar(i);
2129                 }
2130         }
2131         return WordLangTuple(str, lang_code);
2132 }
2133
2134
2135 // This one is also only for the spellchecker
2136 void LyXText::selectSelectedWord(BufferView * bview)
2137 {
2138         if (the_locking_inset) {
2139                 the_locking_inset->selectSelectedWord(bview);
2140                 return;
2141         }
2142         // move cursor to the beginning
2143         setCursor(bview, selection.cursor.par(), selection.cursor.pos());
2144
2145         // set the sel cursor
2146         selection.cursor = cursor;
2147
2148         // now find the end of the word
2149         while (cursor.pos() < cursor.par()->size()
2150                && (cursor.par()->isLetter(cursor.pos())))
2151                 cursor.pos(cursor.pos() + 1);
2152
2153         setCursor(bview, cursor.par(), cursor.pos());
2154
2155         // finally set the selection
2156         setSelection(bview);
2157 }
2158
2159
2160 // Delete from cursor up to the end of the current or next word.
2161 void LyXText::deleteWordForward(BufferView * bview)
2162 {
2163         if (cursor.par()->empty())
2164                 cursorRight(bview);
2165         else {
2166                 LyXCursor tmpcursor = cursor;
2167                 tmpcursor.row(0); // ??
2168                 selection.set(true); // to avoid deletion
2169                 cursorRightOneWord(bview);
2170                 setCursor(bview, tmpcursor, tmpcursor.par(), tmpcursor.pos());
2171                 selection.cursor = cursor;
2172                 cursor = tmpcursor;
2173                 setSelection(bview);
2174
2175                 // Great, CutSelection() gets rid of multiple spaces.
2176                 cutSelection(bview, true, false);
2177         }
2178 }
2179
2180
2181 // Delete from cursor to start of current or prior word.
2182 void LyXText::deleteWordBackward(BufferView * bview)
2183 {
2184         if (cursor.par()->empty())
2185                 cursorLeft(bview);
2186         else {
2187                 LyXCursor tmpcursor = cursor;
2188                 tmpcursor.row(0); // ??
2189                 selection.set(true); // to avoid deletion
2190                 cursorLeftOneWord(bview);
2191                 setCursor(bview, tmpcursor, tmpcursor.par(), tmpcursor.pos());
2192                 selection.cursor = cursor;
2193                 cursor = tmpcursor;
2194                 setSelection(bview);
2195                 cutSelection(bview, true, false);
2196         }
2197 }
2198
2199
2200 // Kill to end of line.
2201 void LyXText::deleteLineForward(BufferView * bview)
2202 {
2203         if (cursor.par()->empty())
2204                 // Paragraph is empty, so we just go to the right
2205                 cursorRight(bview);
2206         else {
2207                 LyXCursor tmpcursor = cursor;
2208                 // We can't store the row over a regular setCursor
2209                 // so we set it to 0 and reset it afterwards.
2210                 tmpcursor.row(0); // ??
2211                 selection.set(true); // to avoid deletion
2212                 cursorEnd(bview);
2213                 setCursor(bview, tmpcursor, tmpcursor.par(), tmpcursor.pos());
2214                 selection.cursor = cursor;
2215                 cursor = tmpcursor;
2216                 setSelection(bview);
2217                 // What is this test for ??? (JMarc)
2218                 if (!selection.set()) {
2219                         deleteWordForward(bview);
2220                 } else {
2221                         cutSelection(bview, true, false);
2222                 }
2223         }
2224 }
2225
2226
2227 void LyXText::changeCase(BufferView & bview, LyXText::TextCase action)
2228 {
2229         LyXCursor from;
2230         LyXCursor to;
2231
2232         if (selection.set()) {
2233                 from = selection.start;
2234                 to = selection.end;
2235         } else {
2236                 getWord(from, to, PARTIAL_WORD);
2237                 setCursor(&bview, to.par(), to.pos() + 1);
2238         }
2239
2240         lyx::Assert(from <= to);
2241
2242         setUndo(&bview, Undo::FINISH, from.par(), to.par()->next());
2243
2244         pos_type pos = from.pos();
2245         Paragraph * par = from.par();
2246
2247         while (par && (pos != to.pos() || par != to.par())) {
2248                 if (pos == par->size()) {
2249                         par = par->next();
2250                         pos = 0;
2251                         continue;
2252                 }
2253                 unsigned char c = par->getChar(pos);
2254                 if (!IsInsetChar(c) && !IsHfillChar(c)) {
2255                         switch (action) {
2256                         case text_lowercase:
2257                                 c = lowercase(c);
2258                                 break;
2259                         case text_capitalization:
2260                                 c = uppercase(c);
2261                                 action = text_lowercase;
2262                                 break;
2263                         case text_uppercase:
2264                                 c = uppercase(c);
2265                                 break;
2266                         }
2267                 }
2268 #warning changes
2269                 par->setChar(pos, c);
2270                 checkParagraph(&bview, par, pos);
2271
2272                 ++pos;
2273         }
2274         if (to.row() != from.row()) {
2275                 refresh_y = from.y() - from.row()->baseline();
2276                 refresh_row = from.row();
2277                 status(&bview, LyXText::NEED_MORE_REFRESH);
2278         }
2279 }
2280
2281
2282 void LyXText::transposeChars(BufferView & bview)
2283 {
2284         Paragraph * tmppar = cursor.par();
2285
2286         setUndo(&bview, Undo::FINISH, tmppar, tmppar->next());
2287
2288         pos_type tmppos = cursor.pos();
2289
2290         // First decide if it is possible to transpose at all
2291  
2292         if (tmppos == 0 || tmppos == tmppar->size())
2293                 return;
2294
2295         if (isDeletedText(*tmppar, tmppos - 1)
2296                 || isDeletedText(*tmppar, tmppos))
2297                 return;
2298
2299         unsigned char c1 = tmppar->getChar(tmppos);
2300         unsigned char c2 = tmppar->getChar(tmppos - 1);
2301
2302         // We should have an implementation that handles insets
2303         // as well, but that will have to come later. (Lgb)
2304         if (c1 == Paragraph::META_INSET || c2 == Paragraph::META_INSET) 
2305                 return;
2306  
2307         bool const erased = tmppar->erase(tmppos - 1, tmppos + 1);
2308         pos_type const ipos(erased ? tmppos - 1 : tmppos + 1);
2309
2310         tmppar->insertChar(ipos, c1);
2311         tmppar->insertChar(ipos + 1, c2);
2312
2313         checkParagraph(&bview, tmppar, tmppos);
2314 }
2315
2316
2317 void LyXText::Delete(BufferView * bview)
2318 {
2319         // this is a very easy implementation
2320
2321         LyXCursor old_cursor = cursor;
2322         int const old_cur_par_id = old_cursor.par()->id();
2323         int const old_cur_par_prev_id = old_cursor.par()->previous() ?
2324                 old_cursor.par()->previous()->id() : -1;
2325
2326         // just move to the right
2327         cursorRight(bview);
2328
2329         // CHECK Look at the comment here.
2330         // This check is not very good...
2331         // The cursorRightIntern calls DeleteEmptyParagrapgMechanism
2332         // and that can very well delete the par or par->previous in
2333         // old_cursor. Will a solution where we compare paragraph id's
2334         //work better?
2335         if ((cursor.par()->previous() ? cursor.par()->previous()->id() : -1)
2336             == old_cur_par_prev_id
2337             && cursor.par()->id() != old_cur_par_id) {
2338                 // delete-empty-paragraph-mechanism has done it
2339                 return;
2340         }
2341
2342         // if you had success make a backspace
2343         if (old_cursor.par() != cursor.par() || old_cursor.pos() != cursor.pos()) {
2344                 LyXCursor tmpcursor = cursor;
2345                 // to make sure undo gets the right cursor position
2346                 cursor = old_cursor;
2347                 setUndo(bview, Undo::DELETE,
2348                         cursor.par(), cursor.par()->next());
2349                 cursor = tmpcursor;
2350                 backspace(bview);
2351         }
2352 }
2353
2354
2355 void LyXText::backspace(BufferView * bview)
2356 {
2357         // Get the font that is used to calculate the baselineskip
2358         pos_type lastpos = cursor.par()->size();
2359         LyXFont rawparfont =
2360                 cursor.par()->getFontSettings(bview->buffer()->params,
2361                                               lastpos - 1);
2362
2363         if (cursor.pos() == 0) {
2364                 // The cursor is at the beginning of a paragraph,
2365                 // so the the backspace will collapse two paragraphs into one.
2366
2367                 // but it's not allowed unless it's new
2368                 if (cursor.par()->isChangeEdited(0, cursor.par()->size()))
2369                         return;
2370  
2371                 // we may paste some paragraphs
2372
2373                 // is it an empty paragraph?
2374
2375                 if ((lastpos == 0
2376                      || (lastpos == 1 && cursor.par()->isSeparator(0)))) {
2377                         // This is an empty paragraph and we delete it just by moving the cursor one step
2378                         // left and let the DeleteEmptyParagraphMechanism handle the actual deletion
2379                         // of the paragraph.
2380
2381                         if (cursor.par()->previous()) {
2382                                 Paragraph * tmppar = cursor.par()->previous();
2383                                 if (cursor.par()->layout() == tmppar->layout()
2384                                     && cursor.par()->getAlign() == tmppar->getAlign()) {
2385                                         // Inherit bottom DTD from the paragraph below.
2386                                         // (the one we are deleting)
2387                                         tmppar->params().lineBottom(cursor.par()->params().lineBottom());
2388                                         tmppar->params().spaceBottom(cursor.par()->params().spaceBottom());
2389                                         tmppar->params().pagebreakBottom(cursor.par()->params().pagebreakBottom());
2390                                 }
2391
2392                                 cursorLeft(bview);
2393
2394                                 // the layout things can change the height of a row !
2395                                 int const tmpheight = cursor.row()->height();
2396                                 setHeightOfRow(bview, cursor.row());
2397                                 if (cursor.row()->height() != tmpheight) {
2398                                         refresh_y = cursor.y() - cursor.row()->baseline();
2399                                         refresh_row = cursor.row();
2400                                         status(bview, LyXText::NEED_MORE_REFRESH);
2401                                 }
2402                                 return;
2403                         }
2404                 }
2405
2406                 if (cursor.par()->previous()) {
2407                         setUndo(bview, Undo::DELETE,
2408                                 cursor.par()->previous(), cursor.par()->next());
2409                 }
2410
2411                 Paragraph * tmppar = cursor.par();
2412                 Row * tmprow = cursor.row();
2413
2414                 // We used to do cursorLeftIntern() here, but it is
2415                 // not a good idea since it triggers the auto-delete
2416                 // mechanism. So we do a cursorLeftIntern()-lite,
2417                 // without the dreaded mechanism. (JMarc)
2418                 if (cursor.par()->previous()) {
2419                         // steps into the above paragraph.
2420                         setCursorIntern(bview, cursor.par()->previous(),
2421                                         cursor.par()->previous()->size(),
2422                                         false);
2423                 }
2424
2425                 // Pasting is not allowed, if the paragraphs have different
2426                 // layout. I think it is a real bug of all other
2427                 // word processors to allow it. It confuses the user.
2428                 // Even so with a footnote paragraph and a non-footnote
2429                 // paragraph. I will not allow pasting in this case,
2430                 // because the user would be confused if the footnote behaves
2431                 // different wether it is open or closed.
2432
2433                 //      Correction: Pasting is always allowed with standard-layout
2434                 LyXTextClass const & tclass =
2435                         bview->buffer()->params.getLyXTextClass();
2436
2437                 if (cursor.par() != tmppar
2438                     && (cursor.par()->layout() == tmppar->layout()
2439                         || tmppar->layout() == tclass.defaultLayout())
2440                     && cursor.par()->getAlign() == tmppar->getAlign()) {
2441                         removeParagraph(tmprow);
2442                         removeRow(tmprow);
2443                         mergeParagraph(bview->buffer()->params, cursor.par());
2444
2445                         if (!cursor.pos() || !cursor.par()->isSeparator(cursor.pos() - 1))
2446                                 ; //cursor.par()->insertChar(cursor.pos(), ' ');
2447                         // strangely enough it seems that commenting out the line above removes
2448                         // most or all of the segfaults. I will however also try to move the
2449                         // two Remove... lines in front of the PasteParagraph too.
2450                         else
2451                                 if (cursor.pos())
2452                                         cursor.pos(cursor.pos() - 1);
2453
2454                         status(bview, LyXText::NEED_MORE_REFRESH);
2455                         refresh_row = cursor.row();
2456                         refresh_y = cursor.y() - cursor.row()->baseline();
2457
2458                         // remove the lost paragraph
2459                         // This one is not safe, since the paragraph that the tmprow and the
2460                         // following rows belong to has been deleted by the PasteParagraph
2461                         // above. The question is... could this be moved in front of the
2462                         // PasteParagraph?
2463                         //RemoveParagraph(tmprow);
2464                         //RemoveRow(tmprow);
2465
2466                         // This rebuilds the rows.
2467                         appendParagraph(bview, cursor.row());
2468                         updateCounters(bview);
2469
2470                         // the row may have changed, block, hfills etc.
2471                         setCursor(bview, cursor.par(), cursor.pos(), false);
2472                 }
2473         } else {
2474                 // this is the code for a normal backspace, not pasting
2475                 // any paragraphs
2476                 setUndo(bview, Undo::DELETE,
2477                         cursor.par(), cursor.par()->next());
2478                 // We used to do cursorLeftIntern() here, but it is
2479                 // not a good idea since it triggers the auto-delete
2480                 // mechanism. So we do a cursorLeftIntern()-lite,
2481                 // without the dreaded mechanism. (JMarc)
2482                 setCursorIntern(bview, cursor.par(), cursor.pos()- 1,
2483                                 false, cursor.boundary());
2484
2485                 if (cursor.par()->isInset(cursor.pos())) {
2486                         // force complete redo when erasing display insets
2487                         // this is a cruel method but safe..... Matthias
2488                         if (cursor.par()->getInset(cursor.pos())->display() ||
2489                             cursor.par()->getInset(cursor.pos())->needFullRow()) {
2490                                 cursor.par()->erase(cursor.pos());
2491                                 redoParagraph(bview);
2492                                 return;
2493                         }
2494                 }
2495
2496                 Row * row = cursor.row();
2497                 int y = cursor.y() - row->baseline();
2498                 pos_type z;
2499                 // remember that a space at the end of a row doesnt count
2500                 // when calculating the fill
2501                 if (cursor.pos() < row->lastPos() ||
2502                     !cursor.par()->isLineSeparator(cursor.pos())) {
2503                         row->fill(row->fill() + singleWidth(bview,
2504                                                             cursor.par(),
2505                                                             cursor.pos()));
2506                 }
2507
2508                 // some special code when deleting a newline. This is similar
2509                 // to the behavior when pasting paragraphs
2510                 if (cursor.pos() && cursor.par()->isNewline(cursor.pos())) {
2511                         cursor.par()->erase(cursor.pos());
2512                         // refresh the positions
2513                         Row * tmprow = row;
2514                         while (tmprow->next() && tmprow->next()->par() == row->par()) {
2515                                 tmprow = tmprow->next();
2516                                 tmprow->pos(tmprow->pos() - 1);
2517                         }
2518                         if (cursor.par()->isLineSeparator(cursor.pos() - 1))
2519                                 cursor.pos(cursor.pos() - 1);
2520
2521                         if (cursor.pos() < cursor.par()->size()
2522                             && !cursor.par()->isSeparator(cursor.pos())) {
2523                                 cursor.par()->insertChar(cursor.pos(), ' ');
2524                                 setCharFont(bview->buffer(), cursor.par(),
2525                                             cursor.pos(), current_font);
2526                                 // refresh the positions
2527                                 tmprow = row;
2528                                 while (tmprow->next() && tmprow->next()->par() == row->par()) {
2529                                         tmprow = tmprow->next();
2530                                         tmprow->pos(tmprow->pos() + 1);
2531                                 }
2532                         }
2533                 } else {
2534                         cursor.par()->erase(cursor.pos());
2535
2536                         // refresh the positions
2537                         Row * tmprow = row;
2538                         while (tmprow->next()
2539                                && tmprow->next()->par() == row->par()) {
2540                                 tmprow = tmprow->next();
2541                                 tmprow->pos(tmprow->pos() - 1);
2542                         }
2543
2544                         // delete newlines at the beginning of paragraphs
2545                         while (!cursor.par()->empty() &&
2546                                cursor.par()->isNewline(cursor.pos()) &&
2547                                cursor.pos() == cursor.par()->beginningOfMainBody()) {
2548                                 cursor.par()->erase(cursor.pos());
2549                                 // refresh the positions
2550                                 tmprow = row;
2551                                 while (tmprow->next() &&
2552                                        tmprow->next()->par() == row->par()) {
2553                                         tmprow = tmprow->next();
2554                                         tmprow->pos(tmprow->pos() - 1);
2555                                 }
2556                         }
2557                 }
2558
2559                 // is there a break one row above
2560                 if (row->previous() && row->previous()->par() == row->par()) {
2561                         z = nextBreakPoint(bview, row->previous(),
2562                                            workWidth(*bview));
2563                         if (z >= row->pos()) {
2564                                 row->pos(z + 1);
2565
2566                                 Row * tmprow = row->previous();
2567
2568                                 // maybe the current row is now empty
2569                                 if (row->pos() >= row->par()->size()) {
2570                                         // remove it
2571                                         removeRow(row);
2572                                         need_break_row = 0;
2573                                 } else {
2574                                         breakAgainOneRow(bview, row);
2575                                         if (row->next() && row->next()->par() == row->par())
2576                                                 need_break_row = row->next();
2577                                         else
2578                                                 need_break_row = 0;
2579                                 }
2580
2581                                 // set the dimensions of the row above
2582                                 y -= tmprow->height();
2583                                 tmprow->fill(fill(*bview, *tmprow, workWidth(*bview)));
2584                                 setHeightOfRow(bview, tmprow);
2585
2586                                 refresh_y = y;
2587                                 refresh_row = tmprow;
2588                                 status(bview, LyXText::NEED_MORE_REFRESH);
2589                                 setCursor(bview, cursor.par(), cursor.pos(),
2590                                           false, cursor.boundary());
2591                                 //current_font = rawtmpfont;
2592                                 //real_current_font = realtmpfont;
2593                                 // check, whether the last character's font has changed.
2594                                 if (rawparfont !=
2595                                     cursor.par()->getFontSettings(bview->buffer()->params,
2596                                                                   cursor.par()->size() - 1))
2597                                         redoHeightOfParagraph(bview, cursor);
2598                                 return;
2599                         }
2600                 }
2601
2602                 // break the cursor row again
2603                 if (row->next() && row->next()->par() == row->par() &&
2604                     (row->lastPos() == row->par()->size() - 1 ||
2605                      nextBreakPoint(bview, row, workWidth(*bview)) != row->lastPos())) {
2606
2607                         // it can happen that a paragraph loses one row
2608                         // without a real breakup. This is when a word
2609                         // is to long to be broken. Well, I don t care this
2610                         // hack ;-)
2611                         if (row->lastPos() == row->par()->size() - 1)
2612                                 removeRow(row->next());
2613
2614                         refresh_y = y;
2615                         refresh_row = row;
2616                         status(bview, LyXText::NEED_MORE_REFRESH);
2617
2618                         breakAgainOneRow(bview, row);
2619                         // will the cursor be in another row now?
2620                         if (row->next() && row->next()->par() == row->par() &&
2621                             row->lastPos() <= cursor.pos()) {
2622                                 row = row->next();
2623                                 breakAgainOneRow(bview, row);
2624                         }
2625
2626                         setCursor(bview, cursor.par(), cursor.pos(), false, cursor.boundary());
2627
2628                         if (row->next() && row->next()->par() == row->par())
2629                                 need_break_row = row->next();
2630                         else
2631                                 need_break_row = 0;
2632                 } else  {
2633                         // set the dimensions of the row
2634                         row->fill(fill(*bview, *row, workWidth(*bview)));
2635                         int const tmpheight = row->height();
2636                         setHeightOfRow(bview, row);
2637                         if (tmpheight == row->height())
2638                                 status(bview, LyXText::NEED_VERY_LITTLE_REFRESH);
2639                         else
2640                                 status(bview, LyXText::NEED_MORE_REFRESH);
2641                         refresh_y = y;
2642                         refresh_row = row;
2643                         setCursor(bview, cursor.par(), cursor.pos(), false, cursor.boundary());
2644                 }
2645         }
2646
2647         // current_font = rawtmpfont;
2648         // real_current_font = realtmpfont;
2649
2650         if (isBoundary(bview->buffer(), cursor.par(), cursor.pos())
2651             != cursor.boundary())
2652                 setCursor(bview, cursor.par(), cursor.pos(), false,
2653                           !cursor.boundary());
2654
2655         lastpos = cursor.par()->size();
2656         if (cursor.pos() == lastpos)
2657                 setCurrentFont(bview);
2658
2659         // check, whether the last characters font has changed.
2660         if (rawparfont !=
2661             cursor.par()->getFontSettings(bview->buffer()->params, lastpos - 1)) {
2662                 redoHeightOfParagraph(bview, cursor);
2663         } else {
2664                 // now the special right address boxes
2665                 if (cursor.par()->layout()->margintype
2666                     == MARGIN_RIGHT_ADDRESS_BOX) {
2667                         redoDrawingOfParagraph(bview, cursor);
2668                 }
2669         }
2670 }
2671
2672
2673 // returns the column near the specified x-coordinate of the row
2674 // x is set to the real beginning of this column
2675 pos_type
2676 LyXText::getColumnNearX(BufferView * bview, Row * row, int & x,
2677                         bool & boundary) const
2678 {
2679         float tmpx = 0.0;
2680         float fill_separator;
2681         float fill_hfill;
2682         float fill_label_hfill;
2683
2684         prepareToPrint(bview, row, tmpx, fill_separator,
2685                        fill_hfill, fill_label_hfill);
2686
2687         pos_type vc = row->pos();
2688         pos_type last = row->lastPrintablePos();
2689         pos_type c = 0;
2690
2691         LyXLayout_ptr const & layout = row->par()->layout();
2692
2693         bool left_side = false;
2694
2695         pos_type main_body = row->par()->beginningOfMainBody();
2696         float last_tmpx = tmpx;
2697
2698         if (main_body > 0 &&
2699             (main_body - 1 > last ||
2700              !row->par()->isLineSeparator(main_body - 1)))
2701                 main_body = 0;
2702
2703         // check for empty row
2704         if (!row->par()->size()) {
2705                 x = int(tmpx);
2706                 return 0;
2707         }
2708  
2709         while (vc <= last && tmpx <= x) {
2710                 c = vis2log(vc);
2711                 last_tmpx = tmpx;
2712                 if (main_body > 0 && c == main_body-1) {
2713                         tmpx += fill_label_hfill +
2714                                 font_metrics::width(layout->labelsep,
2715                                                getLabelFont(bview->buffer(), row->par()));
2716                         if (row->par()->isLineSeparator(main_body - 1))
2717                                 tmpx -= singleWidth(bview, row->par(), main_body-1);
2718                 }
2719
2720                 if (row->hfillExpansion(c)) {
2721                         tmpx += singleWidth(bview, row->par(), c);
2722                         if (c >= main_body)
2723                                 tmpx += fill_hfill;
2724                         else
2725                                 tmpx += fill_label_hfill;
2726                 } else if (row->par()->isSeparator(c)) {
2727                         tmpx += singleWidth(bview, row->par(), c);
2728                         if (c >= main_body)
2729                                 tmpx+= fill_separator;
2730                 } else {
2731                         tmpx += singleWidth(bview, row->par(), c);
2732                 }
2733                 ++vc;
2734         }
2735
2736         if ((tmpx + last_tmpx) / 2 > x) {
2737                 tmpx = last_tmpx;
2738                 left_side = true;
2739         }
2740
2741         if (vc > last + 1)  // This shouldn't happen.
2742                 vc = last + 1;
2743
2744         boundary = false;
2745         bool const lastrow = lyxrc.rtl_support // This is not needed, but gives
2746                                          // some speedup if rtl_support=false
2747                 && (!row->next() || row->next()->par() != row->par());
2748         bool const rtl = (lastrow)
2749                 ? row->par()->isRightToLeftPar(bview->buffer()->params)
2750                 : false; // If lastrow is false, we don't need to compute
2751                          // the value of rtl.
2752
2753         if (lastrow &&
2754                  ((rtl &&  left_side && vc == row->pos() && x < tmpx - 5) ||
2755                    (!rtl && !left_side && vc == last + 1   && x > tmpx + 5)))
2756                 c = last + 1;
2757         else if (vc == row->pos()) {
2758                 c = vis2log(vc);
2759                 if (bidi_level(c) % 2 == 1)
2760                         ++c;
2761         } else {
2762                 c = vis2log(vc - 1);
2763                 bool const rtl = (bidi_level(c) % 2 == 1);
2764                 if (left_side == rtl) {
2765                         ++c;
2766                         boundary = isBoundary(bview->buffer(), row->par(), c);
2767                 }
2768         }
2769
2770         if (row->pos() <= last && c > last
2771             && row->par()->isNewline(last)) {
2772                 if (bidi_level(last) % 2 == 0)
2773                         tmpx -= singleWidth(bview, row->par(), last);
2774                 else
2775                         tmpx += singleWidth(bview, row->par(), last);
2776                 c = last;
2777         }
2778
2779         c -= row->pos();
2780         x = int(tmpx);
2781         return c;
2782 }
2783
2784
2785 // returns pointer to a specified row
2786 Row * LyXText::getRow(Paragraph * par, pos_type pos, int & y) const
2787 {
2788         if (!firstrow)
2789                 return 0;
2790
2791         Row * tmprow = firstrow;
2792         y = 0;
2793
2794         // find the first row of the specified paragraph
2795         while (tmprow->next() && tmprow->par() != par) {
2796                 y += tmprow->height();
2797                 tmprow = tmprow->next();
2798         }
2799
2800         // now find the wanted row
2801         while (tmprow->pos() < pos
2802                && tmprow->next()
2803                && tmprow->next()->par() == par
2804                && tmprow->next()->pos() <= pos) {
2805                 y += tmprow->height();
2806                 tmprow = tmprow->next();
2807         }
2808
2809         return tmprow;
2810 }
2811
2812
2813 Row * LyXText::getRowNearY(int & y) const
2814 {
2815 #if 1
2816         // If possible we should optimize this method. (Lgb)
2817         Row * tmprow = firstrow;
2818         int tmpy = 0;
2819
2820         while (tmprow->next() && tmpy + tmprow->height() <= y) {
2821                 tmpy += tmprow->height();
2822                 tmprow = tmprow->next();
2823         }
2824
2825         y = tmpy;   // return the real y
2826
2827         //lyxerr << "returned y = " << y << endl;
2828
2829         return tmprow;
2830 #else
2831         // Search from the current cursor position.
2832
2833         Row * tmprow = cursor.row();
2834         int tmpy = cursor.y() - tmprow->baseline();
2835
2836         lyxerr << "cursor.y() = " << tmpy << endl;
2837         lyxerr << "tmprow->height() = " << tmprow->height() << endl;
2838         lyxerr << "tmprow->baseline() = " << tmprow->baseline() << endl;
2839         lyxerr << "first = " << first << endl;
2840         lyxerr << "y = " << y << endl;
2841
2842         if (y < tmpy) {
2843                 lyxerr << "up" << endl;
2844                 do {
2845                         tmpy -= tmprow->height();
2846                         tmprow = tmprow->previous();
2847                 } while (tmprow && tmpy - tmprow->height() >= y);
2848         } else if (y > tmpy) {
2849                 lyxerr << "down" << endl;
2850
2851                 while (tmprow->next() && tmpy + tmprow->height() <= y) {
2852                         tmpy += tmprow->height();
2853                         tmprow = tmprow->next();
2854                 }
2855         } else {
2856                 lyxerr << "equal" << endl;
2857         }
2858
2859         y = tmpy; // return the real y
2860
2861         lyxerr << "returned y = " << y << endl;
2862
2863         return tmprow;
2864
2865 #endif
2866 }
2867
2868
2869 int LyXText::getDepth() const
2870 {
2871         return cursor.par()->getDepth();
2872 }