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