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