]> git.lyx.org Git - lyx.git/blob - src/text.C
set fill in fill(...) istead of returning it.
[lyx.git] / src / text.C
1 /**
2  * \file src/text.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Asger Alstrup
7  * \author Lars Gullik Bjønnes
8  * \author Jean-Marc Lasgouttes
9  * \author John Levon
10  * \author André Pönitz
11  * \author Dekel Tsur
12  * \author Jürgen Vigna
13  *
14  * Full author contact details are available in file CREDITS.
15  */
16
17 #include <config.h>
18
19 #include "lyxtext.h"
20
21 #include "buffer.h"
22 #include "bufferparams.h"
23 #include "BufferView.h"
24 #include "debug.h"
25 #include "encoding.h"
26 #include "funcrequest.h"
27 #include "gettext.h"
28 #include "language.h"
29 #include "LColor.h"
30 #include "lyxlength.h"
31 #include "lyxrc.h"
32 #include "lyxrow.h"
33 #include "lyxrow_funcs.h"
34 #include "metricsinfo.h"
35 #include "paragraph.h"
36 #include "paragraph_funcs.h"
37 #include "ParagraphParameters.h"
38 #include "rowpainter.h"
39 #include "text_funcs.h"
40 #include "undo.h"
41 #include "vspace.h"
42 #include "WordLangTuple.h"
43
44 #include "frontends/font_metrics.h"
45 #include "frontends/LyXView.h"
46
47 #include "insets/insettext.h"
48
49 #include "support/lstrings.h"
50 #include "support/textutils.h"
51
52 using bv_funcs::number;
53
54 using lyx::pos_type;
55 using lyx::word_location;
56
57 using lyx::support::contains;
58 using lyx::support::lowercase;
59 using lyx::support::uppercase;
60
61 using std::max;
62 using std::endl;
63 using std::string;
64
65
66 /// top, right, bottom pixel margin
67 extern int const PAPER_MARGIN = 20;
68 /// margin for changebar
69 extern int const CHANGEBAR_MARGIN = 10;
70 /// left margin
71 extern int const LEFT_MARGIN = PAPER_MARGIN + CHANGEBAR_MARGIN;
72
73
74
75 int bibitemMaxWidth(BufferView *, LyXFont const &);
76
77
78 namespace {
79
80 unsigned int maxParagraphWidth(ParagraphList const & plist)
81 {
82         unsigned int width = 0;
83         ParagraphList::const_iterator pit = plist.begin();
84         ParagraphList::const_iterator end = plist.end();
85                 for (; pit != end; ++pit)
86                         width = std::max(width, pit->width);
87         return width;
88 }
89
90 } // namespace anon
91
92
93 BufferView * LyXText::bv()
94 {
95         BOOST_ASSERT(bv_owner != 0);
96         return bv_owner;
97 }
98
99
100 BufferView * LyXText::bv() const
101 {
102         BOOST_ASSERT(bv_owner != 0);
103         return bv_owner;
104 }
105
106
107 void LyXText::updateRowPositions()
108 {
109         ParagraphList::iterator pit = ownerParagraphs().begin();
110         ParagraphList::iterator end = ownerParagraphs().end();
111         for (height = 0; pit != end; ++pit) {
112                 pit->y = height;
113                 height += pit->height;
114         }
115 }
116
117
118 int LyXText::workWidth() const
119 {
120         return inset_owner ? inset_owner->textWidth() : bv()->workWidth();
121 }
122
123
124 int LyXText::getRealCursorX() const
125 {
126         int x = cursor.x();
127         if (the_locking_inset && the_locking_inset->getLyXText(bv()) != this)
128                 x = the_locking_inset->getLyXText(bv())->getRealCursorX();
129         return x;
130 }
131
132
133 #warning FIXME  This function seems to belong outside of LyxText.
134 unsigned char LyXText::transformChar(unsigned char c, Paragraph const & par,
135                                      pos_type pos) const
136 {
137         if (!Encodings::is_arabic(c))
138                 if (lyxrc.font_norm_type == LyXRC::ISO_8859_6_8 && IsDigit(c))
139                         return c + (0xb0 - '0');
140                 else
141                         return c;
142
143         unsigned char const prev_char = pos > 0 ? par.getChar(pos - 1) : ' ';
144         unsigned char next_char = ' ';
145
146         pos_type const par_size = par.size();
147
148         for (pos_type i = pos + 1; i < par_size; ++i) {
149                 unsigned char const par_char = par.getChar(i);
150                 if (!Encodings::IsComposeChar_arabic(par_char)) {
151                         next_char = par_char;
152                         break;
153                 }
154         }
155
156         if (Encodings::is_arabic(next_char)) {
157                 if (Encodings::is_arabic(prev_char) &&
158                         !Encodings::is_arabic_special(prev_char))
159                         return Encodings::TransformChar(c, Encodings::FORM_MEDIAL);
160                 else
161                         return Encodings::TransformChar(c, Encodings::FORM_INITIAL);
162         } else {
163                 if (Encodings::is_arabic(prev_char) &&
164                         !Encodings::is_arabic_special(prev_char))
165                         return Encodings::TransformChar(c, Encodings::FORM_FINAL);
166                 else
167                         return Encodings::TransformChar(c, Encodings::FORM_ISOLATED);
168         }
169 }
170
171 // This is the comments that some of the warnings below refers to.
172 // There are some issues in this file and I don't think they are
173 // really related to the FIX_DOUBLE_SPACE patch. I'd rather think that
174 // this is a problem that has been here almost from day one and that a
175 // larger userbase with different access patters triggers the bad
176 // behaviour. (segfaults.) What I think happen is: In several places
177 // we store the paragraph in the current cursor and then moves the
178 // cursor. This movement of the cursor will delete paragraph at the
179 // old position if it is now empty. This will make the temporary
180 // pointer to the old cursor paragraph invalid and dangerous to use.
181 // And is some cases this will trigger a segfault. I have marked some
182 // of the cases where this happens with a warning, but I am sure there
183 // are others in this file and in text2.C. There is also a note in
184 // Delete() that you should read. In Delete I store the paragraph->id
185 // instead of a pointer to the paragraph. I am pretty sure this faulty
186 // use of temporary pointers to paragraphs that might have gotten
187 // invalidated (through a cursor movement) before they are used, are
188 // the cause of the strange crashes we get reported often.
189 //
190 // It is very tiresom to change this code, especially when it is as
191 // hard to read as it is. Help to fix all the cases where this is done
192 // would be greately appreciated.
193 //
194 // Lgb
195
196 int LyXText::singleWidth(ParagraphList::iterator pit, pos_type pos) const
197 {
198         if (pos >= pit->size())
199                 return 0;
200
201         char const c = pit->getChar(pos);
202         LyXFont const & font = getFont(pit, pos);
203         return singleWidth(pit, pos, c, font);
204 }
205
206
207 int LyXText::singleWidth(ParagraphList::iterator pit,
208                          pos_type pos, char c, LyXFont const & font) const
209 {
210         if (pos >= pit->size()) {
211                 lyxerr << "in singleWidth(), pos: " << pos << endl;
212                 BOOST_ASSERT(false);
213                 return 0;
214         }
215
216
217         // The most common case is handled first (Asger)
218         if (IsPrintable(c)) {
219                 if (!font.language()->RightToLeft()) {
220                         if ((lyxrc.font_norm_type == LyXRC::ISO_8859_6_8 ||
221                              lyxrc.font_norm_type == LyXRC::ISO_10646_1)
222                             && font.language()->lang() == "arabic") {
223                                 if (Encodings::IsComposeChar_arabic(c))
224                                         return 0;
225                                 else
226                                         c = transformChar(c, *pit, pos);
227                         } else if (font.language()->lang() == "hebrew" &&
228                                  Encodings::IsComposeChar_hebrew(c))
229                                 return 0;
230                 }
231                 return font_metrics::width(c, font);
232         }
233
234         if (c == Paragraph::META_INSET) {
235                 InsetOld * tmpinset = pit->getInset(pos);
236                 BOOST_ASSERT(tmpinset);
237                 if (tmpinset->lyxCode() == InsetOld::HFILL_CODE) {
238                         // Because of the representation as vertical lines
239                         return 3;
240                 }
241                 return tmpinset->width();
242         }
243
244         if (IsSeparatorChar(c))
245                 c = ' ';
246         return font_metrics::width(c, font);
247 }
248
249
250 int LyXText::leftMargin(ParagraphList::iterator pit, Row const & row) const
251 {
252         LyXTextClass const & tclass =
253                 bv()->buffer()->params().getLyXTextClass();
254         LyXLayout_ptr const & layout = pit->layout();
255
256         string parindent = layout->parindent;
257
258         int x = LEFT_MARGIN;
259
260         x += font_metrics::signedWidth(tclass.leftmargin(), tclass.defaultfont());
261
262         // this is the way, LyX handles the LaTeX-Environments.
263         // I have had this idea very late, so it seems to be a
264         // later added hack and this is true
265         if (!pit->getDepth()) {
266                 if (pit->layout() == tclass.defaultLayout()) {
267                         // find the previous same level paragraph
268                         if (pit != ownerParagraphs().begin()) {
269                                 ParagraphList::iterator newpit =
270                                         depthHook(pit, ownerParagraphs(),
271                                                   pit->getDepth());
272                                 if (newpit == pit &&
273                                     newpit->layout()->nextnoindent)
274                                         parindent.erase();
275                         }
276                 }
277         } else {
278                 // find the next level paragraph
279
280                 ParagraphList::iterator newpar = outerHook(pit,
281                                                            ownerParagraphs());
282
283                 // make a corresponding row. Needed to call leftMargin()
284
285                 // check wether it is a sufficent paragraph
286                 if (newpar != ownerParagraphs().end() &&
287                     newpar->layout()->isEnvironment()) {
288                         x = leftMargin(newpar, Row(newpar->size()));
289                 }
290
291                 if (newpar != ownerParagraphs().end() &&
292                     pit->layout() == tclass.defaultLayout()) {
293                         if (newpar->params().noindent())
294                                 parindent.erase();
295                         else {
296                                 parindent = newpar->layout()->parindent;
297                         }
298
299                 }
300         }
301
302         LyXFont const labelfont = getLabelFont(pit);
303         switch (layout->margintype) {
304         case MARGIN_DYNAMIC:
305                 if (!layout->leftmargin.empty()) {
306                         x += font_metrics::signedWidth(layout->leftmargin,
307                                                   tclass.defaultfont());
308                 }
309                 if (!pit->getLabelstring().empty()) {
310                         x += font_metrics::signedWidth(layout->labelindent,
311                                                   labelfont);
312                         x += font_metrics::width(pit->getLabelstring(),
313                                             labelfont);
314                         x += font_metrics::width(layout->labelsep, labelfont);
315                 }
316                 break;
317         case MARGIN_MANUAL:
318                 x += font_metrics::signedWidth(layout->labelindent, labelfont);
319                 // The width of an empty par, even with manual label, should be 0
320                 if (!pit->empty() && row.pos() >= pit->beginningOfBody()) {
321                         if (!pit->getLabelWidthString().empty()) {
322                                 x += font_metrics::width(pit->getLabelWidthString(),
323                                                labelfont);
324                                 x += font_metrics::width(layout->labelsep, labelfont);
325                         }
326                 }
327                 break;
328         case MARGIN_STATIC:
329                 x += font_metrics::signedWidth(layout->leftmargin, tclass.defaultfont()) * 4
330                         / (pit->getDepth() + 4);
331                 break;
332         case MARGIN_FIRST_DYNAMIC:
333                 if (layout->labeltype == LABEL_MANUAL) {
334                         if (row.pos() >= pit->beginningOfBody()) {
335                                 x += font_metrics::signedWidth(layout->leftmargin,
336                                                           labelfont);
337                         } else {
338                                 x += font_metrics::signedWidth(layout->labelindent,
339                                                           labelfont);
340                         }
341                 } else if (row.pos()
342                            // Special case to fix problems with
343                            // theorems (JMarc)
344                            || (layout->labeltype == LABEL_STATIC
345                                && layout->latextype == LATEX_ENVIRONMENT
346                                && !isFirstInSequence(pit, ownerParagraphs()))) {
347                         x += font_metrics::signedWidth(layout->leftmargin,
348                                                   labelfont);
349                 } else if (layout->labeltype != LABEL_TOP_ENVIRONMENT
350                            && layout->labeltype != LABEL_BIBLIO
351                            && layout->labeltype !=
352                            LABEL_CENTERED_TOP_ENVIRONMENT) {
353                         x += font_metrics::signedWidth(layout->labelindent,
354                                                   labelfont);
355                         x += font_metrics::width(layout->labelsep, labelfont);
356                         x += font_metrics::width(pit->getLabelstring(),
357                                             labelfont);
358                 }
359                 break;
360
361         case MARGIN_RIGHT_ADDRESS_BOX:
362         {
363                 // ok, a terrible hack. The left margin depends on the widest
364                 // row in this paragraph.
365                 RowList::iterator rit = pit->rows.begin();
366                 RowList::iterator end = pit->rows.end();
367                 int minfill = rit->fill();
368                 for ( ; rit != end; ++rit)
369                         if (rit->fill() < minfill)
370                                 minfill = rit->fill();
371
372                 x += font_metrics::signedWidth(layout->leftmargin,
373                         tclass.defaultfont());
374                 x += minfill;
375         }
376         break;
377         }
378
379         if (workWidth() > 0 && !pit->params().leftIndent().zero()) {
380                 LyXLength const len = pit->params().leftIndent();
381                 int const tw = inset_owner ?
382                         inset_owner->latexTextWidth(bv()) : workWidth();
383                 x += len.inPixels(tw);
384         }
385
386         LyXAlignment align;
387
388         if (pit->params().align() == LYX_ALIGN_LAYOUT)
389                 align = layout->align;
390         else
391                 align = pit->params().align();
392
393         // set the correct parindent
394         if (row.pos() == 0) {
395                 if ((layout->labeltype == LABEL_NO_LABEL
396                      || layout->labeltype == LABEL_TOP_ENVIRONMENT
397                      || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
398                      || (layout->labeltype == LABEL_STATIC
399                          && layout->latextype == LATEX_ENVIRONMENT
400                          && !isFirstInSequence(pit, ownerParagraphs())))
401                     && align == LYX_ALIGN_BLOCK
402                     && !pit->params().noindent()
403                         // in tabulars and ert paragraphs are never indented!
404                         && (!pit->inInset() || !pit->inInset()->owner() ||
405                                 (pit->inInset()->owner()->lyxCode() != InsetOld::TABULAR_CODE &&
406                                  pit->inInset()->owner()->lyxCode() != InsetOld::ERT_CODE))
407                     && (pit->layout() != tclass.defaultLayout() ||
408                         bv()->buffer()->params().paragraph_separation ==
409                         BufferParams::PARSEP_INDENT)) {
410                         x += font_metrics::signedWidth(parindent,
411                                                   tclass.defaultfont());
412                 } else if (layout->labeltype == LABEL_BIBLIO) {
413                         // ale970405 Right width for bibitems
414                         x += bibitemMaxWidth(bv(), tclass.defaultfont());
415                 }
416         }
417
418         return x;
419 }
420
421
422 int LyXText::rightMargin(Paragraph const & par,
423         Buffer const & buf, Row const &) const
424 {
425         LyXTextClass const & tclass = buf.params().getLyXTextClass();
426         LyXLayout_ptr const & layout = par.layout();
427
428         return PAPER_MARGIN
429                 + font_metrics::signedWidth(tclass.rightmargin(),
430                                        tclass.defaultfont())
431                 + font_metrics::signedWidth(layout->rightmargin,
432                                        tclass.defaultfont())
433                 * 4 / (par.getDepth() + 4);
434 }
435
436
437 int LyXText::labelEnd(ParagraphList::iterator pit, Row const & row) const
438 {
439         if (pit->layout()->margintype == MARGIN_MANUAL) {
440                 Row tmprow = row;
441                 tmprow.pos(pit->size());
442                 // return the beginning of the body
443                 return leftMargin(pit, tmprow);
444         }
445
446         // LabelEnd is only needed if the layout
447         // fills a flushleft label.
448         return 0;
449 }
450
451
452 namespace {
453
454 // this needs special handling - only newlines count as a break point
455 pos_type addressBreakPoint(pos_type i, Paragraph const & par)
456 {
457         for (; i < par.size(); ++i)
458                 if (par.isNewline(i))
459                         return i;
460
461         return par.size();
462 }
463
464 };
465
466
467 void LyXText::rowBreakPoint(ParagraphList::iterator pit, Row & row) const
468 {
469         // maximum pixel width of a row.
470         int width = workWidth() - rightMargin(*pit, *bv()->buffer(), row);
471
472         // inset->textWidth() returns -1 via workWidth(),
473         // but why ?
474         if (width < 0) {
475                 row.endpos(pit->size() + 1);
476                 return;
477         }
478
479         LyXLayout_ptr const & layout = pit->layout();
480
481         if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX) {
482                 row.endpos(addressBreakPoint(row.pos(), *pit) + 1);
483                 return;
484         }
485
486         pos_type const pos = row.pos();
487         pos_type const body_pos = pit->beginningOfBody();
488         pos_type const last = pit->size();
489         pos_type point = last;
490
491         if (pos == last) {
492                 row.endpos(last + 1);
493                 return;
494         }
495
496         // Now we iterate through until we reach the right margin
497         // or the end of the par, then choose the possible break
498         // nearest that.
499
500         int const left = leftMargin(pit, row);
501         int x = left;
502
503         // pixel width since last breakpoint
504         int chunkwidth = 0;
505
506         pos_type i = pos;
507
508         // We re-use the font resolution for the entire font span when possible
509         LyXFont font = getFont(pit, i);
510         lyx::pos_type endPosOfFontSpan = pit->getEndPosOfFontSpan(i);
511
512         for (; i < last; ++i) {
513                 if (pit->isNewline(i)) {
514                         point = i;
515                         break;
516                 }
517                 // Break before...      
518                 if (i + 1 < last) {
519                         InsetOld * in = pit->getInset(i + 1);
520                         if (in && in->display()) {
521                                 point = i;
522                                 break;
523                         }
524                         // ...and after.
525                         in = pit->getInset(i);
526                         if (in && in->display()) {
527                                 point = i;
528                                 break;
529                         }
530                 }
531
532                 char const c = pit->getChar(i);
533                 if (i > endPosOfFontSpan) {
534                         font = getFont(pit, i);
535                         endPosOfFontSpan = pit->getEndPosOfFontSpan(i);
536                 }
537
538                 int thiswidth;
539
540                 // add the auto-hfill from label end to the body
541                 if (body_pos && i == body_pos) {
542                         thiswidth = font_metrics::width(layout->labelsep, getLabelFont(pit));
543                         if (pit->isLineSeparator(i - 1))
544                                 thiswidth -= singleWidth(pit, i - 1);
545                         int left_margin = labelEnd(pit, row);
546                         if (thiswidth + x < left_margin)
547                                 thiswidth = left_margin - x;
548                         thiswidth += singleWidth(pit, i, c, font);
549                 } else {
550                         thiswidth = singleWidth(pit, i, c, font);
551                 }
552
553                 x += thiswidth;
554                 //lyxerr << "i: " << i << " x: " << x << " width: " << width << endl;
555                 chunkwidth += thiswidth;
556
557                 // break before a character that will fall off
558                 // the right of the row
559                 if (x >= width) {
560                         // if no break before, break here
561                         if (point == last || chunkwidth >= width - left) {
562                                 if (pos < i) {
563                                         point = i - 1;
564                                         // exit on last registered breakpoint:
565                                         break;  
566                                 }
567                         }
568                         // emergency exit:
569                         if (i + 1 < last)               
570                                 break;  
571                 }
572
573                 InsetOld * in = pit->getInset(i);
574                 if (!in || in->isChar()) {
575                         // some insets are line separators too
576                         if (pit->isLineSeparator(i)) {
577                                 // register breakpoint:
578                                 point = i; 
579                                 chunkwidth = 0;
580                         }
581                 }
582         }
583
584         if (point == last && x >= width) {
585                 // didn't find one, break at the point we reached the edge
586                 point = i;
587         } else if (i == last && x < width) {
588                 // found one, but we fell off the end of the par, so prefer
589                 // that.
590                 point = last;
591         }
592
593         // manual labels cannot be broken in LaTeX. But we
594         // want to make our on-screen rendering of footnotes
595         // etc. still break
596         if (body_pos && point < body_pos)
597                 point = body_pos - 1;
598
599         row.endpos(point + 1);
600 }
601
602
603 // returns the minimum space a row needs on the screen in pixel
604 void LyXText::fill(ParagraphList::iterator pit, Row & row, int paper_width) const
605 {
606         int w;
607         // get the pure distance
608         pos_type const last = lastPos(*pit, row);
609
610         LyXLayout_ptr const & layout = pit->layout();
611
612         // special handling of the right address boxes
613         if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX) {
614                 int const tmpfill = row.fill();
615                 row.fill(0); // the minfill in leftMargin()
616                 w = leftMargin(pit, row);
617                 row.fill(tmpfill);
618         } else {
619                 w = leftMargin(pit, row);
620         }
621
622         pos_type const body_pos = pit->beginningOfBody();
623         pos_type i = row.pos();
624
625         if (! pit->empty() && i <= last) {
626                 // We re-use the font resolution for the entire span when possible
627                 LyXFont font = getFont(pit, i);
628                 lyx::pos_type endPosOfFontSpan = pit->getEndPosOfFontSpan(i);
629                 while (i <= last) {
630                         if (body_pos > 0 && i == body_pos) {
631                                 w += font_metrics::width(layout->labelsep, getLabelFont(pit));
632                                 if (pit->isLineSeparator(i - 1))
633                                         w -= singleWidth(pit, i - 1);
634                                 int left_margin = labelEnd(pit, row);
635                                 if (w < left_margin)
636                                         w = left_margin;
637                         }
638                         char const c = pit->getChar(i);
639                         if (IsPrintable(c) && i > endPosOfFontSpan) {
640                                 // We need to get the next font
641                                 font = getFont(pit, i);
642                                 endPosOfFontSpan = pit->getEndPosOfFontSpan(i);
643                         }
644                         w += singleWidth(pit, i, c, font);
645                         ++i;
646                 }
647         }
648         if (body_pos > 0 && body_pos > last) {
649                 w += font_metrics::width(layout->labelsep, getLabelFont(pit));
650                 if (last >= 0 && pit->isLineSeparator(last))
651                         w -= singleWidth(pit, last);
652                 int const left_margin = labelEnd(pit, row);
653                 if (w < left_margin)
654                         w = left_margin;
655         }
656
657         int const fill = paper_width - w - rightMargin(*pit, *bv()->buffer(), row);
658         row.fill(fill);
659         row.width(paper_width - fill);
660 }
661
662
663 // returns the minimum space a manual label needs on the screen in pixel
664 int LyXText::labelFill(ParagraphList::iterator pit, Row const & row) const
665 {
666         pos_type last = pit->beginningOfBody();
667
668         BOOST_ASSERT(last > 0);
669
670         // -1 because a label ends either with a space that is in the label,
671         // or with the beginning of a footnote that is outside the label.
672         --last;
673
674         // a separator at this end does not count
675         if (pit->isLineSeparator(last))
676                 --last;
677
678         int w = 0;
679         pos_type i = row.pos();
680         while (i <= last) {
681                 w += singleWidth(pit, i);
682                 ++i;
683         }
684
685         int fill = 0;
686         string const & labwidstr = pit->params().labelWidthString();
687         if (!labwidstr.empty()) {
688                 LyXFont const labfont = getLabelFont(pit);
689                 int const labwidth = font_metrics::width(labwidstr, labfont);
690                 fill = max(labwidth - w, 0);
691         }
692
693         return fill;
694 }
695
696
697 LColor_color LyXText::backgroundColor() const
698 {
699         if (inset_owner)
700                 return inset_owner->backgroundColor();
701         else
702                 return LColor::background;
703 }
704
705
706 void LyXText::setHeightOfRow(ParagraphList::iterator pit, Row & row)
707 {
708         // get the maximum ascent and the maximum descent
709         double layoutasc = 0;
710         double layoutdesc = 0;
711         double tmptop = 0;
712
713         // ok, let us initialize the maxasc and maxdesc value.
714         // Only the fontsize count. The other properties
715         // are taken from the layoutfont. Nicer on the screen :)
716         LyXLayout_ptr const & layout = pit->layout();
717
718         // as max get the first character of this row then it can increase but not
719         // decrease the height. Just some point to start with so we don't have to
720         // do the assignment below too often.
721         LyXFont font = getFont(pit, row.pos());
722         LyXFont::FONT_SIZE const tmpsize = font.size();
723         font = getLayoutFont(pit);
724         LyXFont::FONT_SIZE const size = font.size();
725         font.setSize(tmpsize);
726
727         LyXFont labelfont = getLabelFont(pit);
728
729         double spacing_val = 1.0;
730         if (!pit->params().spacing().isDefault())
731                 spacing_val = pit->params().spacing().getValue();
732         else
733                 spacing_val = bv()->buffer()->params().spacing().getValue();
734         //lyxerr << "spacing_val = " << spacing_val << endl;
735
736         int maxasc  = int(font_metrics::maxAscent(font) *
737                           layout->spacing.getValue() * spacing_val);
738         int maxdesc = int(font_metrics::maxDescent(font) *
739                           layout->spacing.getValue() * spacing_val);
740
741         pos_type const pos_end = lastPos(*pit, row);
742         int labeladdon = 0;
743         int maxwidth = 0;
744
745         if (!pit->empty()) {
746                 // We re-use the font resolution for the entire font span when possible
747                 LyXFont font = getFont(pit, row.pos());
748                 lyx::pos_type endPosOfFontSpan = pit->getEndPosOfFontSpan(row.pos());
749
750                 // Optimisation
751                 Paragraph const & par = *pit;
752
753                 // Check if any insets are larger
754                 for (pos_type pos = row.pos(); pos <= pos_end; ++pos) {
755                         // Manual inlined optimised version of common case of
756                         // "maxwidth += singleWidth(pit, pos);"
757                         char const c = par.getChar(pos);
758
759                         if (IsPrintable(c)) {
760                                 if (pos > endPosOfFontSpan) {
761                                         // We need to get the next font
762                                         font = getFont(pit, pos);
763                                         endPosOfFontSpan = par.getEndPosOfFontSpan(pos);
764                                 }
765                                 if (! font.language()->RightToLeft()) {
766                                         maxwidth += font_metrics::width(c, font);
767                                 } else {
768                                         // Fall-back to normal case
769                                         maxwidth += singleWidth(pit, pos, c, font);
770                                         // And flush font cache
771                                         endPosOfFontSpan = 0;
772                                 }
773                         } else {
774                                 // Special handling of insets - are any larger?
775                                 if (par.isInset(pos)) {
776                                         InsetOld const * tmpinset = par.getInset(pos);
777                                         if (tmpinset) {
778                                                 maxwidth += tmpinset->width();
779                                                 maxasc = max(maxasc, tmpinset->ascent());
780                                                 maxdesc = max(maxdesc, tmpinset->descent());
781                                         }
782                                 } else {
783                                         // Fall-back to normal case
784                                         maxwidth += singleWidth(pit, pos, c, font);
785                                         // And flush font cache
786                                         endPosOfFontSpan = 0;
787                                 }
788                         }
789                 }
790         }
791
792         // Check if any custom fonts are larger (Asger)
793         // This is not completely correct, but we can live with the small,
794         // cosmetic error for now.
795         LyXFont::FONT_SIZE maxsize =
796                 pit->highestFontInRange(row.pos(), pos_end, size);
797         if (maxsize > font.size()) {
798                 font.setSize(maxsize);
799                 maxasc = max(maxasc, font_metrics::maxAscent(font));
800                 maxdesc = max(maxdesc, font_metrics::maxDescent(font));
801         }
802
803         // This is nicer with box insets:
804         ++maxasc;
805         ++maxdesc;
806
807         row.ascent_of_text(maxasc);
808
809         // is it a top line?
810         if (!row.pos()) {
811                 BufferParams const & bufparams = bv()->buffer()->params();
812                 // some parksips VERY EASY IMPLEMENTATION
813                 if (bv()->buffer()->params().paragraph_separation ==
814                         BufferParams::PARSEP_SKIP)
815                 {
816                         if (layout->isParagraph()
817                                 && pit->getDepth() == 0
818                                 && pit != ownerParagraphs().begin())
819                         {
820                                 maxasc += bufparams.getDefSkip().inPixels(*bv());
821                         } else if (pit != ownerParagraphs().begin() &&
822                                    boost::prior(pit)->layout()->isParagraph() &&
823                                    boost::prior(pit)->getDepth() == 0)
824                         {
825                                 // is it right to use defskip here too? (AS)
826                                 maxasc += bufparams.getDefSkip().inPixels(*bv());
827                         }
828                 }
829
830                 // the top margin
831                 if (pit == ownerParagraphs().begin() && !isInInset())
832                         maxasc += PAPER_MARGIN;
833
834                 // add the vertical spaces, that the user added
835                 maxasc += getLengthMarkerHeight(*bv(), pit->params().spaceTop());
836
837                 // do not forget the DTP-lines!
838                 // there height depends on the font of the nearest character
839                 if (pit->params().lineTop())
840
841                         maxasc += 2 * font_metrics::ascent('x', getFont(pit, 0));
842                 // and now the pagebreaks
843                 if (pit->params().pagebreakTop())
844                         maxasc += 3 * defaultRowHeight();
845
846                 if (pit->params().startOfAppendix())
847                         maxasc += 3 * defaultRowHeight();
848
849                 // This is special code for the chapter, since the label of this
850                 // layout is printed in an extra row
851                 if (layout->counter == "chapter" && bufparams.secnumdepth >= 0) {
852                         float spacing_val = 1.0;
853                         if (!pit->params().spacing().isDefault()) {
854                                 spacing_val = pit->params().spacing().getValue();
855                         } else {
856                                 spacing_val = bufparams.spacing().getValue();
857                         }
858
859                         labeladdon = int(font_metrics::maxDescent(labelfont) *
860                                          layout->spacing.getValue() *
861                                          spacing_val)
862                                 + int(font_metrics::maxAscent(labelfont) *
863                                       layout->spacing.getValue() *
864                                       spacing_val);
865                 }
866
867                 // special code for the top label
868                 if ((layout->labeltype == LABEL_TOP_ENVIRONMENT
869                      || layout->labeltype == LABEL_BIBLIO
870                      || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
871                     && isFirstInSequence(pit, ownerParagraphs())
872                     && !pit->getLabelstring().empty())
873                 {
874                         float spacing_val = 1.0;
875                         if (!pit->params().spacing().isDefault()) {
876                                 spacing_val = pit->params().spacing().getValue();
877                         } else {
878                                 spacing_val = bufparams.spacing().getValue();
879                         }
880
881                         labeladdon = int(
882                                 (font_metrics::maxAscent(labelfont) +
883                                  font_metrics::maxDescent(labelfont)) *
884                                   layout->spacing.getValue() *
885                                   spacing_val
886                                 + layout->topsep * defaultRowHeight()
887                                 + layout->labelbottomsep * defaultRowHeight());
888                 }
889
890                 // And now the layout spaces, for example before and after
891                 // a section, or between the items of a itemize or enumerate
892                 // environment.
893
894                 if (!pit->params().pagebreakTop()) {
895                         ParagraphList::iterator prev =
896                                 depthHook(pit, ownerParagraphs(),
897                                           pit->getDepth());
898                         if (prev != pit && prev->layout() == layout &&
899                                 prev->getDepth() == pit->getDepth() &&
900                                 prev->getLabelWidthString() == pit->getLabelWidthString())
901                         {
902                                 layoutasc = (layout->itemsep * defaultRowHeight());
903                         } else if (pit != ownerParagraphs().begin() || row.pos() != 0) {
904                                 tmptop = layout->topsep;
905
906                                 if (tmptop > 0)
907                                         layoutasc = (tmptop * defaultRowHeight());
908                         } else if (pit->params().lineTop()) {
909                                 tmptop = layout->topsep;
910
911                                 if (tmptop > 0)
912                                         layoutasc = (tmptop * defaultRowHeight());
913                         }
914
915                         prev = outerHook(pit, ownerParagraphs());
916                         if (prev != ownerParagraphs().end())  {
917                                 maxasc += int(prev->layout()->parsep * defaultRowHeight());
918                         } else if (pit != ownerParagraphs().begin()) {
919                                 ParagraphList::iterator prior_pit = boost::prior(pit);
920                                 if (prior_pit->getDepth() != 0 ||
921                                     prior_pit->layout() == layout) {
922                                         maxasc += int(layout->parsep * defaultRowHeight());
923                                 }
924                         }
925                 }
926         }
927
928         // is it a bottom line?
929         if (row.endpos() >= pit->size()) {
930                 // the bottom margin
931                 ParagraphList::iterator nextpit = boost::next(pit);
932                 if (nextpit == ownerParagraphs().end() && !isInInset())
933                         maxdesc += PAPER_MARGIN;
934
935                 // add the vertical spaces, that the user added
936                 maxdesc += getLengthMarkerHeight(*bv(), pit->params().spaceBottom());
937
938                 // do not forget the DTP-lines!
939                 // there height depends on the font of the nearest character
940                 if (pit->params().lineBottom())
941                         maxdesc += 2 * font_metrics::ascent('x',
942                                         getFont(pit, max(pos_type(0), pit->size() - 1)));
943
944                 // and now the pagebreaks
945                 if (pit->params().pagebreakBottom())
946                         maxdesc += 3 * defaultRowHeight();
947
948                 // and now the layout spaces, for example before and after
949                 // a section, or between the items of a itemize or enumerate
950                 // environment
951                 if (!pit->params().pagebreakBottom()
952                     && nextpit != ownerParagraphs().end()) {
953                         ParagraphList::iterator comparepit = pit;
954                         float usual = 0;
955                         float unusual = 0;
956
957                         if (comparepit->getDepth() > nextpit->getDepth()) {
958                                 usual = (comparepit->layout()->bottomsep * defaultRowHeight());
959                                 comparepit = depthHook(comparepit, ownerParagraphs(), nextpit->getDepth());
960                                 if (comparepit->layout()!= nextpit->layout()
961                                         || nextpit->getLabelWidthString() !=
962                                         comparepit->getLabelWidthString())
963                                 {
964                                         unusual = (comparepit->layout()->bottomsep * defaultRowHeight());
965                                 }
966                                 if (unusual > usual)
967                                         layoutdesc = unusual;
968                                 else
969                                         layoutdesc = usual;
970                         } else if (comparepit->getDepth() ==  nextpit->getDepth()) {
971
972                                 if (comparepit->layout() != nextpit->layout()
973                                         || nextpit->getLabelWidthString() !=
974                                         comparepit->getLabelWidthString())
975                                         layoutdesc = int(comparepit->layout()->bottomsep * defaultRowHeight());
976                         }
977                 }
978         }
979
980         // incalculate the layout spaces
981         maxasc += int(layoutasc * 2 / (2 + pit->getDepth()));
982         maxdesc += int(layoutdesc * 2 / (2 + pit->getDepth()));
983
984         row.height(maxasc + maxdesc + labeladdon);
985         row.baseline(maxasc + labeladdon);
986         row.top_of_text(row.baseline() - font_metrics::maxAscent(font));
987
988         row.width(maxwidth);
989
990         if (inset_owner)
991                 width = max(workWidth(), int(maxParagraphWidth(ownerParagraphs())));
992 }
993
994
995 void LyXText::breakParagraph(ParagraphList & paragraphs, char keep_layout)
996 {
997         // allow only if at start or end, or all previous is new text
998         if (cursor.pos() && cursor.pos() != cursorPar()->size()
999             && cursorPar()->isChangeEdited(0, cursor.pos()))
1000                 return;
1001
1002         LyXTextClass const & tclass =
1003                 bv()->buffer()->params().getLyXTextClass();
1004         LyXLayout_ptr const & layout = cursorPar()->layout();
1005
1006         // this is only allowed, if the current paragraph is not empty or caption
1007         // and if it has not the keepempty flag active
1008         if (cursorPar()->empty() && !cursorPar()->allowEmpty()
1009            && layout->labeltype != LABEL_SENSITIVE)
1010                 return;
1011
1012         recUndo(cursor.par());
1013
1014         // Always break behind a space
1015         //
1016         // It is better to erase the space (Dekel)
1017         if (cursor.pos() < cursorPar()->size()
1018              && cursorPar()->isLineSeparator(cursor.pos()))
1019            cursorPar()->erase(cursor.pos());
1020
1021         // break the paragraph
1022         if (keep_layout)
1023                 keep_layout = 2;
1024         else
1025                 keep_layout = layout->isEnvironment();
1026
1027         // we need to set this before we insert the paragraph. IMO the
1028         // breakParagraph call should return a bool if it inserts the
1029         // paragraph before or behind and we should react on that one
1030         // but we can fix this in 1.3.0 (Jug 20020509)
1031         bool const isempty = (cursorPar()->allowEmpty() && cursorPar()->empty());
1032         ::breakParagraph(bv()->buffer()->params(), paragraphs, cursorPar(),
1033                          cursor.pos(), keep_layout);
1034
1035 #warning Trouble Point! (Lgb)
1036         // When ::breakParagraph is called from within an inset we must
1037         // ensure that the correct ParagraphList is used. Today that is not
1038         // the case and the Buffer::paragraphs is used. Not good. (Lgb)
1039         ParagraphList::iterator next_par = boost::next(cursorPar());
1040
1041         // well this is the caption hack since one caption is really enough
1042         if (layout->labeltype == LABEL_SENSITIVE) {
1043                 if (!cursor.pos())
1044                         // set to standard-layout
1045                         cursorPar()->applyLayout(tclass.defaultLayout());
1046                 else
1047                         // set to standard-layout
1048                         next_par->applyLayout(tclass.defaultLayout());
1049         }
1050
1051         // if the cursor is at the beginning of a row without prior newline,
1052         // move one row up!
1053         // This touches only the screen-update. Otherwise we would may have
1054         // an empty row on the screen
1055         if (cursor.pos() && cursorRow()->pos() == cursor.pos()
1056             && !cursorPar()->isNewline(cursor.pos() - 1))
1057         {
1058                 cursorLeft(bv());
1059         }
1060
1061         while (!next_par->empty() && next_par->isNewline(0))
1062                 next_par->erase(0);
1063
1064         updateCounters();
1065         redoParagraph(cursorPar());
1066         redoParagraph(next_par);
1067
1068         // This check is necessary. Otherwise the new empty paragraph will
1069         // be deleted automatically. And it is more friendly for the user!
1070         if (cursor.pos() || isempty)
1071                 setCursor(next_par, 0);
1072         else
1073                 setCursor(cursorPar(), 0);
1074 }
1075
1076
1077 // convenience function
1078 void LyXText::redoParagraph()
1079 {
1080         clearSelection();
1081         redoParagraph(cursorPar());
1082         setCursorIntern(cursor.par(), cursor.pos());
1083 }
1084
1085
1086 // insert a character, moves all the following breaks in the
1087 // same Paragraph one to the right and make a rebreak
1088 void LyXText::insertChar(char c)
1089 {
1090         recordUndo(Undo::INSERT, this, cursor.par(), cursor.par());
1091
1092         // When the free-spacing option is set for the current layout,
1093         // disable the double-space checking
1094
1095         bool const freeSpacing = cursorPar()->layout()->free_spacing ||
1096                 cursorPar()->isFreeSpacing();
1097
1098         if (lyxrc.auto_number) {
1099                 static string const number_operators = "+-/*";
1100                 static string const number_unary_operators = "+-";
1101                 static string const number_seperators = ".,:";
1102
1103                 if (current_font.number() == LyXFont::ON) {
1104                         if (!IsDigit(c) && !contains(number_operators, c) &&
1105                             !(contains(number_seperators, c) &&
1106                               cursor.pos() >= 1 &&
1107                               cursor.pos() < cursorPar()->size() &&
1108                               getFont(cursorPar(), cursor.pos()).number() == LyXFont::ON &&
1109                               getFont(cursorPar(), cursor.pos() - 1).number() == LyXFont::ON)
1110                            )
1111                                 number(bv()); // Set current_font.number to OFF
1112                 } else if (IsDigit(c) &&
1113                            real_current_font.isVisibleRightToLeft()) {
1114                         number(bv()); // Set current_font.number to ON
1115
1116                         if (cursor.pos() > 0) {
1117                                 char const c = cursorPar()->getChar(cursor.pos() - 1);
1118                                 if (contains(number_unary_operators, c) &&
1119                                     (cursor.pos() == 1 ||
1120                                      cursorPar()->isSeparator(cursor.pos() - 2) ||
1121                                      cursorPar()->isNewline(cursor.pos() - 2))
1122                                   ) {
1123                                         setCharFont(
1124                                                     cursorPar(),
1125                                                     cursor.pos() - 1,
1126                                                     current_font);
1127                                 } else if (contains(number_seperators, c) &&
1128                                            cursor.pos() >= 2 &&
1129                                            getFont(
1130                                                    cursorPar(),
1131                                                    cursor.pos() - 2).number() == LyXFont::ON) {
1132                                         setCharFont(
1133                                                     cursorPar(),
1134                                                     cursor.pos() - 1,
1135                                                     current_font);
1136                                 }
1137                         }
1138                 }
1139         }
1140
1141
1142         // First check, if there will be two blanks together or a blank at
1143         // the beginning of a paragraph.
1144         // I decided to handle blanks like normal characters, the main
1145         // difference are the special checks when calculating the row.fill
1146         // (blank does not count at the end of a row) and the check here
1147
1148         // The bug is triggered when we type in a description environment:
1149         // The current_font is not changed when we go from label to main text
1150         // and it should (along with realtmpfont) when we type the space.
1151         // CHECK There is a bug here! (Asger)
1152
1153         // store the current font.  This is because of the use of cursor
1154         // movements. The moving cursor would refresh the current font
1155         LyXFont realtmpfont = real_current_font;
1156         LyXFont rawtmpfont = current_font;
1157
1158         if (!freeSpacing && IsLineSeparatorChar(c)) {
1159                 if ((cursor.pos() > 0
1160                      && cursorPar()->isLineSeparator(cursor.pos() - 1))
1161                     || (cursor.pos() > 0
1162                         && cursorPar()->isNewline(cursor.pos() - 1))
1163                     || (cursor.pos() == 0)) {
1164                         static bool sent_space_message = false;
1165                         if (!sent_space_message) {
1166                                 if (cursor.pos() == 0)
1167                                         bv()->owner()->message(_("You cannot insert a space at the beginning of a paragraph. Please read the Tutorial."));
1168                                 else
1169                                         bv()->owner()->message(_("You cannot type two spaces this way. Please read the Tutorial."));
1170                                 sent_space_message = true;
1171                         }
1172                         charInserted();
1173                         return;
1174                 }
1175         }
1176
1177         // Here case LyXText::InsertInset already inserted the character
1178         if (c != Paragraph::META_INSET)
1179                 cursorPar()->insertChar(cursor.pos(), c);
1180
1181         setCharFont(cursorPar(), cursor.pos(), rawtmpfont);
1182
1183         current_font = rawtmpfont;
1184         real_current_font = realtmpfont;
1185         redoParagraph(cursorPar());
1186         setCursor(cursor.par(), cursor.pos() + 1, false, cursor.boundary());
1187
1188         charInserted();
1189 }
1190
1191
1192 void LyXText::charInserted()
1193 {
1194         // Here we could call finishUndo for every 20 characters inserted.
1195         // This is from my experience how emacs does it. (Lgb)
1196         static unsigned int counter;
1197         if (counter < 20) {
1198                 ++counter;
1199         } else {
1200                 finishUndo();
1201                 counter = 0;
1202         }
1203 }
1204
1205
1206 void LyXText::prepareToPrint(ParagraphList::iterator pit, Row & row) const
1207 {
1208         double w = row.fill();
1209         double fill_hfill = 0;
1210         double fill_label_hfill = 0;
1211         double fill_separator = 0;
1212         double x = 0;
1213
1214         bool const is_rtl =
1215                 pit->isRightToLeftPar(bv()->buffer()->params());
1216         if (is_rtl)
1217                 x = workWidth() > 0 ? rightMargin(*pit, *bv()->buffer(), row) : 0;
1218         else
1219                 x = workWidth() > 0 ? leftMargin(pit, row) : 0;
1220
1221         // is there a manual margin with a manual label
1222         LyXLayout_ptr const & layout = pit->layout();
1223
1224         if (layout->margintype == MARGIN_MANUAL
1225             && layout->labeltype == LABEL_MANUAL) {
1226                 /// We might have real hfills in the label part
1227                 int nlh = numberOfLabelHfills(*pit, row);
1228
1229                 // A manual label par (e.g. List) has an auto-hfill
1230                 // between the label text and the body of the
1231                 // paragraph too.
1232                 // But we don't want to do this auto hfill if the par
1233                 // is empty.
1234                 if (!pit->empty())
1235                         ++nlh;
1236
1237                 if (nlh && !pit->getLabelWidthString().empty()) {
1238                         fill_label_hfill = labelFill(pit, row) / double(nlh);
1239                 }
1240         }
1241
1242         // are there any hfills in the row?
1243         int const nh = numberOfHfills(*pit, row);
1244
1245         if (nh) {
1246                 if (w > 0)
1247                         fill_hfill = w / nh;
1248         // we don't have to look at the alignment if it is ALIGN_LEFT and
1249         // if the row is already larger then the permitted width as then
1250         // we force the LEFT_ALIGN'edness!
1251         } else if (int(row.width()) < workWidth()) {
1252                 // is it block, flushleft or flushright?
1253                 // set x how you need it
1254                 int align;
1255                 if (pit->params().align() == LYX_ALIGN_LAYOUT) {
1256                         align = layout->align;
1257                 } else {
1258                         align = pit->params().align();
1259                 }
1260                 InsetOld * inset = 0;
1261                 // ERT insets should always be LEFT ALIGNED on screen
1262                 inset = pit->inInset();
1263                 if (inset && inset->owner() &&
1264                         inset->owner()->lyxCode() == InsetOld::ERT_CODE)
1265                 {
1266                         align = LYX_ALIGN_LEFT;
1267                 }
1268
1269                 // Display-style insets should always be on a centred row
1270                 // The test on pit->size() is to catch zero-size pars, which
1271                 // would trigger the assert in Paragraph::getInset().
1272                 //inset = pit->size() ? pit->getInset(row.pos()) : 0;
1273                 inset = pit->isInset(row.pos()) ? pit->getInset(row.pos()) : 0;
1274                 if (inset && inset->display()) {
1275                         align = LYX_ALIGN_CENTER;
1276                 }
1277                 
1278                 switch (align) {
1279             case LYX_ALIGN_BLOCK:
1280                 {
1281                         int const ns = numberOfSeparators(*pit, row);
1282                         bool disp_inset = false;
1283                         if (row.endpos() < pit->size()) {
1284                                 InsetOld * in = pit->getInset(row.endpos());
1285                                 if (in)
1286                                         disp_inset = in->display();
1287                         }
1288                         // If we have separators, this is not the last row of a
1289                         // par, does not end in newline, and is not row above a
1290                         // display inset... then stretch it
1291                         if (ns
1292                                 && row.endpos() < pit->size()
1293                                 && !pit->isNewline(row.endpos())
1294                                 && !disp_inset
1295                                 ) {
1296                                         fill_separator = w / ns;
1297                         } else if (is_rtl) {
1298                                 x += w;
1299                         }
1300                         break;
1301             }
1302             case LYX_ALIGN_RIGHT:
1303                         x += w;
1304                         break;
1305             case LYX_ALIGN_CENTER:
1306                         x += w / 2;
1307                         break;
1308                 }
1309         }
1310
1311         bidi.computeTables(*pit, *bv()->buffer(), row);
1312         if (is_rtl) {
1313                 pos_type body_pos = pit->beginningOfBody();
1314                 pos_type last = lastPos(*pit, row);
1315
1316                 if (body_pos > 0 &&
1317                                 (body_pos - 1 > last ||
1318                                  !pit->isLineSeparator(body_pos - 1))) {
1319                         x += font_metrics::width(layout->labelsep, getLabelFont(pit));
1320                         if (body_pos - 1 <= last)
1321                                 x += fill_label_hfill;
1322                 }
1323         }
1324
1325         row.fill_hfill(fill_hfill);
1326         row.fill_label_hfill(fill_label_hfill);
1327         row.fill_separator(fill_separator);
1328         row.x(x);
1329 }
1330
1331
1332 // important for the screen
1333
1334
1335 // the cursor set functions have a special mechanism. When they
1336 // realize, that you left an empty paragraph, they will delete it.
1337 // They also delete the corresponding row
1338
1339 void LyXText::cursorRightOneWord()
1340 {
1341         ::cursorRightOneWord(*this, cursor, ownerParagraphs());
1342         setCursor(cursorPar(), cursor.pos());
1343 }
1344
1345
1346 // Skip initial whitespace at end of word and move cursor to *start*
1347 // of prior word, not to end of next prior word.
1348 void LyXText::cursorLeftOneWord()
1349 {
1350         LyXCursor tmpcursor = cursor;
1351         ::cursorLeftOneWord(*this, tmpcursor, ownerParagraphs());
1352         setCursor(getPar(tmpcursor), tmpcursor.pos());
1353 }
1354
1355
1356 void LyXText::selectWord(word_location loc)
1357 {
1358         LyXCursor from = cursor;
1359         LyXCursor to = cursor;
1360         ::getWord(*this, from, to, loc, ownerParagraphs());
1361         if (cursor != from)
1362                 setCursor(from.par(), from.pos());
1363         if (to == from)
1364                 return;
1365         selection.cursor = cursor;
1366         setCursor(to.par(), to.pos());
1367         setSelection();
1368 }
1369
1370
1371 // Select the word currently under the cursor when no
1372 // selection is currently set
1373 bool LyXText::selectWordWhenUnderCursor(word_location loc)
1374 {
1375         if (!selection.set()) {
1376                 selectWord(loc);
1377                 return selection.set();
1378         }
1379         return false;
1380 }
1381
1382
1383 void LyXText::acceptChange()
1384 {
1385         if (!selection.set() && cursorPar()->size())
1386                 return;
1387
1388         if (selection.start.par() == selection.end.par()) {
1389                 LyXCursor & startc = selection.start;
1390                 LyXCursor & endc = selection.end;
1391                 recordUndo(Undo::INSERT, this, startc.par());
1392                 getPar(startc)->acceptChange(startc.pos(), endc.pos());
1393                 finishUndo();
1394                 clearSelection();
1395                 redoParagraph(getPar(startc));
1396                 setCursorIntern(startc.par(), 0);
1397         }
1398 #warning handle multi par selection
1399 }
1400
1401
1402 void LyXText::rejectChange()
1403 {
1404         if (!selection.set() && cursorPar()->size())
1405                 return;
1406
1407         if (selection.start.par() == selection.end.par()) {
1408                 LyXCursor & startc = selection.start;
1409                 LyXCursor & endc = selection.end;
1410                 recordUndo(Undo::INSERT, this, startc.par());
1411                 getPar(startc)->rejectChange(startc.pos(), endc.pos());
1412                 finishUndo();
1413                 clearSelection();
1414                 redoParagraph(getPar(startc));
1415                 setCursorIntern(startc.par(), 0);
1416         }
1417 #warning handle multi par selection
1418 }
1419
1420
1421 // This function is only used by the spellchecker for NextWord().
1422 // It doesn't handle LYX_ACCENTs and probably never will.
1423 WordLangTuple const LyXText::selectNextWordToSpellcheck(float & value)
1424 {
1425         if (the_locking_inset) {
1426                 WordLangTuple word =
1427                         the_locking_inset->selectNextWordToSpellcheck(bv(), value);
1428                 if (!word.word().empty()) {
1429                         value += float(cursor.y());
1430                         value /= float(height);
1431                         return word;
1432                 }
1433                 // we have to go on checking so move cursor to the next char
1434                 if (cursor.pos() == cursorPar()->size()) {
1435                         if (cursor.par() + 1 == int(ownerParagraphs().size()))
1436                                 return word;
1437                         cursor.par(cursor.par() + 1);
1438                         cursor.pos(0);
1439                 } else {
1440                         cursor.pos(cursor.pos() + 1);
1441                 }
1442         }
1443         int const tmppar = cursor.par();
1444
1445         // If this is not the very first word, skip rest of
1446         // current word because we are probably in the middle
1447         // of a word if there is text here.
1448         if (cursor.pos() || cursor.par() != 0) {
1449                 while (cursor.pos() < cursorPar()->size()
1450                        && cursorPar()->isLetter(cursor.pos()))
1451                         cursor.pos(cursor.pos() + 1);
1452         }
1453
1454         // Now, skip until we have real text (will jump paragraphs)
1455         while (true) {
1456                 ParagraphList::iterator cpit = cursorPar();
1457                 pos_type const cpos = cursor.pos();
1458
1459                 if (cpos == cpit->size()) {
1460                         if (cursor.par() + 1 != int(ownerParagraphs().size())) {
1461                                 cursor.par(cursor.par() + 1);
1462                                 cursor.pos(0);
1463                                 continue;
1464                         }
1465                         break;
1466                 }
1467
1468                 bool const is_good_inset = cpit->isInset(cpos)
1469                         && cpit->getInset(cpos)->allowSpellcheck();
1470
1471                 if (!isDeletedText(*cpit, cpos)
1472                     && (is_good_inset || cpit->isLetter(cpos)))
1473                         break;
1474
1475                 cursor.pos(cpos + 1);
1476         }
1477
1478         // now check if we hit an inset so it has to be a inset containing text!
1479         if (cursor.pos() < cursorPar()->size() &&
1480             cursorPar()->isInset(cursor.pos())) {
1481                 // lock the inset!
1482                 FuncRequest cmd(bv(), LFUN_INSET_EDIT, "left");
1483                 cursorPar()->getInset(cursor.pos())->dispatch(cmd);
1484                 // now call us again to do the above trick
1485                 // but obviously we have to start from down below ;)
1486                 return bv()->text->selectNextWordToSpellcheck(value);
1487         }
1488
1489         // Update the value if we changed paragraphs
1490         if (cursor.par() != tmppar) {
1491                 setCursor(cursor.par(), cursor.pos());
1492                 value = float(cursor.y())/float(height);
1493         }
1494
1495         // Start the selection from here
1496         selection.cursor = cursor;
1497
1498         string lang_code = getFont(cursorPar(), cursor.pos()).language()->code();
1499         // and find the end of the word (insets like optional hyphens
1500         // and ligature break are part of a word)
1501         while (cursor.pos() < cursorPar()->size()
1502                && cursorPar()->isLetter(cursor.pos())
1503                && !isDeletedText(*cursorPar(), cursor.pos()))
1504                 cursor.pos(cursor.pos() + 1);
1505
1506         // Finally, we copy the word to a string and return it
1507         string str;
1508         if (selection.cursor.pos() < cursor.pos()) {
1509                 for (pos_type i = selection.cursor.pos(); i < cursor.pos(); ++i) {
1510                         if (!cursorPar()->isInset(i))
1511                                 str += cursorPar()->getChar(i);
1512                 }
1513         }
1514         return WordLangTuple(str, lang_code);
1515 }
1516
1517
1518 // This one is also only for the spellchecker
1519 void LyXText::selectSelectedWord()
1520 {
1521         if (the_locking_inset) {
1522                 the_locking_inset->selectSelectedWord(bv());
1523                 return;
1524         }
1525         // move cursor to the beginning
1526         setCursor(selection.cursor.par(), selection.cursor.pos());
1527
1528         // set the sel cursor
1529         selection.cursor = cursor;
1530
1531         // now find the end of the word
1532         while (cursor.pos() < cursorPar()->size()
1533                && cursorPar()->isLetter(cursor.pos()))
1534                 cursor.pos(cursor.pos() + 1);
1535
1536         setCursor(cursorPar(), cursor.pos());
1537
1538         // finally set the selection
1539         setSelection();
1540 }
1541
1542
1543 // Delete from cursor up to the end of the current or next word.
1544 void LyXText::deleteWordForward()
1545 {
1546         if (cursorPar()->empty())
1547                 cursorRight(bv());
1548         else {
1549                 LyXCursor tmpcursor = cursor;
1550                 selection.set(true); // to avoid deletion
1551                 cursorRightOneWord();
1552                 setCursor(tmpcursor, tmpcursor.par(), tmpcursor.pos());
1553                 selection.cursor = cursor;
1554                 cursor = tmpcursor;
1555                 setSelection();
1556                 cutSelection(true, false);
1557         }
1558 }
1559
1560
1561 // Delete from cursor to start of current or prior word.
1562 void LyXText::deleteWordBackward()
1563 {
1564         if (cursorPar()->empty())
1565                 cursorLeft(bv());
1566         else {
1567                 LyXCursor tmpcursor = cursor;
1568                 selection.set(true); // to avoid deletion
1569                 cursorLeftOneWord();
1570                 setCursor(tmpcursor, tmpcursor.par(), tmpcursor.pos());
1571                 selection.cursor = cursor;
1572                 cursor = tmpcursor;
1573                 setSelection();
1574                 cutSelection(true, false);
1575         }
1576 }
1577
1578
1579 // Kill to end of line.
1580 void LyXText::deleteLineForward()
1581 {
1582         if (cursorPar()->empty())
1583                 // Paragraph is empty, so we just go to the right
1584                 cursorRight(bv());
1585         else {
1586                 LyXCursor tmpcursor = cursor;
1587                 // We can't store the row over a regular setCursor
1588                 // so we set it to 0 and reset it afterwards.
1589                 selection.set(true); // to avoid deletion
1590                 cursorEnd();
1591                 setCursor(tmpcursor, tmpcursor.par(), tmpcursor.pos());
1592                 selection.cursor = cursor;
1593                 cursor = tmpcursor;
1594                 setSelection();
1595                 // What is this test for ??? (JMarc)
1596                 if (!selection.set()) {
1597                         deleteWordForward();
1598                 } else {
1599                         cutSelection(true, false);
1600                 }
1601         }
1602 }
1603
1604
1605 void LyXText::changeCase(LyXText::TextCase action)
1606 {
1607         LyXCursor from;
1608         LyXCursor to;
1609
1610         if (selection.set()) {
1611                 from = selection.start;
1612                 to = selection.end;
1613         } else {
1614                 from = cursor;
1615                 ::getWord(*this, from, to, lyx::PARTIAL_WORD, ownerParagraphs());
1616                 setCursor(to.par(), to.pos() + 1);
1617         }
1618
1619         recordUndo(Undo::ATOMIC, this, from.par(), to.par());
1620
1621         pos_type pos = from.pos();
1622         int par = from.par();
1623
1624         while (par != int(ownerParagraphs().size()) &&
1625                (pos != to.pos() || par != to.par())) {
1626                 ParagraphList::iterator pit = getPar(par);
1627                 if (pos == pit->size()) {
1628                         ++par;
1629                         pos = 0;
1630                         continue;
1631                 }
1632                 unsigned char c = pit->getChar(pos);
1633                 if (c != Paragraph::META_INSET) {
1634                         switch (action) {
1635                         case text_lowercase:
1636                                 c = lowercase(c);
1637                                 break;
1638                         case text_capitalization:
1639                                 c = uppercase(c);
1640                                 action = text_lowercase;
1641                                 break;
1642                         case text_uppercase:
1643                                 c = uppercase(c);
1644                                 break;
1645                         }
1646                 }
1647 #warning changes
1648                 pit->setChar(pos, c);
1649                 ++pos;
1650         }
1651 }
1652
1653
1654 void LyXText::Delete()
1655 {
1656         // this is a very easy implementation
1657
1658         LyXCursor old_cursor = cursor;
1659         int const old_cur_par_id = cursorPar()->id();
1660         int const old_cur_par_prev_id =
1661                 old_cursor.par() ? getPar(old_cursor.par() - 1)->id() : -1;
1662
1663         // just move to the right
1664         cursorRight(bv());
1665
1666         // CHECK Look at the comment here.
1667         // This check is not very good...
1668         // The cursorRightIntern calls DeleteEmptyParagraphMechanism
1669         // and that can very well delete the par or par->previous in
1670         // old_cursor. Will a solution where we compare paragraph id's
1671         //work better?
1672         int iid = cursor.par() ? getPar(cursor.par() - 1)->id() : -1;
1673         if (iid == old_cur_par_prev_id && cursorPar()->id() != old_cur_par_id) {
1674                 // delete-empty-paragraph-mechanism has done it
1675                 return;
1676         }
1677
1678         // if you had success make a backspace
1679         if (old_cursor.par() != cursor.par() || old_cursor.pos() != cursor.pos()) {
1680                 recordUndo(Undo::DELETE, this, old_cursor.par());
1681                 backspace();
1682         }
1683 }
1684
1685
1686 void LyXText::backspace()
1687 {
1688         // Get the font that is used to calculate the baselineskip
1689         ParagraphList::iterator pit = cursorPar();
1690         pos_type lastpos = pit->size();
1691
1692         if (cursor.pos() == 0) {
1693                 // The cursor is at the beginning of a paragraph,
1694                 // so the the backspace will collapse two paragraphs into one.
1695
1696                 // but it's not allowed unless it's new
1697                 if (pit->isChangeEdited(0, pit->size()))
1698                         return;
1699
1700                 // we may paste some paragraphs
1701
1702                 // is it an empty paragraph?
1703
1704                 if (lastpos == 0 || (lastpos == 1 && pit->isSeparator(0))) {
1705                         // This is an empty paragraph and we delete it just
1706                         // by moving the cursor one step
1707                         // left and let the DeleteEmptyParagraphMechanism
1708                         // handle the actual deletion of the paragraph.
1709
1710                         if (cursor.par()) {
1711                                 ParagraphList::iterator tmppit = getPar(cursor.par() - 1);
1712                                 if (cursorPar()->layout() == tmppit->layout()
1713                                     && cursorPar()->getAlign() == tmppit->getAlign()) {
1714                                         // Inherit bottom DTD from the paragraph below.
1715                                         // (the one we are deleting)
1716                                         tmppit->params().lineBottom(cursorPar()->params().lineBottom());
1717                                         tmppit->params().spaceBottom(cursorPar()->params().spaceBottom());
1718                                         tmppit->params().pagebreakBottom(cursorPar()->params().pagebreakBottom());
1719                                 }
1720
1721                                 cursorLeft(bv());
1722
1723                                 // the layout things can change the height of a row !
1724                                 redoParagraph();
1725                                 return;
1726                         }
1727                 }
1728
1729                 if (cursor.par() != 0)
1730                         recordUndo(Undo::DELETE, this, cursor.par() - 1, cursor.par());
1731
1732                 ParagraphList::iterator tmppit = cursorPar();
1733                 // We used to do cursorLeftIntern() here, but it is
1734                 // not a good idea since it triggers the auto-delete
1735                 // mechanism. So we do a cursorLeftIntern()-lite,
1736                 // without the dreaded mechanism. (JMarc)
1737                 if (cursor.par() != 0) {
1738                         // steps into the above paragraph.
1739                         setCursorIntern(cursor.par() - 1,
1740                                         getPar(cursor.par() - 1)->size(),
1741                                         false);
1742                 }
1743
1744                 // Pasting is not allowed, if the paragraphs have different
1745                 // layout. I think it is a real bug of all other
1746                 // word processors to allow it. It confuses the user.
1747                 // Correction: Pasting is always allowed with standard-layout
1748                 Buffer & buf = *bv()->buffer();
1749                 BufferParams const & bufparams = buf.params();
1750                 LyXTextClass const & tclass = bufparams.getLyXTextClass();
1751
1752                 if (cursorPar() != tmppit
1753                     && (cursorPar()->layout() == tmppit->layout()
1754                         || tmppit->layout() == tclass.defaultLayout())
1755                     && cursorPar()->getAlign() == tmppit->getAlign()) {
1756                         mergeParagraph(bufparams,
1757                                        buf.paragraphs(), cursorPar());
1758
1759                         if (cursor.pos() && cursorPar()->isSeparator(cursor.pos() - 1))
1760                                 cursor.pos(cursor.pos() - 1);
1761
1762                         // the row may have changed, block, hfills etc.
1763                         updateCounters();
1764                         setCursor(cursor.par(), cursor.pos(), false);
1765                 }
1766         } else {
1767                 // this is the code for a normal backspace, not pasting
1768                 // any paragraphs
1769                 recordUndo(Undo::DELETE, this, cursor.par());
1770                 // We used to do cursorLeftIntern() here, but it is
1771                 // not a good idea since it triggers the auto-delete
1772                 // mechanism. So we do a cursorLeftIntern()-lite,
1773                 // without the dreaded mechanism. (JMarc)
1774                 setCursorIntern(cursor.par(), cursor.pos() - 1,
1775                                 false, cursor.boundary());
1776                 cursorPar()->erase(cursor.pos());
1777         }
1778
1779         lastpos = cursorPar()->size();
1780         if (cursor.pos() == lastpos)
1781                 setCurrentFont();
1782
1783         redoParagraph();
1784         setCursor(cursor.par(), cursor.pos(), false, !cursor.boundary());
1785 }
1786
1787
1788 ParagraphList::iterator LyXText::cursorPar() const
1789 {
1790         return getPar(cursor.par());
1791 }
1792
1793
1794 ParagraphList::iterator LyXText::getPar(LyXCursor const & cur) const
1795 {
1796         return getPar(cur.par());
1797 }
1798
1799
1800 ParagraphList::iterator LyXText::getPar(int par) const
1801 {
1802         BOOST_ASSERT(par >= 0);
1803         BOOST_ASSERT(par < int(ownerParagraphs().size()));
1804         ParagraphList::iterator pit = ownerParagraphs().begin();
1805         std::advance(pit, par);
1806         return pit;
1807 }
1808
1809
1810
1811 RowList::iterator LyXText::cursorRow() const
1812 {
1813         return getRow(*cursorPar(), cursor.pos());
1814 }
1815
1816
1817 RowList::iterator LyXText::getRow(LyXCursor const & cur) const
1818 {
1819         return getRow(*getPar(cur), cur.pos());
1820 }
1821
1822
1823 RowList::iterator LyXText::getRow(Paragraph & par, pos_type pos) const
1824 {
1825         RowList::iterator rit = boost::prior(par.rows.end());
1826         RowList::iterator const begin = par.rows.begin();
1827
1828         while (rit != begin && rit->pos() > pos)
1829                 --rit;
1830
1831         return rit;
1832 }
1833
1834
1835 RowList::iterator
1836 LyXText::getRowNearY(int y, ParagraphList::iterator & pit) const
1837 {
1838         //lyxerr << "getRowNearY: y " << y << endl;
1839
1840         pit = boost::prior(ownerParagraphs().end());
1841
1842         RowList::iterator rit = lastRow();
1843         RowList::iterator rbegin = firstRow();
1844
1845         while (rit != rbegin && int(pit->y + rit->y_offset()) > y)
1846                 previousRow(pit, rit);
1847
1848         return rit;
1849 }
1850
1851
1852 int LyXText::getDepth() const
1853 {
1854         return cursorPar()->getDepth();
1855 }
1856
1857
1858 RowList::iterator LyXText::firstRow() const
1859 {
1860         return ownerParagraphs().front().rows.begin();
1861 }
1862
1863
1864 RowList::iterator LyXText::lastRow() const
1865 {
1866         return boost::prior(endRow());
1867 }
1868
1869
1870 RowList::iterator LyXText::endRow() const
1871 {
1872         return ownerParagraphs().back().rows.end();
1873 }
1874
1875
1876 void LyXText::nextRow(ParagraphList::iterator & pit,
1877         RowList::iterator & rit) const
1878 {
1879         ++rit;
1880         if (rit == pit->rows.end()) {
1881                 ++pit;
1882                 if (pit == ownerParagraphs().end())
1883                         --pit;
1884                 else
1885                         rit = pit->rows.begin();
1886         }
1887 }
1888
1889
1890 void LyXText::previousRow(ParagraphList::iterator & pit,
1891         RowList::iterator & rit) const
1892 {
1893         if (rit != pit->rows.begin())
1894                 --rit;
1895         else {
1896                 BOOST_ASSERT(pit != ownerParagraphs().begin());
1897                 --pit;
1898                 rit = boost::prior(pit->rows.end());
1899         }
1900 }
1901
1902
1903 string LyXText::selectionAsString(Buffer const & buffer, bool label) const
1904 {
1905         if (!selection.set())
1906                 return string();
1907
1908         // should be const ...
1909         ParagraphList::iterator startpit = getPar(selection.start);
1910         ParagraphList::iterator endpit = getPar(selection.end);
1911         size_t const startpos = selection.start.pos();
1912         size_t const endpos = selection.end.pos();
1913
1914         if (startpit == endpit)
1915                 return startpit->asString(buffer, startpos, endpos, label);
1916
1917         // First paragraph in selection
1918         string result =
1919                 startpit->asString(buffer, startpos, startpit->size(), label) + "\n\n";
1920
1921         // The paragraphs in between (if any)
1922         ParagraphList::iterator pit = startpit;
1923         for (++pit; pit != endpit; ++pit)
1924                 result += pit->asString(buffer, 0, pit->size(), label) + "\n\n";
1925
1926         // Last paragraph in selection
1927         result += endpit->asString(buffer, 0, endpos, label);
1928
1929         return result;
1930 }
1931
1932
1933 int LyXText::parOffset(ParagraphList::iterator pit) const
1934 {
1935         return std::distance(ownerParagraphs().begin(), pit);
1936 }
1937
1938
1939 void LyXText::redoParagraphInternal(ParagraphList::iterator pit)
1940 {
1941         // remove rows of paragraph, keep track of height changes
1942         height -= pit->height;
1943
1944         // clear old data
1945         pit->rows.clear();
1946         pit->height = 0;
1947         pit->width = 0;
1948
1949         // redo insets
1950         InsetList::iterator ii = pit->insetlist.begin();
1951         InsetList::iterator iend = pit->insetlist.end();
1952         for (; ii != iend; ++ii) {
1953                 Dimension dim;
1954                 MetricsInfo mi(bv(), getFont(pit, ii->pos), workWidth());
1955                 ii->inset->metrics(mi, dim);
1956         }
1957
1958         // rebreak the paragraph
1959         int const ww = workWidth();
1960         for (pos_type z = 0; z < pit->size() + 1; ) {
1961                 Row row(z);
1962                 rowBreakPoint(pit, row);
1963                 z = row.endpos();
1964                 fill(pit, row, ww);
1965                 prepareToPrint(pit, row);
1966                 setHeightOfRow(pit, row);
1967                 row.y_offset(pit->height);
1968                 pit->rows.push_back(row);
1969                 pit->width = std::max(pit->width, row.width());
1970                 pit->height += row.height();
1971         }
1972         height += pit->height;
1973         //lyxerr << "redoParagraph: " << pit->rows.size() << " rows\n";
1974 }
1975
1976
1977 void LyXText::redoParagraphs(ParagraphList::iterator pit,
1978   ParagraphList::iterator end)
1979 {
1980         for ( ; pit != end; ++pit)
1981                 redoParagraphInternal(pit);
1982         updateRowPositions();
1983 }
1984
1985
1986 void LyXText::redoParagraph(ParagraphList::iterator pit)
1987 {
1988         redoParagraphInternal(pit);
1989         updateRowPositions();
1990 }
1991
1992
1993 void LyXText::fullRebreak()
1994 {
1995         redoParagraphs(ownerParagraphs().begin(), ownerParagraphs().end());
1996         redoCursor();
1997         selection.cursor = cursor;
1998 }
1999
2000
2001 void LyXText::metrics(MetricsInfo & mi, Dimension & dim)
2002 {
2003         //lyxerr << "LyXText::metrics: width: " << mi.base.textwidth
2004         //      << " workWidth: " << workWidth() << "\nfont: " << mi.base.font << endl;
2005         //BOOST_ASSERT(mi.base.textwidth);
2006         //anchor_y_ = 0;
2007
2008         // rebuild row cache. This recomputes height as well.
2009         redoParagraphs(ownerParagraphs().begin(), ownerParagraphs().end());
2010
2011         width = maxParagraphWidth(ownerParagraphs());
2012
2013         // final dimension
2014         dim.asc = firstRow()->ascent_of_text();
2015         dim.des = height - dim.asc;
2016         dim.wid = std::max(mi.base.textwidth, int(width));
2017 }
2018
2019
2020 bool LyXText::isLastRow(ParagraphList::iterator pit, Row const & row) const
2021 {
2022         return row.endpos() >= pit->size()
2023                && boost::next(pit) == ownerParagraphs().end();
2024 }
2025
2026
2027 bool LyXText::isFirstRow(ParagraphList::iterator pit, Row const & row) const
2028 {
2029         return row.pos() == 0 && pit == ownerParagraphs().begin();
2030 }