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