]> git.lyx.org Git - lyx.git/blob - src/text.C
some support for pch
[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 "author.h"
22 #include "buffer.h"
23 #include "bufferparams.h"
24 #include "BufferView.h"
25 #include "cursor.h"
26 #include "CutAndPaste.h"
27 #include "debug.h"
28 #include "dispatchresult.h"
29 #include "encoding.h"
30 #include "errorlist.h"
31 #include "funcrequest.h"
32 #include "factory.h"
33 #include "FontIterator.h"
34 #include "gettext.h"
35 #include "language.h"
36 #include "LColor.h"
37 #include "lyxlength.h"
38 #include "lyxlex.h"
39 #include "lyxrc.h"
40 #include "lyxrow.h"
41 #include "lyxrow_funcs.h"
42 #include "metricsinfo.h"
43 #include "paragraph.h"
44 #include "paragraph_funcs.h"
45 #include "ParagraphParameters.h"
46 #include "rowpainter.h"
47 #include "undo.h"
48 #include "vspace.h"
49 #include "WordLangTuple.h"
50
51 #include "frontends/font_metrics.h"
52 #include "frontends/LyXView.h"
53
54 #include "insets/insettext.h"
55 #include "insets/insetbibitem.h"
56 #include "insets/insethfill.h"
57 #include "insets/insetlatexaccent.h"
58 #include "insets/insetline.h"
59 #include "insets/insetnewline.h"
60 #include "insets/insetpagebreak.h"
61 #include "insets/insetoptarg.h"
62 #include "insets/insetspace.h"
63 #include "insets/insetspecialchar.h"
64 #include "insets/insettabular.h"
65
66 #include "support/lstrings.h"
67 #include "support/textutils.h"
68 #include "support/tostr.h"
69
70 #include <sstream>
71
72 using lyx::par_type;
73 using lyx::pos_type;
74 using lyx::word_location;
75
76 using lyx::support::bformat;
77 using lyx::support::contains;
78 using lyx::support::lowercase;
79 using lyx::support::split;
80 using lyx::support::uppercase;
81
82 using lyx::cap::cutSelection;
83
84 using std::auto_ptr;
85 using std::advance;
86 using std::distance;
87 using std::max;
88 using std::min;
89 using std::endl;
90 using std::string;
91
92
93 namespace {
94
95 int numberOfSeparators(Paragraph const & par, Row const & row)
96 {
97         pos_type const first = max(row.pos(), par.beginOfBody());
98         pos_type const last = row.endpos() - 1;
99         int n = 0;
100         for (pos_type p = first; p < last; ++p) {
101                 if (par.isSeparator(p))
102                         ++n;
103         }
104         return n;
105 }
106
107
108 unsigned int maxParagraphWidth(ParagraphList const & plist)
109 {
110         unsigned int width = 0;
111         ParagraphList::const_iterator pit = plist.begin();
112         ParagraphList::const_iterator end = plist.end();
113                 for (; pit != end; ++pit)
114                         width = std::max(width, pit->width);
115         return width;
116 }
117
118
119 int numberOfLabelHfills(Paragraph const & par, Row const & row)
120 {
121         pos_type last = row.endpos() - 1;
122         pos_type first = row.pos();
123
124         // hfill *DO* count at the beginning of paragraphs!
125         if (first) {
126                 while (first < last && par.isHfill(first))
127                         ++first;
128         }
129
130         last = min(last, par.beginOfBody());
131         int n = 0;
132         for (pos_type p = first; p < last; ++p) {
133                 if (par.isHfill(p))
134                         ++n;
135         }
136         return n;
137 }
138
139
140 int numberOfHfills(Paragraph const & par, Row const & row)
141 {
142         pos_type const last = row.endpos() - 1;
143         pos_type first = row.pos();
144
145         // hfill *DO* count at the beginning of paragraphs!
146         if (first) {
147                 while (first < last && par.isHfill(first))
148                         ++first;
149         }
150
151         first = max(first, par.beginOfBody());
152
153         int n = 0;
154         for (pos_type p = first; p < last; ++p) {
155                 if (par.isHfill(p))
156                         ++n;
157         }
158         return n;
159 }
160
161
162 int readParToken(Buffer const & buf, Paragraph & par, LyXLex & lex,
163         string const & token, LyXFont & font)
164 {
165         static Change change;
166
167         BufferParams const & bp = buf.params();
168
169         if (token[0] != '\\') {
170                 string::const_iterator cit = token.begin();
171                 for (; cit != token.end(); ++cit) {
172                         par.insertChar(par.size(), (*cit), font, change);
173                 }
174         } else if (token == "\\begin_layout") {
175                 lex.eatLine();
176                 string layoutname = lex.getString();
177
178                 font = LyXFont(LyXFont::ALL_INHERIT, bp.language);
179                 change = Change();
180
181                 LyXTextClass const & tclass = bp.getLyXTextClass();
182
183                 if (layoutname.empty()) {
184                         layoutname = tclass.defaultLayoutName();
185                 }
186
187                 bool hasLayout = tclass.hasLayout(layoutname);
188
189                 if (!hasLayout) {
190                         lyxerr << "Layout '" << layoutname << "' does not"
191                                << " exist in textclass '" << tclass.name()
192                                << "'." << endl;
193                         lyxerr << "Trying to use default layout instead."
194                                << endl;
195                         layoutname = tclass.defaultLayoutName();
196                 }
197
198                 par.layout(bp.getLyXTextClass()[layoutname]);
199
200                 // Test whether the layout is obsolete.
201                 LyXLayout_ptr const & layout = par.layout();
202                 if (!layout->obsoleted_by().empty())
203                         par.layout(bp.getLyXTextClass()[layout->obsoleted_by()]);
204
205                 par.params().read(lex);
206
207         } else if (token == "\\end_layout") {
208                 lyxerr << "Solitary \\end_layout in line " << lex.getLineNo() << "\n"
209                        << "Missing \\begin_layout?.\n";
210         } else if (token == "\\end_inset") {
211                 lyxerr << "Solitary \\end_inset in line " << lex.getLineNo() << "\n"
212                        << "Missing \\begin_inset?.\n";
213         } else if (token == "\\begin_inset") {
214                 InsetBase * inset = readInset(lex, buf);
215                 if (inset)
216                         par.insertInset(par.size(), inset, font, change);
217                 else {
218                         lex.eatLine();
219                         string line = lex.getString();
220                         buf.error(ErrorItem(_("Unknown Inset"), line,
221                                             par.id(), 0, par.size()));
222                         return 1;
223                 }
224         } else if (token == "\\family") {
225                 lex.next();
226                 font.setLyXFamily(lex.getString());
227         } else if (token == "\\series") {
228                 lex.next();
229                 font.setLyXSeries(lex.getString());
230         } else if (token == "\\shape") {
231                 lex.next();
232                 font.setLyXShape(lex.getString());
233         } else if (token == "\\size") {
234                 lex.next();
235                 font.setLyXSize(lex.getString());
236         } else if (token == "\\lang") {
237                 lex.next();
238                 string const tok = lex.getString();
239                 Language const * lang = languages.getLanguage(tok);
240                 if (lang) {
241                         font.setLanguage(lang);
242                 } else {
243                         font.setLanguage(bp.language);
244                         lex.printError("Unknown language `$$Token'");
245                 }
246         } else if (token == "\\numeric") {
247                 lex.next();
248                 font.setNumber(font.setLyXMisc(lex.getString()));
249         } else if (token == "\\emph") {
250                 lex.next();
251                 font.setEmph(font.setLyXMisc(lex.getString()));
252         } else if (token == "\\bar") {
253                 lex.next();
254                 string const tok = lex.getString();
255
256                 if (tok == "under")
257                         font.setUnderbar(LyXFont::ON);
258                 else if (tok == "no")
259                         font.setUnderbar(LyXFont::OFF);
260                 else if (tok == "default")
261                         font.setUnderbar(LyXFont::INHERIT);
262                 else
263                         lex.printError("Unknown bar font flag "
264                                        "`$$Token'");
265         } else if (token == "\\noun") {
266                 lex.next();
267                 font.setNoun(font.setLyXMisc(lex.getString()));
268         } else if (token == "\\color") {
269                 lex.next();
270                 font.setLyXColor(lex.getString());
271         } else if (token == "\\InsetSpace" || token == "\\SpecialChar") {
272
273                 // Insets don't make sense in a free-spacing context! ---Kayvan
274                 if (par.isFreeSpacing()) {
275                         if (token == "\\InsetSpace")
276                                 par.insertChar(par.size(), ' ', font, change);
277                         else if (lex.isOK()) {
278                                 lex.next();
279                                 string const next_token = lex.getString();
280                                 if (next_token == "\\-")
281                                         par.insertChar(par.size(), '-', font, change);
282                                 else {
283                                         lex.printError("Token `$$Token' "
284                                                        "is in free space "
285                                                        "paragraph layout!");
286                                 }
287                         }
288                 } else {
289                         auto_ptr<InsetBase> inset;
290                         if (token == "\\SpecialChar" )
291                                 inset.reset(new InsetSpecialChar);
292                         else
293                                 inset.reset(new InsetSpace);
294                         inset->read(buf, lex);
295                         par.insertInset(par.size(), inset.release(),
296                                         font, change);
297                 }
298         } else if (token == "\\i") {
299                 auto_ptr<InsetBase> inset(new InsetLatexAccent);
300                 inset->read(buf, lex);
301                 par.insertInset(par.size(), inset.release(), font, change);
302         } else if (token == "\\backslash") {
303                 par.insertChar(par.size(), '\\', font, change);
304         } else if (token == "\\newline") {
305                 auto_ptr<InsetBase> inset(new InsetNewline);
306                 inset->read(buf, lex);
307                 par.insertInset(par.size(), inset.release(), font, change);
308         } else if (token == "\\LyXTable") {
309                 auto_ptr<InsetBase> inset(new InsetTabular(buf));
310                 inset->read(buf, lex);
311                 par.insertInset(par.size(), inset.release(), font, change);
312         } else if (token == "\\bibitem") {
313                 InsetCommandParams p("bibitem", "dummy");
314                 auto_ptr<InsetBibitem> inset(new InsetBibitem(p));
315                 inset->read(buf, lex);
316                 par.insertInset(par.size(), inset.release(), font, change);
317         } else if (token == "\\hfill") {
318                 par.insertInset(par.size(), new InsetHFill, font, change);
319         } else if (token == "\\lyxline") {
320                 par.insertInset(par.size(), new InsetLine, font, change);
321         } else if (token == "\\newpage") {
322                 par.insertInset(par.size(), new InsetPagebreak, font, change);
323         } else if (token == "\\change_unchanged") {
324                 // Hack ! Needed for empty paragraphs :/
325                 // FIXME: is it still ??
326                 if (!par.size())
327                         par.cleanChanges();
328                 change = Change(Change::UNCHANGED);
329         } else if (token == "\\change_inserted") {
330                 lex.nextToken();
331                 std::istringstream is(lex.getString());
332                 int aid;
333                 lyx::time_type ct;
334                 is >> aid >> ct;
335                 change = Change(Change::INSERTED, bp.author_map[aid], ct);
336         } else if (token == "\\change_deleted") {
337                 lex.nextToken();
338                 std::istringstream is(lex.getString());
339                 int aid;
340                 lyx::time_type ct;
341                 is >> aid >> ct;
342                 change = Change(Change::DELETED, bp.author_map[aid], ct);
343         } else {
344                 lex.eatLine();
345                 buf.error(ErrorItem(_("Unknown token"),
346                         bformat(_("Unknown token: %1$s %2$s\n"), token, lex.getString()),
347                         par.id(), 0, par.size()));
348                 return 1;
349         }
350         return 0;
351 }
352
353
354 int readParagraph(Buffer const & buf, Paragraph & par, LyXLex & lex)
355 {
356         int unknown = 0;
357
358         lex.nextToken();
359         string token = lex.getString();
360         LyXFont font;
361
362         while (lex.isOK()) {
363
364                 unknown += readParToken(buf, par, lex, token, font);
365
366                 lex.nextToken();
367                 token = lex.getString();
368
369                 if (token.empty())
370                         continue;
371
372                 if (token == "\\end_layout") {
373                         //Ok, paragraph finished
374                         break;
375                 }
376
377                 lyxerr[Debug::PARSER] << "Handling paragraph token: `"
378                                       << token << '\'' << endl;
379                 if (token == "\\begin_layout" || token == "\\end_document"
380                     || token == "\\end_inset" || token == "\\begin_deeper"
381                     || token == "\\end_deeper") {
382                         lex.pushToken(token);
383                         lyxerr << "Paragraph ended in line "
384                                << lex.getLineNo() << "\n"
385                                << "Missing \\end_layout.\n";
386                         break;
387                 }
388         }
389
390         return unknown;
391 }
392
393
394 } // namespace anon
395
396
397 BufferView * LyXText::bv()
398 {
399         BOOST_ASSERT(bv_owner != 0);
400         return bv_owner;
401 }
402
403
404 BufferView * LyXText::bv() const
405 {
406         BOOST_ASSERT(bv_owner != 0);
407         return bv_owner;
408 }
409
410
411 double LyXText::spacing(Paragraph const & par) const
412 {
413         if (par.params().spacing().isDefault())
414                 return bv()->buffer()->params().spacing().getValue();
415         return par.params().spacing().getValue();
416 }
417
418
419 void LyXText::updateParPositions()
420 {
421         par_type pit = 0;
422         par_type end = pars_.size();
423         for (height_ = 0; pit != end; ++pit) {
424                 pars_[pit].y = height_;
425                 height_ += pars_[pit].height;
426         }
427 }
428
429
430 int LyXText::width() const
431 {
432         return width_;
433 }
434
435
436 int LyXText::height() const
437 {
438         return height_;
439 }
440
441
442 int LyXText::singleWidth(Paragraph const & par, pos_type pos) const
443 {
444         return singleWidth(par, pos, par.getChar(pos), getFont(par, pos));
445 }
446
447
448 int LyXText::singleWidth(Paragraph const & par,
449                          pos_type pos, char c, LyXFont const & font) const
450 {
451         BOOST_ASSERT(pos < par.size());
452
453         // The most common case is handled first (Asger)
454         if (IsPrintable(c)) {
455                 if (font.language()->RightToLeft()) {
456                         if ((lyxrc.font_norm_type == LyXRC::ISO_8859_6_8 ||
457                              lyxrc.font_norm_type == LyXRC::ISO_10646_1)
458                             && font.language()->lang() == "arabic") {
459                                 if (Encodings::IsComposeChar_arabic(c))
460                                         return 0;
461                                 else
462                                         c = par.transformChar(c, pos);
463                         } else if (font.language()->lang() == "hebrew" &&
464                                    Encodings::IsComposeChar_hebrew(c))
465                                 return 0;
466                 }
467                 return font_metrics::width(c, font);
468         }
469
470         if (c == Paragraph::META_INSET)
471                 return par.getInset(pos)->width();
472
473         if (IsSeparatorChar(c))
474                 c = ' ';
475         return font_metrics::width(c, font);
476 }
477
478
479 int LyXText::leftMargin(par_type pit) const
480 {
481         return leftMargin(pit, pars_[pit].size());
482 }
483
484
485 int LyXText::leftMargin(par_type const pit, pos_type const pos) const
486 {
487         Paragraph const & par = pars_[pit];
488         LyXTextClass const & tclass =
489                 bv()->buffer()->params().getLyXTextClass();
490         LyXLayout_ptr const & layout = par.layout();
491
492         string parindent = layout->parindent;
493
494         int l_margin = 0;
495
496         if (xo_ == 0)
497                 l_margin += changebarMargin();
498
499         l_margin += font_metrics::signedWidth(tclass.leftmargin(), tclass.defaultfont());
500
501         if (par.getDepth() != 0) {
502         // find the next level paragraph
503         par_type newpar = outerHook(pit, pars_);
504                 if (newpar != par_type(pars_.size())) {
505                         if (pars_[newpar].layout()->isEnvironment()) {
506                                 l_margin = leftMargin(newpar);
507                         }
508                         if (par.layout() == tclass.defaultLayout()) {
509                                 if (pars_[newpar].params().noindent())
510                                         parindent.erase();
511                                 else
512                                         parindent = pars_[newpar].layout()->parindent;
513                         }
514                 }
515         }
516
517         LyXFont const labelfont = getLabelFont(par);
518         switch (layout->margintype) {
519         case MARGIN_DYNAMIC:
520                 if (!layout->leftmargin.empty())
521                         l_margin += font_metrics::signedWidth(layout->leftmargin,
522                                                   tclass.defaultfont());
523                 if (!par.getLabelstring().empty()) {
524                         l_margin += font_metrics::signedWidth(layout->labelindent,
525                                                   labelfont);
526                         l_margin += font_metrics::width(par.getLabelstring(),
527                                             labelfont);
528                         l_margin += font_metrics::width(layout->labelsep, labelfont);
529                 }
530                 break;
531
532         case MARGIN_MANUAL:
533                 l_margin += font_metrics::signedWidth(layout->labelindent, labelfont);
534                 // The width of an empty par, even with manual label, should be 0
535                 if (!par.empty() && pos >= par.beginOfBody()) {
536                         if (!par.getLabelWidthString().empty()) {
537                                 l_margin += font_metrics::width(par.getLabelWidthString(),
538                                                labelfont);
539                                 l_margin += font_metrics::width(layout->labelsep, labelfont);
540                         }
541                 }
542                 break;
543
544         case MARGIN_STATIC:
545                 l_margin += font_metrics::signedWidth(layout->leftmargin, tclass.defaultfont()) * 4
546                         / (par.getDepth() + 4);
547                 break;
548
549         case MARGIN_FIRST_DYNAMIC:
550                 if (layout->labeltype == LABEL_MANUAL) {
551                         if (pos >= par.beginOfBody()) {
552                                 l_margin += font_metrics::signedWidth(layout->leftmargin,
553                                                           labelfont);
554                         } else {
555                                 l_margin += font_metrics::signedWidth(layout->labelindent,
556                                                           labelfont);
557                         }
558                 } else if (pos != 0
559                            // Special case to fix problems with
560                            // theorems (JMarc)
561                            || (layout->labeltype == LABEL_STATIC
562                                && layout->latextype == LATEX_ENVIRONMENT
563                                && !isFirstInSequence(pit, pars_))) {
564                         l_margin += font_metrics::signedWidth(layout->leftmargin,
565                                                   labelfont);
566                 } else if (layout->labeltype != LABEL_TOP_ENVIRONMENT
567                            && layout->labeltype != LABEL_BIBLIO
568                            && layout->labeltype !=
569                            LABEL_CENTERED_TOP_ENVIRONMENT) {
570                         l_margin += font_metrics::signedWidth(layout->labelindent,
571                                                   labelfont);
572                         l_margin += font_metrics::width(layout->labelsep, labelfont);
573                         l_margin += font_metrics::width(par.getLabelstring(),
574                                             labelfont);
575                 }
576                 break;
577
578         case MARGIN_RIGHT_ADDRESS_BOX: {
579 #if 0
580                 // ok, a terrible hack. The left margin depends on the widest
581                 // row in this paragraph.
582                 RowList::iterator rit = par.rows.begin();
583                 RowList::iterator end = par.rows.end();
584 #ifdef WITH_WARNINGS
585 #warning This is wrong.
586 #endif
587                 int minfill = maxwidth_;
588                 for ( ; rit != end; ++rit)
589                         if (rit->fill() < minfill)
590                                 minfill = rit->fill();
591                 l_margin += font_metrics::signedWidth(layout->leftmargin,
592                         tclass.defaultfont());
593                 l_margin += minfill;
594 #endif
595                 // also wrong, but much shorter.
596                 l_margin += maxwidth_ / 2;
597                 break;
598         }
599         }
600
601         if (!par.params().leftIndent().zero())
602                 l_margin += par.params().leftIndent().inPixels(maxwidth_);
603
604         LyXAlignment align;
605
606         if (par.params().align() == LYX_ALIGN_LAYOUT)
607                 align = layout->align;
608         else
609                 align = par.params().align();
610
611         // set the correct parindent
612         if (pos == 0
613             && (layout->labeltype == LABEL_NO_LABEL
614                || layout->labeltype == LABEL_TOP_ENVIRONMENT
615                || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
616                || (layout->labeltype == LABEL_STATIC
617                    && layout->latextype == LATEX_ENVIRONMENT
618                    && !isFirstInSequence(pit, pars_)))
619             && align == LYX_ALIGN_BLOCK
620             && !par.params().noindent()
621             // in tabulars and ert paragraphs are never indented!
622             && (par.ownerCode() != InsetBase::TEXT_CODE
623                     && par.ownerCode() != InsetBase::ERT_CODE)
624             && (par.layout() != tclass.defaultLayout()
625                 || bv()->buffer()->params().paragraph_separation ==
626                    BufferParams::PARSEP_INDENT))
627         {
628                 l_margin += font_metrics::signedWidth(parindent, tclass.defaultfont());
629         }
630
631         return l_margin;
632 }
633
634
635 int LyXText::rightMargin(Paragraph const & par) const
636 {
637         LyXTextClass const & tclass = bv()->buffer()->params().getLyXTextClass();
638
639         // We do not want rightmargins on inner texts.
640         if (bv()->text() != this)
641                 return 0;
642
643         int const r_margin =
644                 ::rightMargin()
645                 + font_metrics::signedWidth(tclass.rightmargin(),
646                                             tclass.defaultfont())
647                 + font_metrics::signedWidth(par.layout()->rightmargin,
648                                             tclass.defaultfont())
649                 * 4 / (par.getDepth() + 4);
650
651         return r_margin;
652
653 }
654
655
656 int LyXText::labelEnd(par_type const pit) const
657 {
658         // labelEnd is only needed if the layout fills a flushleft label.
659         if (pars_[pit].layout()->margintype != MARGIN_MANUAL)
660                 return 0;
661         // return the beginning of the body
662         return leftMargin(pit);
663 }
664
665
666 namespace {
667
668 // this needs special handling - only newlines count as a break point
669 pos_type addressBreakPoint(pos_type i, Paragraph const & par)
670 {
671         pos_type const end = par.size();
672
673         for (; i < end; ++i)
674                 if (par.isNewline(i))
675                         return i + 1;
676
677         return end;
678 }
679
680 };
681
682
683 void LyXText::rowBreakPoint(par_type const pit, Row & row) const
684 {
685         Paragraph const & par = pars_[pit];
686         pos_type const end = par.size();
687         pos_type const pos = row.pos();
688         if (pos == end) {
689                 row.endpos(end);
690                 return;
691         }
692
693         // maximum pixel width of a row
694         int width = maxwidth_ - rightMargin(par); // - leftMargin(pit, row);
695         if (width < 0) {
696                 row.endpos(end);
697                 return;
698         }
699
700         LyXLayout_ptr const & layout = par.layout();
701
702         if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX) {
703                 row.endpos(addressBreakPoint(pos, par));
704                 return;
705         }
706
707         pos_type const body_pos = par.beginOfBody();
708
709
710         // Now we iterate through until we reach the right margin
711         // or the end of the par, then choose the possible break
712         // nearest that.
713
714         int const left = leftMargin(pit, pos);
715         int x = left;
716
717         // pixel width since last breakpoint
718         int chunkwidth = 0;
719
720         FontIterator fi = FontIterator(*this, pit, pos);
721         pos_type point = end;
722         pos_type i = pos;
723         for ( ; i < end; ++i, ++fi) {
724                 char const c = par.getChar(i);
725
726                 {
727                         int thiswidth = singleWidth(par, i, c, *fi);
728
729                         // add the auto-hfill from label end to the body
730                         if (body_pos && i == body_pos) {
731                                 int add = font_metrics::width(layout->labelsep, getLabelFont(par));
732                                 if (par.isLineSeparator(i - 1))
733                                         add -= singleWidth(par, i - 1);
734
735                                 add = std::max(add, labelEnd(pit) - x);
736                                 thiswidth += add;
737                         }
738
739                         x += thiswidth;
740                         chunkwidth += thiswidth;
741                 }
742
743                 // break before a character that will fall off
744                 // the right of the row
745                 if (x >= width) {
746                         // if no break before, break here
747                         if (point == end || chunkwidth >= width - left) {
748                                 if (i > pos)
749                                         point = i;
750                                 else
751                                         point = i + 1;
752
753                         }
754                         // exit on last registered breakpoint:
755                         break;
756                 }
757
758                 if (par.isNewline(i)) {
759                         point = i + 1;
760                         break;
761                 }
762                 // Break before...
763                 if (i + 1 < end) {
764                         if (par.isInset(i + 1) && par.getInset(i + 1)->display()) {
765                                 point = i + 1;
766                                 break;
767                         }
768                         // ...and after.
769                         if (par.isInset(i) && par.getInset(i)->display()) {
770                                 point = i + 1;
771                                 break;
772                         }
773                 }
774
775                 if (!par.isInset(i) || par.getInset(i)->isChar()) {
776                         // some insets are line separators too
777                         if (par.isLineSeparator(i)) {
778                                 // register breakpoint:
779                                 point = i + 1;
780                                 chunkwidth = 0;
781                         }
782                 }
783         }
784
785         // maybe found one, but the par is short enough.
786         if (i == end && x < width)
787                 point = end;
788
789         // manual labels cannot be broken in LaTeX. But we
790         // want to make our on-screen rendering of footnotes
791         // etc. still break
792         if (body_pos && point < body_pos)
793                 point = body_pos;
794
795         row.endpos(point);
796 }
797
798
799 void LyXText::setRowWidth(par_type const pit, Row & row) const
800 {
801         // get the pure distance
802         pos_type const end = row.endpos();
803
804         Paragraph const & par = pars_[pit];
805         string labelsep = par.layout()->labelsep;
806         int w = leftMargin(pit, row.pos());
807
808         pos_type const body_pos = par.beginOfBody();
809         pos_type i = row.pos();
810
811         if (i < end) {
812                 FontIterator fi = FontIterator(*this, pit, i);
813                 for ( ; i < end; ++i, ++fi) {
814                         if (body_pos > 0 && i == body_pos) {
815                                 w += font_metrics::width(labelsep, getLabelFont(par));
816                                 if (par.isLineSeparator(i - 1))
817                                         w -= singleWidth(par, i - 1);
818                                 w = max(w, labelEnd(pit));
819                         }
820                         char const c = par.getChar(i);
821                         w += singleWidth(par, i, c, *fi);
822                 }
823         }
824
825         if (body_pos > 0 && body_pos >= end) {
826                 w += font_metrics::width(labelsep, getLabelFont(par));
827                 if (end > 0 && par.isLineSeparator(end - 1))
828                         w -= singleWidth(par, end - 1);
829                 w = max(w, labelEnd(pit));
830         }
831
832         row.width(w + rightMargin(par));
833 }
834
835
836 // returns the minimum space a manual label needs on the screen in pixel
837 int LyXText::labelFill(Paragraph const & par, Row const & row) const
838 {
839         pos_type last = par.beginOfBody();
840
841         BOOST_ASSERT(last > 0);
842
843         // -1 because a label ends with a space that is in the label
844         --last;
845
846         // a separator at this end does not count
847         if (par.isLineSeparator(last))
848                 --last;
849
850         int w = 0;
851         for (pos_type i = row.pos(); i <= last; ++i)
852                 w += singleWidth(par, i);
853
854         string const & label = par.params().labelWidthString();
855         if (label.empty())
856                 return 0;
857
858         return max(0, font_metrics::width(label, getLabelFont(par)) - w);
859 }
860
861
862 LColor_color LyXText::backgroundColor() const
863 {
864         return LColor_color(LColor::color(background_color_));
865 }
866
867
868 void LyXText::setHeightOfRow(par_type const pit, Row & row)
869 {
870         Paragraph const & par = pars_[pit];
871         // get the maximum ascent and the maximum descent
872         double layoutasc = 0;
873         double layoutdesc = 0;
874         double const dh = defaultRowHeight();
875
876         // ok, let us initialize the maxasc and maxdesc value.
877         // Only the fontsize count. The other properties
878         // are taken from the layoutfont. Nicer on the screen :)
879         LyXLayout_ptr const & layout = par.layout();
880
881         // as max get the first character of this row then it can
882         // increase but not decrease the height. Just some point to
883         // start with so we don't have to do the assignment below too
884         // often.
885         LyXFont font = getFont(par, row.pos());
886         LyXFont::FONT_SIZE const tmpsize = font.size();
887         font = getLayoutFont(pit);
888         LyXFont::FONT_SIZE const size = font.size();
889         font.setSize(tmpsize);
890
891         LyXFont labelfont = getLabelFont(par);
892
893         // these are minimum values
894         double const spacing_val = layout->spacing.getValue() * spacing(par);
895         //lyxerr << "spacing_val = " << spacing_val << endl;
896         int maxasc  = int(font_metrics::maxAscent(font)  * spacing_val);
897         int maxdesc = int(font_metrics::maxDescent(font) * spacing_val);
898
899         // insets may be taller
900         InsetList::const_iterator ii = par.insetlist.begin();
901         InsetList::const_iterator iend = par.insetlist.end();
902         for ( ; ii != iend; ++ii) {
903                 if (ii->pos >= row.pos() && ii->pos < row.endpos()) {
904                         maxasc  = max(maxasc,  ii->inset->ascent());
905                         maxdesc = max(maxdesc, ii->inset->descent());
906                 }
907         }
908
909         // Check if any custom fonts are larger (Asger)
910         // This is not completely correct, but we can live with the small,
911         // cosmetic error for now.
912         int labeladdon = 0;
913         pos_type const pos_end = row.endpos();
914
915         LyXFont::FONT_SIZE maxsize =
916                 par.highestFontInRange(row.pos(), pos_end, size);
917         if (maxsize > font.size()) {
918                 font.setSize(maxsize);
919                 maxasc  = max(maxasc,  font_metrics::maxAscent(font));
920                 maxdesc = max(maxdesc, font_metrics::maxDescent(font));
921         }
922
923         // This is nicer with box insets:
924         ++maxasc;
925         ++maxdesc;
926
927         row.ascent_of_text(maxasc);
928
929         // is it a top line?
930         if (row.pos() == 0) {
931                 BufferParams const & bufparams = bv()->buffer()->params();
932                 // some parksips VERY EASY IMPLEMENTATION
933                 if (bv()->buffer()->params().paragraph_separation
934                     == BufferParams::PARSEP_SKIP
935                         && pit != 0
936                         && ((layout->isParagraph() && par.getDepth() == 0)
937                             || (pars_[pit - 1].layout()->isParagraph()
938                                 && pars_[pit - 1].getDepth() == 0)))
939                 {
940                                 maxasc += bufparams.getDefSkip().inPixels(*bv());
941                 }
942
943                 if (pars_[pit].params().startOfAppendix())
944                         maxasc += int(3 * dh);
945
946                 // This is special code for the chapter, since the label of this
947                 // layout is printed in an extra row
948                 if (layout->counter == "chapter" && bufparams.secnumdepth >= 0) {
949                         labeladdon = int(font_metrics::maxHeight(labelfont)
950                                      * layout->spacing.getValue()
951                                      * spacing(par));
952                 }
953
954                 // special code for the top label
955                 if ((layout->labeltype == LABEL_TOP_ENVIRONMENT
956                      || layout->labeltype == LABEL_BIBLIO
957                      || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
958                     && isFirstInSequence(pit, paragraphs())
959                     && !par.getLabelstring().empty())
960                 {
961                         labeladdon = int(
962                                   font_metrics::maxHeight(labelfont)
963                                         * layout->spacing.getValue()
964                                         * spacing(par)
965                                 + (layout->topsep + layout->labelbottomsep) * dh);
966                 }
967
968                 // Add the layout spaces, for example before and after
969                 // a section, or between the items of a itemize or enumerate
970                 // environment.
971
972                 par_type prev = depthHook(pit, pars_, par.getDepth());
973                 if (prev != pit
974                     && pars_[prev].layout() == layout
975                     && pars_[prev].getDepth() == par.getDepth()
976                     && pars_[prev].getLabelWidthString() == par.getLabelWidthString())
977                 {
978                         layoutasc = layout->itemsep * dh;
979                 } else if (pit != 0 || row.pos() != 0) {
980                         if (layout->topsep > 0)
981                                 layoutasc = layout->topsep * dh;
982                 }
983
984                 prev = outerHook(pit, pars_);
985                 if (prev != par_type(pars_.size())) {
986                         maxasc += int(pars_[prev].layout()->parsep * dh);
987                 } else if (pit != 0) {
988                         if (pars_[pit - 1].getDepth() != 0 ||
989                                         pars_[pit - 1].layout() == layout) {
990                                 maxasc += int(layout->parsep * dh);
991                         }
992                 }
993         }
994
995         // is it a bottom line?
996         if (row.endpos() >= par.size()) {
997                 // add the layout spaces, for example before and after
998                 // a section, or between the items of a itemize or enumerate
999                 // environment
1000                 par_type nextpit = pit + 1;
1001                 if (nextpit != par_type(pars_.size())) {
1002                         par_type cpit = pit;
1003                         double usual = 0;
1004                         double unusual = 0;
1005
1006                         if (pars_[cpit].getDepth() > pars_[nextpit].getDepth()) {
1007                                 usual = pars_[cpit].layout()->bottomsep * dh;
1008                                 cpit = depthHook(cpit, paragraphs(), pars_[nextpit].getDepth());
1009                                 if (pars_[cpit].layout() != pars_[nextpit].layout()
1010                                         || pars_[nextpit].getLabelWidthString() != pars_[cpit].getLabelWidthString())
1011                                 {
1012                                         unusual = pars_[cpit].layout()->bottomsep * dh;
1013                                 }
1014                                 layoutdesc = max(unusual, usual);
1015                         } else if (pars_[cpit].getDepth() == pars_[nextpit].getDepth()) {
1016                                 if (pars_[cpit].layout() != pars_[nextpit].layout()
1017                                         || pars_[nextpit].getLabelWidthString() != pars_[cpit].getLabelWidthString())
1018                                         layoutdesc = int(pars_[cpit].layout()->bottomsep * dh);
1019                         }
1020                 }
1021         }
1022
1023         // incalculate the layout spaces
1024         maxasc  += int(layoutasc  * 2 / (2 + pars_[pit].getDepth()));
1025         maxdesc += int(layoutdesc * 2 / (2 + pars_[pit].getDepth()));
1026
1027         row.height(maxasc + maxdesc + labeladdon);
1028         row.baseline(maxasc + labeladdon);
1029         row.top_of_text(row.baseline() - font_metrics::maxAscent(font));
1030 }
1031
1032
1033 namespace {
1034
1035 }
1036
1037 void LyXText::breakParagraph(LCursor & cur, char keep_layout)
1038 {
1039         BOOST_ASSERT(this == cur.text());
1040         // allow only if at start or end, or all previous is new text
1041         Paragraph & cpar = cur.paragraph();
1042         par_type cpit = cur.par();
1043
1044         if (cur.pos() != 0 && cur.pos() != cur.lastpos()
1045             && cpar.isChangeEdited(0, cur.pos()))
1046                 return;
1047
1048         LyXTextClass const & tclass = cur.buffer().params().getLyXTextClass();
1049         LyXLayout_ptr const & layout = cpar.layout();
1050
1051         // this is only allowed, if the current paragraph is not empty
1052         // or caption and if it has not the keepempty flag active
1053         if (cur.lastpos() == 0 && !cpar.allowEmpty()
1054            && layout->labeltype != LABEL_SENSITIVE)
1055                 return;
1056
1057         // a layout change may affect also the following paragraph
1058         recUndo(cur.par(), undoSpan(cur.par()) - 1);
1059
1060         // Always break behind a space
1061         // It is better to erase the space (Dekel)
1062         if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
1063                 cpar.erase(cur.pos());
1064
1065         // break the paragraph
1066         if (keep_layout)
1067                 keep_layout = 2;
1068         else
1069                 keep_layout = layout->isEnvironment();
1070
1071         // we need to set this before we insert the paragraph. IMO the
1072         // breakParagraph call should return a bool if it inserts the
1073         // paragraph before or behind and we should react on that one
1074         // but we can fix this in 1.3.0 (Jug 20020509)
1075         bool const isempty = cpar.allowEmpty() && cpar.empty();
1076         ::breakParagraph(cur.buffer().params(), paragraphs(), cpit,
1077                          cur.pos(), keep_layout);
1078
1079         cpit = cur.par();
1080         par_type next_par = cpit + 1;
1081
1082         // well this is the caption hack since one caption is really enough
1083         if (layout->labeltype == LABEL_SENSITIVE) {
1084                 if (cur.pos() == 0)
1085                         // set to standard-layout
1086                         pars_[cpit].applyLayout(tclass.defaultLayout());
1087                 else
1088                         // set to standard-layout
1089                         pars_[next_par].applyLayout(tclass.defaultLayout());
1090         }
1091
1092         // if the cursor is at the beginning of a row without prior newline,
1093         // move one row up!
1094         // This touches only the screen-update. Otherwise we would may have
1095         // an empty row on the screen
1096         if (cur.pos() != 0 && cur.textRow().pos() == cur.pos()
1097             && !pars_[cpit].isNewline(cur.pos() - 1))
1098         {
1099                 cursorLeft(cur);
1100         }
1101
1102         while (!pars_[next_par].empty() && pars_[next_par].isNewline(0))
1103                 pars_[next_par].erase(0);
1104
1105         updateCounters();
1106         redoParagraph(cpit);
1107         redoParagraph(next_par);
1108
1109         // This check is necessary. Otherwise the new empty paragraph will
1110         // be deleted automatically. And it is more friendly for the user!
1111         if (cur.pos() != 0 || isempty)
1112                 setCursor(cur, cur.par() + 1, 0);
1113         else
1114                 setCursor(cur, cur.par(), 0);
1115 }
1116
1117
1118 // convenience function
1119 void LyXText::redoParagraph(LCursor & cur)
1120 {
1121         BOOST_ASSERT(this == cur.text());
1122         cur.clearSelection();
1123         redoParagraph(cur.par());
1124         setCursorIntern(cur, cur.par(), cur.pos());
1125 }
1126
1127
1128 // insert a character, moves all the following breaks in the
1129 // same Paragraph one to the right and make a rebreak
1130 void LyXText::insertChar(LCursor & cur, char c)
1131 {
1132         BOOST_ASSERT(this == cur.text());
1133         BOOST_ASSERT(c != Paragraph::META_INSET);
1134
1135         recordUndo(cur, Undo::INSERT);
1136
1137         Paragraph & par = cur.paragraph();
1138         // try to remove this
1139         par_type const pit = cur.par();
1140
1141         bool const freeSpacing = par.layout()->free_spacing ||
1142                 par.isFreeSpacing();
1143
1144         if (lyxrc.auto_number) {
1145                 static string const number_operators = "+-/*";
1146                 static string const number_unary_operators = "+-";
1147                 static string const number_seperators = ".,:";
1148
1149                 if (current_font.number() == LyXFont::ON) {
1150                         if (!IsDigit(c) && !contains(number_operators, c) &&
1151                             !(contains(number_seperators, c) &&
1152                               cur.pos() != 0 &&
1153                               cur.pos() != cur.lastpos() &&
1154                               getFont(par, cur.pos()).number() == LyXFont::ON &&
1155                               getFont(par, cur.pos() - 1).number() == LyXFont::ON)
1156                            )
1157                                 number(cur); // Set current_font.number to OFF
1158                 } else if (IsDigit(c) &&
1159                            real_current_font.isVisibleRightToLeft()) {
1160                         number(cur); // Set current_font.number to ON
1161
1162                         if (cur.pos() != 0) {
1163                                 char const c = par.getChar(cur.pos() - 1);
1164                                 if (contains(number_unary_operators, c) &&
1165                                     (cur.pos() == 1
1166                                      || par.isSeparator(cur.pos() - 2)
1167                                      || par.isNewline(cur.pos() - 2))
1168                                   ) {
1169                                         setCharFont(pit, cur.pos() - 1, current_font);
1170                                 } else if (contains(number_seperators, c)
1171                                      && cur.pos() >= 2
1172                                      && getFont(par, cur.pos() - 2).number() == LyXFont::ON) {
1173                                         setCharFont(pit, cur.pos() - 1, current_font);
1174                                 }
1175                         }
1176                 }
1177         }
1178
1179         // First check, if there will be two blanks together or a blank at
1180         // the beginning of a paragraph.
1181         // I decided to handle blanks like normal characters, the main
1182         // difference are the special checks when calculating the row.fill
1183         // (blank does not count at the end of a row) and the check here
1184
1185         // The bug is triggered when we type in a description environment:
1186         // The current_font is not changed when we go from label to main text
1187         // and it should (along with realtmpfont) when we type the space.
1188         // CHECK There is a bug here! (Asger)
1189
1190         // store the current font.  This is because of the use of cursor
1191         // movements. The moving cursor would refresh the current font
1192         LyXFont realtmpfont = real_current_font;
1193         LyXFont rawtmpfont = current_font;
1194
1195         // When the free-spacing option is set for the current layout,
1196         // disable the double-space checking
1197         if (!freeSpacing && IsLineSeparatorChar(c)) {
1198                 if (cur.pos() == 0) {
1199                         static bool sent_space_message = false;
1200                         if (!sent_space_message) {
1201                                 cur.message(_("You cannot insert a space at the "
1202                                         "beginning of a paragraph. Please read the Tutorial."));
1203                                 sent_space_message = true;
1204                                 return;
1205                         }
1206                 }
1207                 BOOST_ASSERT(cur.pos() > 0);
1208                 if (par.isLineSeparator(cur.pos() - 1)
1209                     || par.isNewline(cur.pos() - 1)) {
1210                         static bool sent_space_message = false;
1211                         if (!sent_space_message) {
1212                                 cur.message(_("You cannot type two spaces this way. "
1213                                         "Please read the Tutorial."));
1214                                 sent_space_message = true;
1215                         }
1216                         return;
1217                 }
1218         }
1219
1220         par.insertChar(cur.pos(), c, rawtmpfont);
1221
1222         current_font = rawtmpfont;
1223         real_current_font = realtmpfont;
1224         redoParagraph(cur);
1225         setCursor(cur, cur.par(), cur.pos() + 1, false, cur.boundary());
1226         charInserted();
1227 }
1228
1229
1230 void LyXText::charInserted()
1231 {
1232         // Here we call finishUndo for every 20 characters inserted.
1233         // This is from my experience how emacs does it. (Lgb)
1234         static unsigned int counter;
1235         if (counter < 20) {
1236                 ++counter;
1237         } else {
1238                 finishUndo();
1239                 counter = 0;
1240         }
1241 }
1242
1243
1244 RowMetrics LyXText::computeRowMetrics(par_type const pit, Row const & row) const
1245 {
1246         RowMetrics result;
1247         Paragraph const & par = pars_[pit];
1248
1249         double w = width_ - row.width();
1250
1251         bool const is_rtl = isRTL(par);
1252         if (is_rtl)
1253                 result.x = rightMargin(par);
1254         else
1255                 result.x = leftMargin(pit, row.pos());
1256
1257         // is there a manual margin with a manual label
1258         LyXLayout_ptr const & layout = par.layout();
1259
1260         if (layout->margintype == MARGIN_MANUAL
1261             && layout->labeltype == LABEL_MANUAL) {
1262                 /// We might have real hfills in the label part
1263                 int nlh = numberOfLabelHfills(par, row);
1264
1265                 // A manual label par (e.g. List) has an auto-hfill
1266                 // between the label text and the body of the
1267                 // paragraph too.
1268                 // But we don't want to do this auto hfill if the par
1269                 // is empty.
1270                 if (!par.empty())
1271                         ++nlh;
1272
1273                 if (nlh && !par.getLabelWidthString().empty())
1274                         result.label_hfill = labelFill(par, row) / double(nlh);
1275         }
1276
1277         // are there any hfills in the row?
1278         int const nh = numberOfHfills(par, row);
1279
1280         if (nh) {
1281                 if (w > 0)
1282                         result.hfill = w / nh;
1283         // we don't have to look at the alignment if it is ALIGN_LEFT and
1284         // if the row is already larger then the permitted width as then
1285         // we force the LEFT_ALIGN'edness!
1286         } else if (int(row.width()) < maxwidth_) {
1287                 // is it block, flushleft or flushright?
1288                 // set x how you need it
1289                 int align;
1290                 if (par.params().align() == LYX_ALIGN_LAYOUT)
1291                         align = layout->align;
1292                 else
1293                         align = par.params().align();
1294
1295                 // Display-style insets should always be on a centred row
1296                 // The test on par.size() is to catch zero-size pars, which
1297                 // would trigger the assert in Paragraph::getInset().
1298                 //inset = par.size() ? par.getInset(row.pos()) : 0;
1299                 if (!par.empty()
1300                     && par.isInset(row.pos())
1301                     && par.getInset(row.pos())->display())
1302                 {
1303                         align = LYX_ALIGN_CENTER;
1304                 }
1305
1306                 switch (align) {
1307                 case LYX_ALIGN_BLOCK: {
1308                         int const ns = numberOfSeparators(par, row);
1309                         bool disp_inset = false;
1310                         if (row.endpos() < par.size()) {
1311                                 InsetBase const * in = par.getInset(row.endpos());
1312                                 if (in)
1313                                         disp_inset = in->display();
1314                         }
1315                         // If we have separators, this is not the last row of a
1316                         // par, does not end in newline, and is not row above a
1317                         // display inset... then stretch it
1318                         if (ns
1319                             && row.endpos() < par.size()
1320                             && !par.isNewline(row.endpos() - 1)
1321                             && !disp_inset
1322                                 ) {
1323                                 result.separator = w / ns;
1324                         } else if (is_rtl) {
1325                                 result.x += w;
1326                         }
1327                         break;
1328                 }
1329                 case LYX_ALIGN_RIGHT:
1330                         result.x += w;
1331                         break;
1332                 case LYX_ALIGN_CENTER:
1333                         result.x += w / 2;
1334                         break;
1335                 }
1336         }
1337
1338         bidi.computeTables(par, *bv()->buffer(), row);
1339         if (is_rtl) {
1340                 pos_type body_pos = par.beginOfBody();
1341                 pos_type end = row.endpos();
1342
1343                 if (body_pos > 0
1344                     && (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1345                 {
1346                         result.x += font_metrics::width(layout->labelsep, getLabelFont(par));
1347                         if (body_pos <= end)
1348                                 result.x += result.label_hfill;
1349                 }
1350         }
1351
1352         return result;
1353 }
1354
1355
1356 // the cursor set functions have a special mechanism. When they
1357 // realize, that you left an empty paragraph, they will delete it.
1358
1359 void LyXText::cursorRightOneWord(LCursor & cur)
1360 {
1361         BOOST_ASSERT(this == cur.text());
1362         if (cur.pos() == cur.lastpos() && cur.par() != cur.lastpar()) {
1363                 ++cur.par();
1364                 cur.pos() = 0;
1365         } else {
1366                 // Skip through initial nonword stuff.
1367                 // Treat floats and insets as words.
1368                 while (cur.pos() != cur.lastpos() && !cur.paragraph().isWord(cur.pos()))
1369                         ++cur.pos();
1370                 // Advance through word.
1371                 while (cur.pos() != cur.lastpos() && cur.paragraph().isWord(cur.pos()))
1372                         ++cur.pos();
1373         }
1374         setCursor(cur, cur.par(), cur.pos());
1375 }
1376
1377
1378 void LyXText::cursorLeftOneWord(LCursor & cur)
1379 {
1380         BOOST_ASSERT(this == cur.text());
1381         if (cur.pos() == 0 && cur.par() != 0) {
1382                 --cur.par();
1383                 cur.pos() = cur.lastpos();
1384         } else {
1385                 // Skip through initial nonword stuff.
1386                 // Treat floats and insets as words.
1387                 while (cur.pos() != 0 && !cur.paragraph().isWord(cur.pos() - 1))
1388                         --cur.pos();
1389                 // Advance through word.
1390                 while (cur.pos() != 0 && cur.paragraph().isWord(cur.pos() - 1))
1391                         --cur.pos();
1392         }
1393         setCursor(cur, cur.par(), cur.pos());
1394 }
1395
1396
1397 void LyXText::selectWord(LCursor & cur, word_location loc)
1398 {
1399         BOOST_ASSERT(this == cur.text());
1400         CursorSlice from = cur.top();
1401         CursorSlice to = cur.top();
1402         getWord(from, to, loc);
1403         if (cur.top() != from)
1404                 setCursor(cur, from.par(), from.pos());
1405         if (to == from)
1406                 return;
1407         cur.resetAnchor();
1408         setCursor(cur, to.par(), to.pos());
1409         cur.setSelection();
1410 }
1411
1412
1413 // Select the word currently under the cursor when no
1414 // selection is currently set
1415 bool LyXText::selectWordWhenUnderCursor(LCursor & cur, word_location loc)
1416 {
1417         BOOST_ASSERT(this == cur.text());
1418         if (cur.selection())
1419                 return false;
1420         selectWord(cur, loc);
1421         return cur.selection();
1422 }
1423
1424
1425 void LyXText::acceptChange(LCursor & cur)
1426 {
1427         BOOST_ASSERT(this == cur.text());
1428         if (!cur.selection() && cur.lastpos() != 0)
1429                 return;
1430
1431         CursorSlice const & startc = cur.selBegin();
1432         CursorSlice const & endc = cur.selEnd();
1433         if (startc.par() == endc.par()) {
1434                 recordUndoSelection(cur, Undo::INSERT);
1435                 pars_[startc.par()].acceptChange(startc.pos(), endc.pos());
1436                 finishUndo();
1437                 cur.clearSelection();
1438                 redoParagraph(startc.par());
1439                 setCursorIntern(cur, startc.par(), 0);
1440         }
1441 #ifdef WITH_WARNINGS
1442 #warning handle multi par selection
1443 #endif
1444 }
1445
1446
1447 void LyXText::rejectChange(LCursor & cur)
1448 {
1449         BOOST_ASSERT(this == cur.text());
1450         if (!cur.selection() && cur.lastpos() != 0)
1451                 return;
1452
1453         CursorSlice const & startc = cur.selBegin();
1454         CursorSlice const & endc = cur.selEnd();
1455         if (startc.par() == endc.par()) {
1456                 recordUndoSelection(cur, Undo::INSERT);
1457                 pars_[startc.par()].rejectChange(startc.pos(), endc.pos());
1458                 finishUndo();
1459                 cur.clearSelection();
1460                 redoParagraph(startc.par());
1461                 setCursorIntern(cur, startc.par(), 0);
1462         }
1463 #ifdef WITH_WARNINGS
1464 #warning handle multi par selection
1465 #endif
1466 }
1467
1468
1469 // Delete from cursor up to the end of the current or next word.
1470 void LyXText::deleteWordForward(LCursor & cur)
1471 {
1472         BOOST_ASSERT(this == cur.text());
1473         if (cur.lastpos() == 0)
1474                 cursorRight(cur);
1475         else {
1476                 cur.resetAnchor();
1477                 cur.selection() = true;
1478                 cursorRightOneWord(cur);
1479                 cur.setSelection();
1480                 cutSelection(cur, true, false);
1481         }
1482 }
1483
1484
1485 // Delete from cursor to start of current or prior word.
1486 void LyXText::deleteWordBackward(LCursor & cur)
1487 {
1488         BOOST_ASSERT(this == cur.text());
1489         if (cur.lastpos() == 0)
1490                 cursorLeft(cur);
1491         else {
1492                 cur.resetAnchor();
1493                 cur.selection() = true;
1494                 cursorLeftOneWord(cur);
1495                 cur.setSelection();
1496                 cutSelection(cur, true, false);
1497         }
1498 }
1499
1500
1501 // Kill to end of line.
1502 void LyXText::deleteLineForward(LCursor & cur)
1503 {
1504         BOOST_ASSERT(this == cur.text());
1505         if (cur.lastpos() == 0) {
1506                 // Paragraph is empty, so we just go to the right
1507                 cursorRight(cur);
1508         } else {
1509                 cur.resetAnchor();
1510                 cur.selection() = true; // to avoid deletion
1511                 cursorEnd(cur);
1512                 cur.setSelection();
1513                 // What is this test for ??? (JMarc)
1514                 if (!cur.selection())
1515                         deleteWordForward(cur);
1516                 else
1517                         cutSelection(cur, true, false);
1518         }
1519 }
1520
1521
1522 void LyXText::changeCase(LCursor & cur, LyXText::TextCase action)
1523 {
1524         BOOST_ASSERT(this == cur.text());
1525         CursorSlice from;
1526         CursorSlice to;
1527
1528         if (cur.selection()) {
1529                 from = cur.selBegin();
1530                 to = cur.selEnd();
1531         } else {
1532                 from = cur.top();
1533                 getWord(from, to, lyx::PARTIAL_WORD);
1534                 setCursor(cur, to.par(), to.pos() + 1);
1535         }
1536
1537         recordUndoSelection(cur);
1538
1539         pos_type pos = from.pos();
1540         int par = from.par();
1541
1542         while (par != int(pars_.size()) && (pos != to.pos() || par != to.par())) {
1543                 par_type pit = par;
1544                 if (pos == pars_[pit].size()) {
1545                         ++par;
1546                         pos = 0;
1547                         continue;
1548                 }
1549                 unsigned char c = pars_[pit].getChar(pos);
1550                 if (c != Paragraph::META_INSET) {
1551                         switch (action) {
1552                         case text_lowercase:
1553                                 c = lowercase(c);
1554                                 break;
1555                         case text_capitalization:
1556                                 c = uppercase(c);
1557                                 action = text_lowercase;
1558                                 break;
1559                         case text_uppercase:
1560                                 c = uppercase(c);
1561                                 break;
1562                         }
1563                 }
1564 #ifdef WITH_WARNINGS
1565 #warning changes
1566 #endif
1567                 pars_[pit].setChar(pos, c);
1568                 ++pos;
1569         }
1570 }
1571
1572
1573 void LyXText::Delete(LCursor & cur)
1574 {
1575         BOOST_ASSERT(this == cur.text());
1576         if (cur.pos() != cur.lastpos()) {
1577                 recordUndo(cur, Undo::DELETE, cur.par());
1578                 setCursorIntern(cur, cur.par(), cur.pos() + 1, false, cur.boundary());
1579                 backspace(cur);
1580         }
1581         // should we do anything in an else branch?
1582 }
1583
1584
1585 void LyXText::backspace(LCursor & cur)
1586 {
1587         BOOST_ASSERT(this == cur.text());
1588         if (cur.pos() == 0) {
1589                 // The cursor is at the beginning of a paragraph, so
1590                 // the the backspace will collapse two paragraphs into
1591                 // one.
1592
1593                 // but it's not allowed unless it's new
1594                 Paragraph & par = cur.paragraph();
1595                 if (par.isChangeEdited(0, par.size()))
1596                         return;
1597
1598                 // we may paste some paragraphs
1599
1600                 // is it an empty paragraph?
1601                 pos_type lastpos = cur.lastpos();
1602                 if (lastpos == 0 || (lastpos == 1 && par.isSeparator(0))) {
1603                         // This is an empty paragraph and we delete it just
1604                         // by moving the cursor one step
1605                         // left and let the DeleteEmptyParagraphMechanism
1606                         // handle the actual deletion of the paragraph.
1607
1608                         if (cur.par() != 0) {
1609                                 cursorLeft(cur);
1610                                 // the layout things can change the height of a row !
1611                                 redoParagraph(cur);
1612                                 return;
1613                         }
1614                 }
1615
1616                 if (cur.par() != 0)
1617                         recordUndo(cur, Undo::DELETE, cur.par() - 1);
1618
1619                 par_type tmppit = cur.par();
1620                 // We used to do cursorLeftIntern() here, but it is
1621                 // not a good idea since it triggers the auto-delete
1622                 // mechanism. So we do a cursorLeftIntern()-lite,
1623                 // without the dreaded mechanism. (JMarc)
1624                 if (cur.par() != 0) {
1625                         // steps into the above paragraph.
1626                         setCursorIntern(cur, cur.par() - 1,
1627                                         pars_[cur.par() - 1].size(),
1628                                         false);
1629                 }
1630
1631                 // Pasting is not allowed, if the paragraphs have different
1632                 // layout. I think it is a real bug of all other
1633                 // word processors to allow it. It confuses the user.
1634                 // Correction: Pasting is always allowed with standard-layout
1635                 Buffer & buf = cur.buffer();
1636                 BufferParams const & bufparams = buf.params();
1637                 LyXTextClass const & tclass = bufparams.getLyXTextClass();
1638                 par_type const cpit = cur.par();
1639
1640                 if (cpit != tmppit
1641                     && (pars_[cpit].layout() == pars_[tmppit].layout()
1642                         || pars_[tmppit].layout() == tclass.defaultLayout())
1643                     && pars_[cpit].getAlign() == pars_[tmppit].getAlign()) {
1644                         mergeParagraph(bufparams, buf.paragraphs(), cpit);
1645
1646                         if (cur.pos() != 0 && pars_[cpit].isSeparator(cur.pos() - 1))
1647                                 --cur.pos();
1648
1649                         // the counters may have changed
1650                         updateCounters();
1651                         setCursor(cur, cur.par(), cur.pos(), false);
1652                 }
1653         } else {
1654                 // this is the code for a normal backspace, not pasting
1655                 // any paragraphs
1656                 recordUndo(cur, Undo::DELETE);
1657                 // We used to do cursorLeftIntern() here, but it is
1658                 // not a good idea since it triggers the auto-delete
1659                 // mechanism. So we do a cursorLeftIntern()-lite,
1660                 // without the dreaded mechanism. (JMarc)
1661                 setCursorIntern(cur, cur.par(), cur.pos() - 1,
1662                                 false, cur.boundary());
1663                 cur.paragraph().erase(cur.pos());
1664         }
1665
1666         if (cur.pos() == cur.lastpos())
1667                 setCurrentFont(cur);
1668
1669         redoParagraph(cur);
1670         setCursor(cur, cur.par(), cur.pos(), false, cur.boundary());
1671 }
1672
1673
1674 Paragraph & LyXText::getPar(par_type par) const
1675 {
1676         //lyxerr << "getPar: " << par << " from " << paragraphs().size() << endl;
1677         BOOST_ASSERT(par >= 0);
1678         BOOST_ASSERT(par < int(paragraphs().size()));
1679         return paragraphs()[par];
1680 }
1681
1682
1683 Row const & LyXText::firstRow() const
1684 {
1685         return *paragraphs().front().rows.begin();
1686 }
1687
1688
1689 void LyXText::redoParagraphInternal(par_type const pit)
1690 {
1691         // remove rows of paragraph, keep track of height changes
1692         Paragraph & par = pars_[pit];
1693         height_ -= par.height;
1694
1695         // clear old data
1696         par.rows.clear();
1697         par.height = 0;
1698         par.width = 0;
1699
1700         // redo insets
1701         InsetList::iterator ii = par.insetlist.begin();
1702         InsetList::iterator iend = par.insetlist.end();
1703         for (; ii != iend; ++ii) {
1704                 Dimension dim;
1705                 int const w = maxwidth_ - leftMargin(pit) - rightMargin(par);
1706                 MetricsInfo mi(bv(), getFont(par, ii->pos), w);
1707                 ii->inset->metrics(mi, dim);
1708         }
1709
1710         // rebreak the paragraph
1711         par.setBeginOfBody();
1712         pos_type z = 0;
1713         do {
1714                 Row row(z);
1715                 rowBreakPoint(pit, row);
1716                 setRowWidth(pit, row);
1717                 setHeightOfRow(pit, row);
1718                 row.y_offset(par.height);
1719                 par.rows.push_back(row);
1720                 par.width = std::max(par.width, row.width());
1721                 par.height += row.height();
1722                 z = row.endpos();
1723         } while (z < par.size());
1724
1725         height_ += par.height;
1726         //lyxerr << "redoParagraph: " << par.rows.size() << " rows\n";
1727 }
1728
1729
1730 void LyXText::redoParagraphs(par_type pit, par_type end)
1731 {
1732         for (; pit != end; ++pit)
1733                 redoParagraphInternal(pit);
1734         updateParPositions();
1735         updateCounters();
1736 }
1737
1738
1739 void LyXText::redoParagraph(par_type pit)
1740 {
1741         redoParagraphInternal(pit);
1742         updateParPositions();
1743 }
1744
1745
1746 void LyXText::fullRebreak()
1747 {
1748         redoParagraphs(0, paragraphs().size());
1749         bv()->cursor().resetAnchor();
1750 }
1751
1752
1753 void LyXText::metrics(MetricsInfo & mi, Dimension & dim)
1754 {
1755         //BOOST_ASSERT(mi.base.textwidth);
1756         if (mi.base.textwidth)
1757                 maxwidth_ = mi.base.textwidth;
1758         //lyxerr << "LyXText::metrics: width: " << mi.base.textwidth
1759         //<< " maxWidth: " << maxwidth << "\nfont: " << mi.base.font
1760         //<< endl;
1761
1762         // Rebuild row cache. This recomputes height as well.
1763         redoParagraphs(0, paragraphs().size());
1764
1765         width_ = maxParagraphWidth(paragraphs());
1766
1767         // final dimension
1768         dim.asc = firstRow().ascent_of_text();
1769         dim.des = height_ - dim.asc;
1770         dim.wid = width_;
1771 }
1772
1773
1774 // only used for inset right now. should also be used for main text
1775 void LyXText::draw(PainterInfo & pi, int x, int y) const
1776 {
1777         xo_ = x;
1778         yo_ = y;
1779         paintTextInset(*this, pi);
1780 }
1781
1782
1783 // only used for inset right now. should also be used for main text
1784 void LyXText::drawSelection(PainterInfo &, int, int) const
1785 {
1786         //lyxerr << "LyXText::drawSelection at " << x << " " << y << endl;
1787 }
1788
1789
1790 bool LyXText::isLastRow(par_type pit, Row const & row) const
1791 {
1792         return row.endpos() >= pars_[pit].size()
1793                 && pit + 1 == par_type(paragraphs().size());
1794 }
1795
1796
1797 bool LyXText::isFirstRow(par_type pit, Row const & row) const
1798 {
1799         return row.pos() == 0 && pit == 0;
1800 }
1801
1802
1803 void LyXText::getWord(CursorSlice & from, CursorSlice & to,
1804         word_location const loc)
1805 {
1806         Paragraph const & from_par = pars_[from.par()];
1807         switch (loc) {
1808         case lyx::WHOLE_WORD_STRICT:
1809                 if (from.pos() == 0 || from.pos() == from_par.size()
1810                     || !from_par.isWord(from.pos())
1811                     || !from_par.isWord(from.pos() - 1)) {
1812                         to = from;
1813                         return;
1814                 }
1815                 // no break here, we go to the next
1816
1817         case lyx::WHOLE_WORD:
1818                 // If we are already at the beginning of a word, do nothing
1819                 if (!from.pos() || !from_par.isWord(from.pos() - 1))
1820                         break;
1821                 // no break here, we go to the next
1822
1823         case lyx::PREVIOUS_WORD:
1824                 // always move the cursor to the beginning of previous word
1825                 while (from.pos() && from_par.isWord(from.pos() - 1))
1826                         --from.pos();
1827                 break;
1828         case lyx::NEXT_WORD:
1829                 lyxerr << "LyXText::getWord: NEXT_WORD not implemented yet"
1830                        << endl;
1831                 break;
1832         case lyx::PARTIAL_WORD:
1833                 // no need to move the 'from' cursor
1834                 break;
1835         }
1836         to = from;
1837         Paragraph & to_par = pars_[to.par()];
1838         while (to.pos() < to_par.size() && to_par.isWord(to.pos()))
1839                 ++to.pos();
1840 }
1841
1842
1843 void LyXText::write(Buffer const & buf, std::ostream & os) const
1844 {
1845         ParagraphList::const_iterator pit = paragraphs().begin();
1846         ParagraphList::const_iterator end = paragraphs().end();
1847         Paragraph::depth_type dth = 0;
1848         for (; pit != end; ++pit)
1849                 pit->write(buf, os, buf.params(), dth);
1850 }
1851
1852
1853 bool LyXText::read(Buffer const & buf, LyXLex & lex)
1854 {
1855         static Change current_change;
1856
1857         Paragraph::depth_type depth = 0;
1858
1859         while (lex.isOK()) {
1860                 lex.nextToken();
1861                 string const token = lex.getString();
1862
1863                 if (token.empty())
1864                         continue;
1865
1866                 if (token == "\\end_inset") {
1867                         break;
1868                 }
1869
1870                 if (token == "\\end_document") {
1871                         return false;
1872                 }
1873
1874                 // FIXME: ugly.
1875                 int unknown = 0;
1876
1877                 if (token == "\\begin_layout") {
1878                         lex.pushToken(token);
1879
1880                         Paragraph par;
1881                         par.params().depth(depth);
1882                         if (buf.params().tracking_changes)
1883                                 par.trackChanges();
1884                         par.setFont(0, LyXFont(LyXFont::ALL_INHERIT, buf.params().language));
1885                         pars_.push_back(par);
1886
1887                         // FIXME: goddamn InsetTabular makes us pass a Buffer
1888                         // not BufferParams
1889                         ::readParagraph(buf, pars_.back(), lex);
1890
1891                 } else if (token == "\\begin_deeper") {
1892                         ++depth;
1893                 } else if (token == "\\end_deeper") {
1894                         if (!depth) {
1895                                 lex.printError("\\end_deeper: " "depth is already null");
1896                         } else {
1897                                 --depth;
1898                         }
1899                 } else {
1900                         ++unknown;
1901                 }
1902
1903         }
1904         return true;
1905 }
1906
1907
1908 int LyXText::ascent() const
1909 {
1910         return firstRow().ascent_of_text();
1911 }
1912
1913
1914 int LyXText::descent() const
1915 {
1916         return height_ - firstRow().ascent_of_text();
1917 }
1918
1919
1920 int LyXText::cursorX(CursorSlice const & cur) const
1921 {
1922         par_type const pit = cur.par();
1923         Paragraph const & par = pars_[pit];
1924         if (par.rows.empty())
1925                 return xo_;
1926
1927         Row const & row = *par.getRow(cur.pos());
1928
1929         pos_type pos = cur.pos();
1930         pos_type cursor_vpos = 0;
1931
1932         RowMetrics const m = computeRowMetrics(pit, row);
1933         double x = m.x;
1934
1935         pos_type const row_pos  = row.pos();
1936         pos_type const end      = row.endpos();
1937
1938         if (end <= row_pos)
1939                 cursor_vpos = row_pos;
1940         else if (pos >= end)
1941                 cursor_vpos = isRTL(par) ? row_pos : end;
1942         else if (pos > row_pos && pos >= end)
1943                 // Place cursor after char at (logical) position pos - 1
1944                 cursor_vpos = (bidi.level(pos - 1) % 2 == 0)
1945                         ? bidi.log2vis(pos - 1) + 1 : bidi.log2vis(pos - 1);
1946         else
1947                 // Place cursor before char at (logical) position pos
1948                 cursor_vpos = (bidi.level(pos) % 2 == 0)
1949                         ? bidi.log2vis(pos) : bidi.log2vis(pos) + 1;
1950
1951         pos_type body_pos = par.beginOfBody();
1952         if (body_pos > 0 &&
1953             (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1954                 body_pos = 0;
1955
1956         for (pos_type vpos = row_pos; vpos < cursor_vpos; ++vpos) {
1957                 pos_type pos = bidi.vis2log(vpos);
1958                 if (body_pos > 0 && pos == body_pos - 1) {
1959                         x += m.label_hfill
1960                                 + font_metrics::width(par.layout()->labelsep,
1961                                                       getLabelFont(par));
1962                         if (par.isLineSeparator(body_pos - 1))
1963                                 x -= singleWidth(par, body_pos - 1);
1964                 }
1965
1966                 if (hfillExpansion(par, row, pos)) {
1967                         x += singleWidth(par, pos);
1968                         if (pos >= body_pos)
1969                                 x += m.hfill;
1970                         else
1971                                 x += m.label_hfill;
1972                 } else if (par.isSeparator(pos)) {
1973                         x += singleWidth(par, pos);
1974                         if (pos >= body_pos)
1975                                 x += m.separator;
1976                 } else
1977                         x += singleWidth(par, pos);
1978         }
1979         return xo_ + int(x);
1980 }
1981
1982
1983 int LyXText::cursorY(CursorSlice const & cur) const
1984 {
1985         Paragraph const & par = getPar(cur.par());
1986         Row const & row = *par.getRow(cur.pos());
1987         return yo_ + par.y + row.y_offset() + row.baseline();
1988 }
1989
1990
1991 // Returns the current font and depth as a message.
1992 string LyXText::currentState(LCursor & cur)
1993 {
1994         BOOST_ASSERT(this == cur.text());
1995         Buffer & buf = cur.buffer();
1996         Paragraph const & par = cur.paragraph();
1997         std::ostringstream os;
1998
1999         bool const show_change = buf.params().tracking_changes
2000                 && cur.pos() != cur.lastpos()
2001                 && par.lookupChange(cur.pos()) != Change::UNCHANGED;
2002
2003         if (show_change) {
2004                 Change change = par.lookupChangeFull(cur.pos());
2005                 Author const & a = buf.params().authors().get(change.author);
2006                 os << _("Change: ") << a.name();
2007                 if (!a.email().empty())
2008                         os << " (" << a.email() << ")";
2009                 if (change.changetime)
2010                         os << _(" at ") << ctime(&change.changetime);
2011                 os << " : ";
2012         }
2013
2014         // I think we should only show changes from the default
2015         // font. (Asger)
2016         LyXFont font = real_current_font;
2017         font.reduce(buf.params().getLyXTextClass().defaultfont());
2018
2019         // avoid _(...) re-entrance problem
2020         string const s = font.stateText(&buf.params());
2021         os << bformat(_("Font: %1$s"), s);
2022
2023         // os << bformat(_("Font: %1$s"), font.stateText(&buf.params));
2024
2025         // The paragraph depth
2026         int depth = cur.paragraph().getDepth();
2027         if (depth > 0)
2028                 os << bformat(_(", Depth: %1$s"), tostr(depth));
2029
2030         // The paragraph spacing, but only if different from
2031         // buffer spacing.
2032         Spacing const & spacing = par.params().spacing();
2033         if (!spacing.isDefault()) {
2034                 os << _(", Spacing: ");
2035                 switch (spacing.getSpace()) {
2036                 case Spacing::Single:
2037                         os << _("Single");
2038                         break;
2039                 case Spacing::Onehalf:
2040                         os << _("OneHalf");
2041                         break;
2042                 case Spacing::Double:
2043                         os << _("Double");
2044                         break;
2045                 case Spacing::Other:
2046                         os << _("Other (") << spacing.getValue() << ')';
2047                         break;
2048                 case Spacing::Default:
2049                         // should never happen, do nothing
2050                         break;
2051                 }
2052         }
2053
2054 #ifdef DEVEL_VERSION
2055         os << _(", Inset: ") << &cur.inset();
2056         os << _(", Paragraph: ") << cur.par();
2057         os << _(", Id: ") << par.id();
2058         os << _(", Position: ") << cur.pos();
2059         Row & row = cur.textRow();
2060         os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
2061 #endif
2062         return os.str();
2063 }
2064
2065
2066 string LyXText::getPossibleLabel(LCursor & cur) const
2067 {
2068         par_type pit = cur.par();
2069
2070         LyXLayout_ptr layout = pars_[pit].layout();
2071
2072         if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
2073                 LyXLayout_ptr const & layout2 = pars_[pit - 1].layout();
2074                 if (layout2->latextype != LATEX_PARAGRAPH) {
2075                         --pit;
2076                         layout = layout2;
2077                 }
2078         }
2079
2080         string text = layout->latexname().substr(0, 3);
2081         if (layout->latexname() == "theorem")
2082                 text = "thm"; // Create a correct prefix for prettyref
2083
2084         text += ':';
2085         if (layout->latextype == LATEX_PARAGRAPH || lyxrc.label_init_length < 0)
2086                 text.erase();
2087
2088         string par_text = pars_[pit].asString(cur.buffer(), false);
2089         for (int i = 0; i < lyxrc.label_init_length; ++i) {
2090                 if (par_text.empty())
2091                         break;
2092                 string head;
2093                 par_text = split(par_text, head, ' ');
2094                 // Is it legal to use spaces in labels ?
2095                 if (i > 0)
2096                         text += '-';
2097                 text += head;
2098         }
2099
2100         return text;
2101 }
2102
2103
2104 // Manhattan distance to nearest corner
2105 int LyXText::dist(int x, int y) const
2106 {
2107         int xx = 0;
2108         int yy = 0;
2109
2110         if (x < xo_)
2111                 xx = xo_ - x;
2112         else if (x > xo_ + int(width_))
2113                 xx = x - xo_ - width_;
2114
2115         if (y < yo_ - ascent())
2116                 yy = yo_ - ascent() - y;
2117         else if (y > yo_ + descent())
2118                 yy = y - yo_ - descent();
2119
2120         lyxerr << " xo_=" << xo_ << "  yo_=" << yo_ 
2121                << " width_=" << width_ << " ascent=" << ascent()
2122                << " descent=" << descent() 
2123                << " dist=" << xx+yy <<endl;
2124         return xx + yy;
2125 }