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