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