]> git.lyx.org Git - lyx.git/blob - src/text.C
make it compile again (hopefully)
[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 "buffer_funcs.h"
24 #include "bufferparams.h"
25 #include "BufferView.h"
26 #include "cursor.h"
27 #include "pariterator.h"
28 #include "coordcache.h"
29 #include "CutAndPaste.h"
30 #include "debug.h"
31 #include "dispatchresult.h"
32 #include "encoding.h"
33 #include "errorlist.h"
34 #include "funcrequest.h"
35 #include "factory.h"
36 #include "FontIterator.h"
37 #include "gettext.h"
38 #include "language.h"
39 #include "LColor.h"
40 #include "lyxlength.h"
41 #include "lyxlex.h"
42 #include "lyxrc.h"
43 #include "lyxrow.h"
44 #include "lyxrow_funcs.h"
45 #include "metricsinfo.h"
46 #include "paragraph.h"
47 #include "paragraph_funcs.h"
48 #include "ParagraphParameters.h"
49 #include "rowpainter.h"
50 #include "undo.h"
51 #include "vspace.h"
52 #include "WordLangTuple.h"
53
54 #include "frontends/FontMetrics.h"
55 #include "frontends/Painter.h"
56
57 #include "insets/insettext.h"
58 #include "insets/insetbibitem.h"
59 #include "insets/insethfill.h"
60 #include "insets/insetlatexaccent.h"
61 #include "insets/insetline.h"
62 #include "insets/insetnewline.h"
63 #include "insets/insetpagebreak.h"
64 #include "insets/insetoptarg.h"
65 #include "insets/insetspace.h"
66 #include "insets/insetspecialchar.h"
67 #include "insets/insettabular.h"
68
69 #include "support/lstrings.h"
70 #include "support/textutils.h"
71 #include "support/convert.h"
72
73 #include <boost/current_function.hpp>
74
75 #include <sstream>
76
77 using lyx::docstring;
78 using lyx::char_type;
79 using lyx::pit_type;
80 using lyx::pos_type;
81 using lyx::word_location;
82
83 using lyx::support::bformat;
84 using lyx::support::contains;
85 using lyx::support::lowercase;
86 using lyx::support::split;
87 using lyx::support::uppercase;
88
89 using lyx::cap::cutSelection;
90 using lyx::cap::pasteParagraphList;
91
92 using lyx::frontend::FontMetrics;
93
94 using std::auto_ptr;
95 using std::advance;
96 using std::distance;
97 using std::max;
98 using std::min;
99 using std::endl;
100 using std::string;
101
102
103 namespace {
104
105 int numberOfSeparators(Paragraph const & par, Row const & row)
106 {
107         pos_type const first = max(row.pos(), par.beginOfBody());
108         pos_type const last = row.endpos() - 1;
109         int n = 0;
110         for (pos_type p = first; p < last; ++p) {
111                 if (par.isSeparator(p))
112                         ++n;
113         }
114         return n;
115 }
116
117
118 int numberOfLabelHfills(Paragraph const & par, Row const & row)
119 {
120         pos_type last = row.endpos() - 1;
121         pos_type first = row.pos();
122
123         // hfill *DO* count at the beginning of paragraphs!
124         if (first) {
125                 while (first < last && par.isHfill(first))
126                         ++first;
127         }
128
129         last = min(last, par.beginOfBody());
130         int n = 0;
131         for (pos_type p = first; p < last; ++p) {
132                 if (par.isHfill(p))
133                         ++n;
134         }
135         return n;
136 }
137
138
139 int numberOfHfills(Paragraph const & par, Row const & row)
140 {
141         pos_type const last = row.endpos();
142         pos_type first = row.pos();
143
144         // hfill *DO* count at the beginning of paragraphs!
145         if (first) {
146                 while (first < last && par.isHfill(first))
147                         ++first;
148         }
149
150         first = max(first, par.beginOfBody());
151
152         int n = 0;
153         for (pos_type p = first; p < last; ++p) {
154                 if (par.isHfill(p))
155                         ++n;
156         }
157         return n;
158 }
159
160
161 void readParToken(Buffer const & buf, Paragraph & par, LyXLex & lex,
162         string const & token, LyXFont & font, Change & change, ErrorList & errorList)
163 {
164         BufferParams const & bp = buf.params();
165
166         if (token[0] != '\\') {
167 #if 0
168                 string::const_iterator cit = token.begin();
169                 for (; cit != token.end(); ++cit)
170                         par.insertChar(par.size(), (*cit), font, change);
171 #else
172                 lyx::docstring dstr = lex.getDocString();
173                 lyx::docstring::const_iterator cit = dstr.begin();
174                 lyx::docstring::const_iterator cend = dstr.end();
175                 for (; cit != cend; ++cit)
176                         par.insertChar(par.size(), *cit, font, change);
177 #endif
178         } else if (token == "\\begin_layout") {
179                 lex.eatLine();
180                 string layoutname = lex.getString();
181
182                 font = LyXFont(LyXFont::ALL_INHERIT, bp.language);
183                 change = Change(Change::UNCHANGED);
184
185                 LyXTextClass const & tclass = bp.getLyXTextClass();
186
187                 if (layoutname.empty()) {
188                         layoutname = tclass.defaultLayoutName();
189                 }
190
191                 bool hasLayout = tclass.hasLayout(layoutname);
192
193                 if (!hasLayout) {
194                         errorList.push_back(ErrorItem(_("Unknown layout"),
195                         bformat(_("Layout '%1$s' does not exist in textclass '%2$s'\nTrying to use the default instead.\n"),
196                         lyx::from_utf8(layoutname), lyx::from_utf8(tclass.name())), par.id(), 0, par.size()));
197                         layoutname = tclass.defaultLayoutName();
198                 }
199
200                 par.layout(bp.getLyXTextClass()[layoutname]);
201
202                 // Test whether the layout is obsolete.
203                 LyXLayout_ptr const & layout = par.layout();
204                 if (!layout->obsoleted_by().empty())
205                         par.layout(bp.getLyXTextClass()[layout->obsoleted_by()]);
206
207                 par.params().read(lex);
208
209         } else if (token == "\\end_layout") {
210                 lyxerr << BOOST_CURRENT_FUNCTION
211                        << ": Solitary \\end_layout in line "
212                        << lex.getLineNo() << "\n"
213                        << "Missing \\begin_layout?.\n";
214         } else if (token == "\\end_inset") {
215                 lyxerr << BOOST_CURRENT_FUNCTION
216                        << ": Solitary \\end_inset in line "
217                        << lex.getLineNo() << "\n"
218                        << "Missing \\begin_inset?.\n";
219         } else if (token == "\\begin_inset") {
220                 InsetBase * inset = readInset(lex, buf);
221                 if (inset)
222                         par.insertInset(par.size(), inset, font, change);
223                 else {
224                         lex.eatLine();
225                         docstring line = lyx::from_utf8(lex.getString());
226                         errorList.push_back(ErrorItem(_("Unknown Inset"), line,
227                                             par.id(), 0, par.size()));
228                 }
229         } else if (token == "\\family") {
230                 lex.next();
231                 font.setLyXFamily(lex.getString());
232         } else if (token == "\\series") {
233                 lex.next();
234                 font.setLyXSeries(lex.getString());
235         } else if (token == "\\shape") {
236                 lex.next();
237                 font.setLyXShape(lex.getString());
238         } else if (token == "\\size") {
239                 lex.next();
240                 font.setLyXSize(lex.getString());
241         } else if (token == "\\lang") {
242                 lex.next();
243                 string const tok = lex.getString();
244                 Language const * lang = languages.getLanguage(tok);
245                 if (lang) {
246                         font.setLanguage(lang);
247                 } else {
248                         font.setLanguage(bp.language);
249                         lex.printError("Unknown language `$$Token'");
250                 }
251         } else if (token == "\\numeric") {
252                 lex.next();
253                 font.setNumber(font.setLyXMisc(lex.getString()));
254         } else if (token == "\\emph") {
255                 lex.next();
256                 font.setEmph(font.setLyXMisc(lex.getString()));
257         } else if (token == "\\bar") {
258                 lex.next();
259                 string const tok = lex.getString();
260
261                 if (tok == "under")
262                         font.setUnderbar(LyXFont::ON);
263                 else if (tok == "no")
264                         font.setUnderbar(LyXFont::OFF);
265                 else if (tok == "default")
266                         font.setUnderbar(LyXFont::INHERIT);
267                 else
268                         lex.printError("Unknown bar font flag "
269                                        "`$$Token'");
270         } else if (token == "\\noun") {
271                 lex.next();
272                 font.setNoun(font.setLyXMisc(lex.getString()));
273         } else if (token == "\\color") {
274                 lex.next();
275                 font.setLyXColor(lex.getString());
276         } else if (token == "\\InsetSpace" || token == "\\SpecialChar") {
277
278                 // Insets don't make sense in a free-spacing context! ---Kayvan
279                 if (par.isFreeSpacing()) {
280                         if (token == "\\InsetSpace")
281                                 par.insertChar(par.size(), ' ', font, change);
282                         else if (lex.isOK()) {
283                                 lex.next();
284                                 string const next_token = lex.getString();
285                                 if (next_token == "\\-")
286                                         par.insertChar(par.size(), '-', font, change);
287                                 else {
288                                         lex.printError("Token `$$Token' "
289                                                        "is in free space "
290                                                        "paragraph layout!");
291                                 }
292                         }
293                 } else {
294                         auto_ptr<InsetBase> inset;
295                         if (token == "\\SpecialChar" )
296                                 inset.reset(new InsetSpecialChar);
297                         else
298                                 inset.reset(new InsetSpace);
299                         inset->read(buf, lex);
300                         par.insertInset(par.size(), inset.release(),
301                                         font, change);
302                 }
303         } else if (token == "\\i") {
304                 auto_ptr<InsetBase> inset(new InsetLatexAccent);
305                 inset->read(buf, lex);
306                 par.insertInset(par.size(), inset.release(), font, change);
307         } else if (token == "\\backslash") {
308                 par.insertChar(par.size(), '\\', font, change);
309         } else if (token == "\\newline") {
310                 auto_ptr<InsetBase> inset(new InsetNewline);
311                 inset->read(buf, lex);
312                 par.insertInset(par.size(), inset.release(), font, change);
313         } else if (token == "\\LyXTable") {
314                 auto_ptr<InsetBase> inset(new InsetTabular(buf));
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: change tracking (MG)
326                 // set empty 'par' to INSERTED???
327                 change = Change(Change::UNCHANGED);
328         } else if (token == "\\change_inserted") {
329                 lex.eatLine();
330                 std::istringstream is(lex.getString());
331                 unsigned int aid;
332                 lyx::time_type ct;
333                 is >> aid >> ct;
334                 if (aid >= bp.author_map.size()) {
335                         errorList.push_back(ErrorItem(_("Change tracking error"),
336                                             bformat(_("Unknown author index for insertion: %1$d\n"), aid),
337                                             par.id(), 0, par.size()));
338
339                         change = Change(Change::UNCHANGED);
340                 } else
341                         change = Change(Change::INSERTED, bp.author_map[aid], ct);
342         } else if (token == "\\change_deleted") {
343                 lex.eatLine();
344                 std::istringstream is(lex.getString());
345                 unsigned int aid;
346                 lyx::time_type ct;
347                 is >> aid >> ct;
348                 if (aid >= bp.author_map.size()) {
349                         errorList.push_back(ErrorItem(_("Change tracking error"),
350                                             bformat(_("Unknown author index for deletion: %1$d\n"), aid),
351                                             par.id(), 0, par.size()));
352
353                         change = Change(Change::UNCHANGED);
354                 } else
355                         change = Change(Change::DELETED, bp.author_map[aid], ct);
356         } else {
357                 lex.eatLine();
358                 errorList.push_back(ErrorItem(_("Unknown token"),
359                         bformat(_("Unknown token: %1$s %2$s\n"), lyx::from_utf8(token),
360                         lyx::from_utf8(lex.getString())),
361                         par.id(), 0, par.size()));
362         }
363 }
364
365
366 void readParagraph(Buffer const & buf, Paragraph & par, LyXLex & lex, ErrorList & errorList)
367 {
368         lex.nextToken();
369         string token = lex.getString();
370         LyXFont font;
371         Change change(Change::UNCHANGED);
372
373         while (lex.isOK()) {
374
375                 readParToken(buf, par, lex, token, font, change, errorList);
376
377                 lex.nextToken();
378                 token = lex.getString();
379
380                 if (token.empty())
381                         continue;
382
383                 if (token == "\\end_layout") {
384                         //Ok, paragraph finished
385                         break;
386                 }
387
388                 lyxerr[Debug::PARSER] << "Handling paragraph token: `"
389                                       << token << '\'' << endl;
390                 if (token == "\\begin_layout" || token == "\\end_document"
391                     || token == "\\end_inset" || token == "\\begin_deeper"
392                     || token == "\\end_deeper") {
393                         lex.pushToken(token);
394                         lyxerr << "Paragraph ended in line "
395                                << lex.getLineNo() << "\n"
396                                << "Missing \\end_layout.\n";
397                         break;
398                 }
399         }
400         // Final change goes to paragraph break:
401         par.setChange(par.size(), change);
402
403         // Initialize begin_of_body_ on load; redoParagraph maintains
404         par.setBeginOfBody();
405 }
406
407
408 } // namespace anon
409
410
411
412 BufferView * LyXText::bv() const
413 {
414         BOOST_ASSERT(bv_owner != 0);
415         return bv_owner;
416 }
417
418
419 double LyXText::spacing(Paragraph const & par) const
420 {
421         if (par.params().spacing().isDefault())
422                 return bv()->buffer()->params().spacing().getValue();
423         return par.params().spacing().getValue();
424 }
425
426
427 int LyXText::width() const
428 {
429         return dim_.wid;
430 }
431
432
433 int LyXText::height() const
434 {
435         return dim_.height();
436 }
437
438
439 int LyXText::singleWidth(Paragraph const & par, pos_type pos) const
440 {
441         return singleWidth(par, pos, par.getChar(pos), getFont(par, pos));
442 }
443
444
445 int LyXText::singleWidth(Paragraph const & par,
446                          pos_type pos, char_type c, LyXFont const & font) const
447 {
448         // The most common case is handled first (Asger)
449         if (isPrintable(c)) {
450                 Language const * language = font.language();
451                 if (language->rightToLeft()) {
452                         if ((lyxrc.font_norm_type == LyXRC::ISO_8859_6_8 ||
453                              lyxrc.font_norm_type == LyXRC::ISO_10646_1)
454                             && language->lang() == "arabic") {
455                                 if (Encodings::isComposeChar_arabic(c))
456                                         return 0;
457                                 c = par.transformChar(c, pos);
458                         } else if (language->lang() == "hebrew" &&
459                                    Encodings::isComposeChar_hebrew(c))
460                                 return 0;
461                 }
462                 return theFontMetrics(font).width(c);
463         }
464
465         if (c == Paragraph::META_INSET)
466                 return par.getInset(pos)->width();
467
468         return theFontMetrics(font).width(c);
469 }
470
471
472 int LyXText::leftMargin(pit_type pit) const
473 {
474         BOOST_ASSERT(pit >= 0);
475         BOOST_ASSERT(pit < int(pars_.size()));
476         return leftMargin(pit, pars_[pit].size());
477 }
478
479
480 int LyXText::leftMargin(pit_type const pit, pos_type const pos) const
481 {
482         BOOST_ASSERT(pit >= 0);
483         BOOST_ASSERT(pit < int(pars_.size()));
484         Paragraph const & par = pars_[pit];
485         BOOST_ASSERT(pos >= 0);
486         BOOST_ASSERT(pos <= par.size());
487         //lyxerr << "LyXText::leftMargin: pit: " << pit << " pos: " << pos << endl;
488         BufferParams const & params = bv()->buffer()->params();
489         LyXTextClass const & tclass = params.getLyXTextClass();
490         LyXLayout_ptr const & layout = par.layout();
491
492         string parindent = layout->parindent;
493
494         int l_margin = 0;
495
496         if (isMainText())
497                 l_margin += changebarMargin();
498
499         // FIXME UNICODE
500         docstring leftm = lyx::from_utf8(tclass.leftmargin());
501         l_margin += theFontMetrics(params.getFont()).signedWidth(leftm);
502
503         if (par.getDepth() != 0) {
504                 // find the next level paragraph
505                 pit_type newpar = outerHook(pit, pars_);
506                 if (newpar != pit_type(pars_.size())) {
507                         if (pars_[newpar].layout()->isEnvironment()) {
508                                 l_margin = leftMargin(newpar);
509                         }
510                         if (par.layout() == tclass.defaultLayout()) {
511                                 if (pars_[newpar].params().noindent())
512                                         parindent.erase();
513                                 else
514                                         parindent = pars_[newpar].layout()->parindent;
515                         }
516                 }
517         }
518
519         // This happens after sections in standard classes. The 1.3.x
520         // code compared depths too, but it does not seem necessary
521         // (JMarc)
522         if (par.layout() == tclass.defaultLayout()
523             && pit > 0 && pars_[pit - 1].layout()->nextnoindent)
524                 parindent.erase();
525
526         LyXFont const labelfont = getLabelFont(par);
527         FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
528
529         switch (layout->margintype) {
530         case MARGIN_DYNAMIC:
531                 if (!layout->leftmargin.empty()) {
532                         // FIXME UNICODE
533                         docstring leftm = lyx::from_utf8(layout->leftmargin);
534                         l_margin += theFontMetrics(params.getFont()).signedWidth(leftm);
535                 }
536                 if (!par.getLabelstring().empty()) {
537                         // FIXME UNICODE
538                         docstring labin = lyx::from_utf8(layout->labelindent);
539                         l_margin += labelfont_metrics.signedWidth(labin);
540                         docstring labstr = lyx::from_utf8(par.getLabelstring());
541                         l_margin += labelfont_metrics.width(labstr);
542                         docstring labsep = lyx::from_utf8(layout->labelsep);
543                         l_margin += labelfont_metrics.width(labsep);
544                 }
545                 break;
546
547         case MARGIN_MANUAL: {
548                 // FIXME UNICODE
549                 docstring labin = lyx::from_utf8(layout->labelindent);
550                 l_margin += labelfont_metrics.signedWidth(labin);
551                 // The width of an empty par, even with manual label, should be 0
552                 if (!par.empty() && pos >= par.beginOfBody()) {
553                         if (!par.getLabelWidthString().empty()) {
554                                 docstring labstr = lyx::from_utf8(par.getLabelWidthString());
555                                 l_margin += labelfont_metrics.width(labstr);
556                                 docstring labsep = lyx::from_utf8(layout->labelsep);
557                                 l_margin += labelfont_metrics.width(labsep);
558                         }
559                 }
560                 break;
561         }
562
563         case MARGIN_STATIC: {
564                 // FIXME UNICODE
565                 docstring leftm = lyx::from_utf8(layout->leftmargin);
566                 l_margin += theFontMetrics(params.getFont()).signedWidth(leftm)
567                         * 4     / (par.getDepth() + 4);
568                 break;
569         }
570
571         case MARGIN_FIRST_DYNAMIC:
572                 if (layout->labeltype == LABEL_MANUAL) {
573                         if (pos >= par.beginOfBody()) {
574                                 // FIXME UNICODE
575                                 l_margin += labelfont_metrics.signedWidth(
576                                         lyx::from_utf8(layout->leftmargin));
577                         } else {
578                                 // FIXME UNICODE
579                                 l_margin += labelfont_metrics.signedWidth(
580                                         lyx::from_utf8(layout->labelindent));
581                         }
582                 } else if (pos != 0
583                            // Special case to fix problems with
584                            // theorems (JMarc)
585                            || (layout->labeltype == LABEL_STATIC
586                                && layout->latextype == LATEX_ENVIRONMENT
587                                && !isFirstInSequence(pit, pars_))) {
588                         // FIXME UNICODE
589                         l_margin += labelfont_metrics.signedWidth(lyx::from_utf8(layout->leftmargin));
590                 } else if (layout->labeltype != LABEL_TOP_ENVIRONMENT
591                            && layout->labeltype != LABEL_BIBLIO
592                            && layout->labeltype !=
593                            LABEL_CENTERED_TOP_ENVIRONMENT) {
594                         l_margin += labelfont_metrics.signedWidth(lyx::from_utf8(layout->labelindent));
595                         l_margin += labelfont_metrics.width(lyx::from_utf8(layout->labelsep));
596                         l_margin += labelfont_metrics.width(lyx::from_utf8(par.getLabelstring()));
597                 }
598                 break;
599
600         case MARGIN_RIGHT_ADDRESS_BOX: {
601 #if 0
602                 // ok, a terrible hack. The left margin depends on the widest
603                 // row in this paragraph.
604                 RowList::iterator rit = par.rows().begin();
605                 RowList::iterator end = par.rows().end();
606 #ifdef WITH_WARNINGS
607 #warning This is wrong.
608 #endif
609                 int minfill = maxwidth_;
610                 for ( ; rit != end; ++rit)
611                         if (rit->fill() < minfill)
612                                 minfill = rit->fill();
613                 l_margin += theFontMetrics(params.getFont()).signedWidth(layout->leftmargin);
614                 l_margin += minfill;
615 #endif
616                 // also wrong, but much shorter.
617                 l_margin += maxwidth_ / 2;
618                 break;
619         }
620         }
621
622         if (!par.params().leftIndent().zero())
623                 l_margin += par.params().leftIndent().inPixels(maxwidth_);
624
625         LyXAlignment align;
626
627         if (par.params().align() == LYX_ALIGN_LAYOUT)
628                 align = layout->align;
629         else
630                 align = par.params().align();
631
632         // set the correct parindent
633         if (pos == 0
634             && (layout->labeltype == LABEL_NO_LABEL
635                || layout->labeltype == LABEL_TOP_ENVIRONMENT
636                || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT
637                || (layout->labeltype == LABEL_STATIC
638                    && layout->latextype == LATEX_ENVIRONMENT
639                    && !isFirstInSequence(pit, pars_)))
640             && align == LYX_ALIGN_BLOCK
641             && !par.params().noindent()
642             // in some insets, paragraphs are never indented
643             && !(par.inInset() && par.inInset()->neverIndent())
644             // display style insets are always centered, omit indentation
645             && !(!par.empty()
646                     && par.isInset(pos)
647                     && par.getInset(pos)->display())
648             && (par.layout() != tclass.defaultLayout()
649                 || bv()->buffer()->params().paragraph_separation ==
650                    BufferParams::PARSEP_INDENT))
651         {
652                 docstring din = lyx::from_utf8(parindent);
653                 l_margin += theFontMetrics(params.getFont()).signedWidth(din);
654         }
655
656         return l_margin;
657 }
658
659
660 int LyXText::rightMargin(Paragraph const & par) const
661 {
662         // FIXME: the correct way is to only call rightMargin() only
663         // within the main LyXText. The following test is thus bogus.
664         LyXText const & text = bv()->buffer()->text();
665         // We do not want rightmargins on inner texts.
666         if (&text != this)
667                 return 0;
668
669         BufferParams const & params = bv()->buffer()->params();
670         LyXTextClass const & tclass = params.getLyXTextClass();
671         docstring trmarg = lyx::from_utf8(tclass.rightmargin());
672         docstring lrmarg = lyx::from_utf8(par.layout()->rightmargin);
673         FontMetrics const & fm = theFontMetrics(params.getFont());
674         int const r_margin =
675                 ::rightMargin()
676                 + fm.signedWidth(trmarg)
677                 + fm.signedWidth(lrmarg)
678                 * 4 / (par.getDepth() + 4);
679
680         return r_margin;
681 }
682
683
684 int LyXText::labelEnd(pit_type const pit) const
685 {
686         // labelEnd is only needed if the layout fills a flushleft label.
687         if (pars_[pit].layout()->margintype != MARGIN_MANUAL)
688                 return 0;
689         // return the beginning of the body
690         return leftMargin(pit);
691 }
692
693
694 namespace {
695
696 // this needs special handling - only newlines count as a break point
697 pos_type addressBreakPoint(pos_type i, Paragraph const & par)
698 {
699         pos_type const end = par.size();
700
701         for (; i < end; ++i)
702                 if (par.isNewline(i))
703                         return i + 1;
704
705         return end;
706 }
707
708 };
709
710
711 void LyXText::rowBreakPoint(pit_type const pit, Row & row) const
712 {
713         Paragraph const & par = pars_[pit];
714         pos_type const end = par.size();
715         pos_type const pos = row.pos();
716         if (pos == end) {
717                 row.endpos(end);
718                 return;
719         }
720
721         // maximum pixel width of a row
722         int width = maxwidth_ - rightMargin(par); // - leftMargin(pit, row);
723         if (width < 0) {
724                 row.endpos(end);
725                 return;
726         }
727
728         LyXLayout_ptr const & layout = par.layout();
729
730         if (layout->margintype == MARGIN_RIGHT_ADDRESS_BOX) {
731                 row.endpos(addressBreakPoint(pos, par));
732                 return;
733         }
734
735         pos_type const body_pos = par.beginOfBody();
736
737
738         // Now we iterate through until we reach the right margin
739         // or the end of the par, then choose the possible break
740         // nearest that.
741
742         int const left = leftMargin(pit, pos);
743         int x = left;
744
745         // pixel width since last breakpoint
746         int chunkwidth = 0;
747
748         FontIterator fi = FontIterator(*this, par, pos);
749         pos_type point = end;
750         pos_type i = pos;
751         FontMetrics const & fm = theFontMetrics(getLabelFont(par));
752         for ( ; i < end; ++i, ++fi) {
753                 char_type const c = par.getChar(i);
754                 int thiswidth = singleWidth(par, i, c, *fi);
755
756                 // add the auto-hfill from label end to the body
757                 if (body_pos && i == body_pos) {
758                         docstring lsep = lyx::from_utf8(layout->labelsep);
759                         int add = fm.width(lsep);
760                         if (par.isLineSeparator(i - 1))
761                                 add -= singleWidth(par, i - 1);
762
763                         add = std::max(add, labelEnd(pit) - x);
764                         thiswidth += add;
765                 }
766
767                 x += thiswidth;
768                 chunkwidth += thiswidth;
769
770                 // break before a character that will fall off
771                 // the right of the row
772                 if (x >= width) {
773                         // if no break before, break here
774                         if (point == end || chunkwidth >= width - left) {
775                                 if (i > pos)
776                                         point = i;
777                                 else
778                                         point = i + 1;
779
780                         }
781                         // exit on last registered breakpoint:
782                         break;
783                 }
784
785                 if (par.isNewline(i)) {
786                         point = i + 1;
787                         break;
788                 }
789                 // Break before...
790                 if (i + 1 < end) {
791                         if (par.isInset(i + 1) && par.getInset(i + 1)->display()) {
792                                 point = i + 1;
793                                 break;
794                         }
795                         // ...and after.
796                         if (par.isInset(i) && par.getInset(i)->display()) {
797                                 point = i + 1;
798                                 break;
799                         }
800                 }
801
802                 if (!par.isInset(i) || par.getInset(i)->isChar()) {
803                         // some insets are line separators too
804                         if (par.isLineSeparator(i)) {
805                                 // register breakpoint:
806                                 point = i + 1;
807                                 chunkwidth = 0;
808                         }
809                 }
810         }
811
812         // maybe found one, but the par is short enough.
813         if (i == end && x < width)
814                 point = end;
815
816         // manual labels cannot be broken in LaTeX. But we
817         // want to make our on-screen rendering of footnotes
818         // etc. still break
819         if (body_pos && point < body_pos)
820                 point = body_pos;
821
822         row.endpos(point);
823 }
824
825
826 void LyXText::setRowWidth(pit_type const pit, Row & row) const
827 {
828         // get the pure distance
829         pos_type const end = row.endpos();
830
831         Paragraph const & par = pars_[pit];
832         docstring const labelsep = lyx::from_utf8(par.layout()->labelsep);
833         int w = leftMargin(pit, row.pos());
834
835         pos_type const body_pos = par.beginOfBody();
836         pos_type i = row.pos();
837
838         FontMetrics const & fm = theFontMetrics(getLabelFont(par));
839
840         if (i < end) {
841                 FontIterator fi = FontIterator(*this, par, i);
842                 for ( ; i < end; ++i, ++fi) {
843                         if (body_pos > 0 && i == body_pos) {
844                                 w += fm.width(labelsep);
845                                 if (par.isLineSeparator(i - 1))
846                                         w -= singleWidth(par, i - 1);
847                                 w = max(w, labelEnd(pit));
848                         }
849                         char_type const c = par.getChar(i);
850                         w += singleWidth(par, i, c, *fi);
851                 }
852         }
853
854         if (body_pos > 0 && body_pos >= end) {
855                 w += fm.width(labelsep);
856                 if (end > 0 && par.isLineSeparator(end - 1))
857                         w -= singleWidth(par, end - 1);
858                 w = max(w, labelEnd(pit));
859         }
860
861         row.width(w + rightMargin(par));
862 }
863
864
865 // returns the minimum space a manual label needs on the screen in pixel
866 int LyXText::labelFill(Paragraph const & par, Row const & row) const
867 {
868         pos_type last = par.beginOfBody();
869
870         BOOST_ASSERT(last > 0);
871
872         // -1 because a label ends with a space that is in the label
873         --last;
874
875         // a separator at this end does not count
876         if (par.isLineSeparator(last))
877                 --last;
878
879         int w = 0;
880         for (pos_type i = row.pos(); i <= last; ++i)
881                 w += singleWidth(par, i);
882
883         string const & label = par.params().labelWidthString();
884         if (label.empty())
885                 return 0;
886
887         FontMetrics const & fm = theFontMetrics(getLabelFont(par));
888
889         // FIXME UNICODE
890         return max(0, fm.width(lyx::from_utf8(label)) - w);
891 }
892
893
894 LColor_color LyXText::backgroundColor() const
895 {
896         return LColor_color(LColor::color(background_color_));
897 }
898
899
900 void LyXText::setHeightOfRow(pit_type const pit, Row & row)
901 {
902         Paragraph const & par = pars_[pit];
903         // get the maximum ascent and the maximum descent
904         double layoutasc = 0;
905         double layoutdesc = 0;
906         double const dh = defaultRowHeight();
907
908         // ok, let us initialize the maxasc and maxdesc value.
909         // Only the fontsize count. The other properties
910         // are taken from the layoutfont. Nicer on the screen :)
911         LyXLayout_ptr const & layout = par.layout();
912
913         // as max get the first character of this row then it can
914         // increase but not decrease the height. Just some point to
915         // start with so we don't have to do the assignment below too
916         // often.
917         LyXFont font = getFont(par, row.pos());
918         LyXFont::FONT_SIZE const tmpsize = font.size();
919         font = getLayoutFont(pit);
920         LyXFont::FONT_SIZE const size = font.size();
921         font.setSize(tmpsize);
922
923         LyXFont labelfont = getLabelFont(par);
924
925         FontMetrics const & labelfont_metrics = theFontMetrics(labelfont);
926         FontMetrics const & fontmetrics = theFontMetrics(font);
927
928         // these are minimum values
929         double const spacing_val = layout->spacing.getValue() * spacing(par);
930         //lyxerr << "spacing_val = " << spacing_val << endl;
931         int maxasc  = int(fontmetrics.maxAscent()  * spacing_val);
932         int maxdesc = int(fontmetrics.maxDescent() * spacing_val);
933
934         // insets may be taller
935         InsetList::const_iterator ii = par.insetlist.begin();
936         InsetList::const_iterator iend = par.insetlist.end();
937         for ( ; ii != iend; ++ii) {
938                 if (ii->pos >= row.pos() && ii->pos < row.endpos()) {
939                         maxasc  = max(maxasc,  ii->inset->ascent());
940                         maxdesc = max(maxdesc, ii->inset->descent());
941                 }
942         }
943
944         // Check if any custom fonts are larger (Asger)
945         // This is not completely correct, but we can live with the small,
946         // cosmetic error for now.
947         int labeladdon = 0;
948         pos_type const pos_end = row.endpos();
949
950         LyXFont::FONT_SIZE maxsize =
951                 par.highestFontInRange(row.pos(), pos_end, size);
952         if (maxsize > font.size()) {
953                 font.setSize(maxsize);
954                 maxasc  = max(maxasc,  fontmetrics.maxAscent());
955                 maxdesc = max(maxdesc, fontmetrics.maxDescent());
956         }
957
958         // This is nicer with box insets:
959         ++maxasc;
960         ++maxdesc;
961
962         row.ascent(maxasc);
963
964         // is it a top line?
965         if (row.pos() == 0) {
966                 BufferParams const & bufparams = bv()->buffer()->params();
967                 // some parksips VERY EASY IMPLEMENTATION
968                 if (bv()->buffer()->params().paragraph_separation
969                     == BufferParams::PARSEP_SKIP
970                         && pit != 0
971                         && ((layout->isParagraph() && par.getDepth() == 0)
972                             || (pars_[pit - 1].layout()->isParagraph()
973                                 && pars_[pit - 1].getDepth() == 0)))
974                 {
975                                 maxasc += bufparams.getDefSkip().inPixels(*bv());
976                 }
977
978                 if (par.params().startOfAppendix())
979                         maxasc += int(3 * dh);
980
981                 // This is special code for the chapter, since the label of this
982                 // layout is printed in an extra row
983                 if (layout->counter == "chapter"
984                     && !par.params().labelString().empty()) {
985                         labeladdon = int(labelfont_metrics.maxHeight()
986                                      * layout->spacing.getValue()
987                                      * spacing(par));
988                 }
989
990                 // special code for the top label
991                 if ((layout->labeltype == LABEL_TOP_ENVIRONMENT
992                      || layout->labeltype == LABEL_BIBLIO
993                      || layout->labeltype == LABEL_CENTERED_TOP_ENVIRONMENT)
994                     && isFirstInSequence(pit, paragraphs())
995                     && !par.getLabelstring().empty())
996                 {
997                         labeladdon = int(
998                                   labelfont_metrics.maxHeight()
999                                         * layout->spacing.getValue()
1000                                         * spacing(par)
1001                                 + (layout->topsep + layout->labelbottomsep) * dh);
1002                 }
1003
1004                 // Add the layout spaces, for example before and after
1005                 // a section, or between the items of a itemize or enumerate
1006                 // environment.
1007
1008                 pit_type prev = depthHook(pit, pars_, par.getDepth());
1009                 if (prev != pit
1010                     && pars_[prev].layout() == layout
1011                     && pars_[prev].getDepth() == par.getDepth()
1012                     && pars_[prev].getLabelWidthString() == par.getLabelWidthString())
1013                 {
1014                         layoutasc = layout->itemsep * dh;
1015                 } else if (pit != 0 || row.pos() != 0) {
1016                         if (layout->topsep > 0)
1017                                 layoutasc = layout->topsep * dh;
1018                 }
1019
1020                 prev = outerHook(pit, pars_);
1021                 if (prev != pit_type(pars_.size())) {
1022                         maxasc += int(pars_[prev].layout()->parsep * dh);
1023                 } else if (pit != 0) {
1024                         if (pars_[pit - 1].getDepth() != 0 ||
1025                                         pars_[pit - 1].layout() == layout) {
1026                                 maxasc += int(layout->parsep * dh);
1027                         }
1028                 }
1029         }
1030
1031         // is it a bottom line?
1032         if (row.endpos() >= par.size()) {
1033                 // add the layout spaces, for example before and after
1034                 // a section, or between the items of a itemize or enumerate
1035                 // environment
1036                 pit_type nextpit = pit + 1;
1037                 if (nextpit != pit_type(pars_.size())) {
1038                         pit_type cpit = pit;
1039                         double usual = 0;
1040                         double unusual = 0;
1041
1042                         if (pars_[cpit].getDepth() > pars_[nextpit].getDepth()) {
1043                                 usual = pars_[cpit].layout()->bottomsep * dh;
1044                                 cpit = depthHook(cpit, paragraphs(), pars_[nextpit].getDepth());
1045                                 if (pars_[cpit].layout() != pars_[nextpit].layout()
1046                                         || pars_[nextpit].getLabelWidthString() != pars_[cpit].getLabelWidthString())
1047                                 {
1048                                         unusual = pars_[cpit].layout()->bottomsep * dh;
1049                                 }
1050                                 layoutdesc = max(unusual, usual);
1051                         } else if (pars_[cpit].getDepth() == pars_[nextpit].getDepth()) {
1052                                 if (pars_[cpit].layout() != pars_[nextpit].layout()
1053                                         || pars_[nextpit].getLabelWidthString() != pars_[cpit].getLabelWidthString())
1054                                         layoutdesc = int(pars_[cpit].layout()->bottomsep * dh);
1055                         }
1056                 }
1057         }
1058
1059         // incalculate the layout spaces
1060         maxasc  += int(layoutasc  * 2 / (2 + pars_[pit].getDepth()));
1061         maxdesc += int(layoutdesc * 2 / (2 + pars_[pit].getDepth()));
1062
1063         // FIXME: the correct way is to do the following is to move the 
1064         // following code in another method specially tailored for the 
1065         // main LyXText. The following test is thus bogus.
1066         LyXText const & text = bv_owner->buffer()->text();
1067         // Top and bottom margin of the document (only at top-level)
1068         if (&text == this) {
1069                 if (pit == 0 && row.pos() == 0)
1070                         maxasc += 20;
1071                 if (pit + 1 == pit_type(pars_.size()) &&
1072                     row.endpos() == par.size())
1073                         maxdesc += 20;
1074         }
1075
1076         row.ascent(maxasc + labeladdon);
1077         row.descent(maxdesc);
1078 }
1079
1080
1081 namespace {
1082
1083 }
1084
1085 void LyXText::breakParagraph(LCursor & cur, bool keep_layout)
1086 {
1087         BOOST_ASSERT(this == cur.text());
1088
1089         Paragraph & cpar = cur.paragraph();
1090         pit_type cpit = cur.pit();
1091
1092         LyXTextClass const & tclass = cur.buffer().params().getLyXTextClass();
1093         LyXLayout_ptr const & layout = cpar.layout();
1094
1095         // this is only allowed, if the current paragraph is not empty
1096         // or caption and if it has not the keepempty flag active
1097         if (cur.lastpos() == 0 && !cpar.allowEmpty()
1098            && layout->labeltype != LABEL_SENSITIVE)
1099                 return;
1100
1101         // a layout change may affect also the following paragraph
1102         recUndo(cur.pit(), undoSpan(cur.pit()) - 1);
1103
1104         // Always break behind a space
1105         // It is better to erase the space (Dekel)
1106         if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
1107                 // FIXME: change tracking (MG)
1108                 cpar.erase(cur.pos(), cur.buffer().params().trackChanges);
1109
1110         // How should the layout for the new paragraph be?
1111         int preserve_layout = 0;
1112         if (keep_layout)
1113                 preserve_layout = 2;
1114         else
1115                 preserve_layout = layout->isEnvironment();
1116
1117         // We need to remember this before we break the paragraph, because
1118         // that invalidates the layout variable
1119         bool sensitive = layout->labeltype == LABEL_SENSITIVE;
1120
1121         // we need to set this before we insert the paragraph.
1122         bool const isempty = cpar.allowEmpty() && cpar.empty();
1123
1124         ::breakParagraph(cur.buffer().params(), paragraphs(), cpit,
1125                          cur.pos(), preserve_layout);
1126
1127         // After this, neither paragraph contains any rows!
1128
1129         cpit = cur.pit();
1130         pit_type next_par = cpit + 1;
1131
1132         // well this is the caption hack since one caption is really enough
1133         if (sensitive) {
1134                 if (cur.pos() == 0)
1135                         // set to standard-layout
1136                         pars_[cpit].applyLayout(tclass.defaultLayout());
1137                 else
1138                         // set to standard-layout
1139                         pars_[next_par].applyLayout(tclass.defaultLayout());
1140         }
1141
1142         while (!pars_[next_par].empty() && pars_[next_par].isNewline(0))
1143                 // FIXME: change tracking (MG)
1144                 pars_[next_par].erase(0, cur.buffer().params().trackChanges);
1145
1146         ParIterator current_it(cur);
1147         ParIterator last_it(cur);
1148         ++last_it;
1149         ++last_it;
1150
1151         updateLabels(cur.buffer(), current_it, last_it);
1152
1153         // Mark "carriage return" as inserted if change tracking:
1154         if (cur.buffer().params().trackChanges) {
1155                 // FIXME: Change tracking (MG)
1156                 cur.paragraph().setChange(cur.paragraph().size(),
1157                         Change(Change::INSERTED));
1158         }
1159
1160         // This check is necessary. Otherwise the new empty paragraph will
1161         // be deleted automatically. And it is more friendly for the user!
1162         if (cur.pos() != 0 || isempty)
1163                 setCursor(cur, cur.pit() + 1, 0);
1164         else
1165                 setCursor(cur, cur.pit(), 0);
1166 }
1167
1168
1169 // insert a character, moves all the following breaks in the
1170 // same Paragraph one to the right and make a rebreak
1171 void LyXText::insertChar(LCursor & cur, char_type c)
1172 {
1173         BOOST_ASSERT(this == cur.text());
1174         BOOST_ASSERT(c != Paragraph::META_INSET);
1175
1176         recordUndo(cur, Undo::INSERT);
1177
1178         Paragraph & par = cur.paragraph();
1179         // try to remove this
1180         pit_type const pit = cur.pit();
1181
1182         bool const freeSpacing = par.layout()->free_spacing ||
1183                 par.isFreeSpacing();
1184
1185         if (lyxrc.auto_number) {
1186                 static docstring const number_operators = lyx::from_ascii("+-/*");
1187                 static docstring const number_unary_operators = lyx::from_ascii("+-");
1188                 static docstring const number_seperators = lyx::from_ascii(".,:");
1189
1190                 if (current_font.number() == LyXFont::ON) {
1191                         if (!isDigit(c) && !contains(number_operators, c) &&
1192                             !(contains(number_seperators, c) &&
1193                               cur.pos() != 0 &&
1194                               cur.pos() != cur.lastpos() &&
1195                               getFont(par, cur.pos()).number() == LyXFont::ON &&
1196                               getFont(par, cur.pos() - 1).number() == LyXFont::ON)
1197                            )
1198                                 number(cur); // Set current_font.number to OFF
1199                 } else if (isDigit(c) &&
1200                            real_current_font.isVisibleRightToLeft()) {
1201                         number(cur); // Set current_font.number to ON
1202
1203                         if (cur.pos() != 0) {
1204                                 char_type const c = par.getChar(cur.pos() - 1);
1205                                 if (contains(number_unary_operators, c) &&
1206                                     (cur.pos() == 1
1207                                      || par.isSeparator(cur.pos() - 2)
1208                                      || par.isNewline(cur.pos() - 2))
1209                                   ) {
1210                                         setCharFont(pit, cur.pos() - 1, current_font);
1211                                 } else if (contains(number_seperators, c)
1212                                      && cur.pos() >= 2
1213                                      && getFont(par, cur.pos() - 2).number() == LyXFont::ON) {
1214                                         setCharFont(pit, cur.pos() - 1, current_font);
1215                                 }
1216                         }
1217                 }
1218         }
1219
1220         // First check, if there will be two blanks together or a blank at
1221         // the beginning of a paragraph.
1222         // I decided to handle blanks like normal characters, the main
1223         // difference are the special checks when calculating the row.fill
1224         // (blank does not count at the end of a row) and the check here
1225
1226         // When the free-spacing option is set for the current layout,
1227         // disable the double-space checking
1228         if (!freeSpacing && isLineSeparatorChar(c)) {
1229                 if (cur.pos() == 0) {
1230                         static bool sent_space_message = false;
1231                         if (!sent_space_message) {
1232                                 cur.message(_("You cannot insert a space at the "
1233                                                            "beginning of a paragraph. Please read the Tutorial."));
1234                                 sent_space_message = true;
1235                         }
1236                         return;
1237                 }
1238                 BOOST_ASSERT(cur.pos() > 0);
1239                 if ((par.isLineSeparator(cur.pos() - 1)
1240                     || par.isNewline(cur.pos() - 1))
1241                     // FIXME: change tracking (MG)
1242                     && par.lookupChange(cur.pos() - 1) != Change(Change::DELETED)) {
1243                         static bool sent_space_message = false;
1244                         if (!sent_space_message) {
1245                                 cur.message(_("You cannot type two spaces this way. "
1246                                                            "Please read the Tutorial."));
1247                                 sent_space_message = true;
1248                         }
1249                         return;
1250                 }
1251         }
1252
1253         // FIXME: change tracking (MG)
1254         par.insertChar(cur.pos(), c, current_font, Change(Change::INSERTED));
1255         setCursor(cur, cur.pit(), cur.pos() + 1, false, cur.boundary());
1256         charInserted();
1257 }
1258
1259
1260 void LyXText::charInserted()
1261 {
1262         // Here we call finishUndo for every 20 characters inserted.
1263         // This is from my experience how emacs does it. (Lgb)
1264         static unsigned int counter;
1265         if (counter < 20) {
1266                 ++counter;
1267         } else {
1268                 finishUndo();
1269                 counter = 0;
1270         }
1271 }
1272
1273
1274 RowMetrics
1275 LyXText::computeRowMetrics(pit_type const pit, Row const & row) const
1276 {
1277         RowMetrics result;
1278         Paragraph const & par = pars_[pit];
1279
1280         double w = dim_.wid - row.width();
1281
1282         bool const is_rtl = isRTL(par);
1283         if (is_rtl)
1284                 result.x = rightMargin(par);
1285         else
1286                 result.x = leftMargin(pit, row.pos());
1287
1288         // is there a manual margin with a manual label
1289         LyXLayout_ptr const & layout = par.layout();
1290
1291         if (layout->margintype == MARGIN_MANUAL
1292             && layout->labeltype == LABEL_MANUAL) {
1293                 /// We might have real hfills in the label part
1294                 int nlh = numberOfLabelHfills(par, row);
1295
1296                 // A manual label par (e.g. List) has an auto-hfill
1297                 // between the label text and the body of the
1298                 // paragraph too.
1299                 // But we don't want to do this auto hfill if the par
1300                 // is empty.
1301                 if (!par.empty())
1302                         ++nlh;
1303
1304                 if (nlh && !par.getLabelWidthString().empty())
1305                         result.label_hfill = labelFill(par, row) / double(nlh);
1306         }
1307
1308         // are there any hfills in the row?
1309         int const nh = numberOfHfills(par, row);
1310
1311         if (nh) {
1312                 if (w > 0)
1313                         result.hfill = w / nh;
1314         // we don't have to look at the alignment if it is ALIGN_LEFT and
1315         // if the row is already larger then the permitted width as then
1316         // we force the LEFT_ALIGN'edness!
1317         } else if (int(row.width()) < maxwidth_) {
1318                 // is it block, flushleft or flushright?
1319                 // set x how you need it
1320                 int align;
1321                 if (par.params().align() == LYX_ALIGN_LAYOUT)
1322                         align = layout->align;
1323                 else
1324                         align = par.params().align();
1325
1326                 // Display-style insets should always be on a centred row
1327                 // The test on par.size() is to catch zero-size pars, which
1328                 // would trigger the assert in Paragraph::getInset().
1329                 //inset = par.size() ? par.getInset(row.pos()) : 0;
1330                 if (!par.empty()
1331                     && par.isInset(row.pos())
1332                     && par.getInset(row.pos())->display())
1333                 {
1334                         align = LYX_ALIGN_CENTER;
1335                 }
1336
1337                 switch (align) {
1338                 case LYX_ALIGN_BLOCK: {
1339                         int const ns = numberOfSeparators(par, row);
1340                         bool disp_inset = false;
1341                         if (row.endpos() < par.size()) {
1342                                 InsetBase const * in = par.getInset(row.endpos());
1343                                 if (in)
1344                                         disp_inset = in->display();
1345                         }
1346                         // If we have separators, this is not the last row of a
1347                         // par, does not end in newline, and is not row above a
1348                         // display inset... then stretch it
1349                         if (ns
1350                             && row.endpos() < par.size()
1351                             && !par.isNewline(row.endpos() - 1)
1352                             && !disp_inset
1353                                 ) {
1354                                 result.separator = w / ns;
1355                         } else if (is_rtl) {
1356                                 result.x += w;
1357                         }
1358                         break;
1359                 }
1360                 case LYX_ALIGN_RIGHT:
1361                         result.x += w;
1362                         break;
1363                 case LYX_ALIGN_CENTER:
1364                         result.x += w / 2;
1365                         break;
1366                 }
1367         }
1368
1369         bidi.computeTables(par, *bv()->buffer(), row);
1370         if (is_rtl) {
1371                 pos_type body_pos = par.beginOfBody();
1372                 pos_type end = row.endpos();
1373
1374                 if (body_pos > 0
1375                     && (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1376                 {
1377                         docstring const lsep = lyx::from_utf8(layout->labelsep);
1378                         result.x += theFontMetrics(getLabelFont(par)).width(lsep);
1379                         if (body_pos <= end)
1380                                 result.x += result.label_hfill;
1381                 }
1382         }
1383
1384         return result;
1385 }
1386
1387
1388 // the cursor set functions have a special mechanism. When they
1389 // realize, that you left an empty paragraph, they will delete it.
1390
1391 bool LyXText::cursorRightOneWord(LCursor & cur)
1392 {
1393         BOOST_ASSERT(this == cur.text());
1394
1395         LCursor old = cur;
1396
1397         if (old.pos() == old.lastpos() && old.pit() != old.lastpit()) {
1398                 ++old.pit();
1399                 old.pos() = 0;
1400         } else {
1401                 // Advance through word.
1402                 while (old.pos() != old.lastpos() && old.paragraph().isLetter(old.pos()))
1403                         ++old.pos();
1404                 // Skip through trailing nonword stuff.
1405                 while (old.pos() != old.lastpos() && !old.paragraph().isLetter(old.pos()))
1406                         ++old.pos();
1407         }
1408         return setCursor(cur, old.pit(), old.pos());
1409 }
1410
1411
1412 bool LyXText::cursorLeftOneWord(LCursor & cur)
1413 {
1414         BOOST_ASSERT(this == cur.text());
1415
1416         LCursor old = cur;
1417
1418         if (old.pos() == 0 && old.pit() != 0) {
1419                 --old.pit();
1420                 old.pos() = old.lastpos();
1421         } else {
1422                 // Skip through initial nonword stuff.
1423                 while (old.pos() != 0 && !old.paragraph().isLetter(old.pos() - 1))
1424                         --old.pos();
1425                 // Advance through word.
1426                 while (old.pos() != 0 && old.paragraph().isLetter(old.pos() - 1))
1427                         --old.pos();
1428         }
1429         return setCursor(cur, old.pit(), old.pos());
1430 }
1431
1432
1433 void LyXText::selectWord(LCursor & cur, word_location loc)
1434 {
1435         BOOST_ASSERT(this == cur.text());
1436         CursorSlice from = cur.top();
1437         CursorSlice to = cur.top();
1438         getWord(from, to, loc);
1439         if (cur.top() != from)
1440                 setCursor(cur, from.pit(), from.pos());
1441         if (to == from)
1442                 return;
1443         cur.resetAnchor();
1444         setCursor(cur, to.pit(), to.pos());
1445         cur.setSelection();
1446 }
1447
1448
1449 // Select the word currently under the cursor when no
1450 // selection is currently set
1451 bool LyXText::selectWordWhenUnderCursor(LCursor & cur, word_location loc)
1452 {
1453         BOOST_ASSERT(this == cur.text());
1454         if (cur.selection())
1455                 return false;
1456         selectWord(cur, loc);
1457         return cur.selection();
1458 }
1459
1460
1461 void LyXText::acceptChange(LCursor & cur)
1462 {
1463         BOOST_ASSERT(this == cur.text());
1464         if (!cur.selection() && cur.lastpos() != 0)
1465                 return;
1466
1467         recordUndoSelection(cur, Undo::INSERT);
1468
1469         DocIterator it = cur.selectionBegin();
1470         DocIterator et = cur.selectionEnd();
1471         pit_type pit = it.pit();
1472         Change::Type const type = pars_[pit].lookupChange(it.pos()).type;
1473         for (; pit <= et.pit(); ++pit) {
1474                 pos_type left  = ( pit == it.pit() ? it.pos() : 0 );
1475                 pos_type right =
1476                     ( pit == et.pit() ? et.pos() : pars_[pit].size() + 1 );
1477                 pars_[pit].acceptChange(left, right);
1478         }
1479         if (type == Change::DELETED) {
1480                 ParagraphList & plist = paragraphs();
1481                 if (it.pit() + 1 < et.pit())
1482                         pars_.erase(boost::next(plist.begin(), it.pit() + 1),
1483                                     boost::next(plist.begin(), et.pit()));
1484
1485                 // Paragraph merge if appropriate:
1486                 // FIXME: change tracking (MG)
1487                 if (pars_[it.pit()].lookupChange(pars_[it.pit()].size())
1488                         == Change(Change::DELETED)) {
1489                         setCursorIntern(cur, it.pit() + 1, 0);
1490                         backspacePos0(cur);
1491                 }
1492         }
1493         finishUndo();
1494         cur.clearSelection();
1495         setCursorIntern(cur, it.pit(), 0);
1496 }
1497
1498
1499 void LyXText::rejectChange(LCursor & cur)
1500 {
1501         BOOST_ASSERT(this == cur.text());
1502         if (!cur.selection() && cur.lastpos() != 0)
1503                 return;
1504
1505         recordUndoSelection(cur, Undo::INSERT);
1506
1507         DocIterator it = cur.selectionBegin();
1508         DocIterator et = cur.selectionEnd();
1509         pit_type pit = it.pit();
1510         Change::Type const type = pars_[pit].lookupChange(it.pos()).type;
1511         for (; pit <= et.pit(); ++pit) {
1512                 pos_type left  = ( pit == it.pit() ? it.pos() : 0 );
1513                 pos_type right =
1514                     ( pit == et.pit() ? et.pos() : pars_[pit].size() + 1 );
1515                 pars_[pit].rejectChange(left, right);
1516         }
1517         if (type == Change::INSERTED) {
1518                 ParagraphList & plist = paragraphs();
1519                 if (it.pit() + 1 < et.pit())
1520                         pars_.erase(boost::next(plist.begin(), it.pit() + 1),
1521                                     boost::next(plist.begin(), et.pit()));
1522                 // Paragraph merge if appropriate:
1523                 // FIXME: change tracking (MG)
1524                 if (pars_[it.pit()].lookupChange(pars_[it.pit()].size())
1525                         == Change(Change::INSERTED)) {
1526                         setCursorIntern(cur, it.pit() + 1, 0);
1527                         backspacePos0(cur);
1528                 }
1529         }
1530         finishUndo();
1531         cur.clearSelection();
1532         setCursorIntern(cur, it.pit(), 0);
1533 }
1534
1535
1536 // Delete from cursor up to the end of the current or next word.
1537 void LyXText::deleteWordForward(LCursor & cur)
1538 {
1539         BOOST_ASSERT(this == cur.text());
1540         if (cur.lastpos() == 0)
1541                 cursorRight(cur);
1542         else {
1543                 cur.resetAnchor();
1544                 cur.selection() = true;
1545                 cursorRightOneWord(cur);
1546                 cur.setSelection();
1547                 cutSelection(cur, true, false);
1548         }
1549 }
1550
1551
1552 // Delete from cursor to start of current or prior word.
1553 void LyXText::deleteWordBackward(LCursor & cur)
1554 {
1555         BOOST_ASSERT(this == cur.text());
1556         if (cur.lastpos() == 0)
1557                 cursorLeft(cur);
1558         else {
1559                 cur.resetAnchor();
1560                 cur.selection() = true;
1561                 cursorLeftOneWord(cur);
1562                 cur.setSelection();
1563                 cutSelection(cur, true, false);
1564         }
1565 }
1566
1567
1568 // Kill to end of line.
1569 void LyXText::deleteLineForward(LCursor & cur)
1570 {
1571         BOOST_ASSERT(this == cur.text());
1572         if (cur.lastpos() == 0) {
1573                 // Paragraph is empty, so we just go to the right
1574                 cursorRight(cur);
1575         } else {
1576                 cur.resetAnchor();
1577                 cur.selection() = true; // to avoid deletion
1578                 cursorEnd(cur);
1579                 cur.setSelection();
1580                 // What is this test for ??? (JMarc)
1581                 if (!cur.selection())
1582                         deleteWordForward(cur);
1583                 else
1584                         cutSelection(cur, true, false);
1585         }
1586 }
1587
1588
1589 void LyXText::changeCase(LCursor & cur, LyXText::TextCase action)
1590 {
1591         BOOST_ASSERT(this == cur.text());
1592         CursorSlice from;
1593         CursorSlice to;
1594
1595         if (cur.selection()) {
1596                 from = cur.selBegin();
1597                 to = cur.selEnd();
1598         } else {
1599                 from = cur.top();
1600                 getWord(from, to, lyx::PARTIAL_WORD);
1601                 cursorRightOneWord(cur);
1602         }
1603
1604         recordUndoSelection(cur);
1605
1606         pos_type pos = from.pos();
1607         int par = from.pit();
1608
1609         while (par != int(pars_.size()) && (pos != to.pos() || par != to.pit())) {
1610                 pit_type pit = par;
1611                 if (pos == pars_[pit].size()) {
1612                         ++par;
1613                         pos = 0;
1614                         continue;
1615                 }
1616                 char_type c = pars_[pit].getChar(pos);
1617                 if (c != Paragraph::META_INSET) {
1618                         switch (action) {
1619                         case text_lowercase:
1620                                 c = lowercase(c);
1621                                 break;
1622                         case text_capitalization:
1623                                 c = uppercase(c);
1624                                 action = text_lowercase;
1625                                 break;
1626                         case text_uppercase:
1627                                 c = uppercase(c);
1628                                 break;
1629                         }
1630                 }
1631 #ifdef WITH_WARNINGS
1632 #warning changes
1633 #endif
1634                 pars_[pit].setChar(pos, c);
1635                 ++pos;
1636         }
1637 }
1638
1639
1640 bool LyXText::erase(LCursor & cur)
1641 {
1642         BOOST_ASSERT(this == cur.text());
1643         bool needsUpdate = false;
1644
1645         if (cur.pos() != cur.lastpos()) {
1646                 recordUndo(cur, Undo::DELETE, cur.pit());
1647                 setCursorIntern(cur, cur.pit(), cur.pos() + 1, false, cur.boundary());
1648                 needsUpdate = backspace(cur);
1649                 // FIXME: change tracking (MG)
1650                 if (cur.paragraph().lookupChange(cur.pos()) == Change(Change::DELETED))
1651                         cur.posRight();
1652         } else if (cur.pit() != cur.lastpit()) {
1653                 LCursor scur = cur;
1654
1655                 setCursorIntern(cur, cur.pit() + 1, 0, false, false);
1656                 if (pars_[cur.pit()].layout() == pars_[scur.pit()].layout()) {
1657                         recordUndo(scur, Undo::DELETE, scur.pit());
1658                         needsUpdate = backspace(cur);
1659                         if (cur.buffer().params().trackChanges) {
1660                                 // FIXME: Change tracking (MG)
1661                                 // move forward after the paragraph break is DELETED
1662                                 Paragraph & par = cur.paragraph();
1663                                 // FIXME: change tracking (MG)
1664                                 if (par.lookupChange(par.size()) == Change(Change::DELETED))
1665                                         setCursorIntern(cur, cur.pit() + 1, 0);
1666                                 }
1667                 } else {
1668                         setCursorIntern(scur, scur.pit(), scur.pos(), false, scur.boundary());
1669                 }
1670         } else
1671                 needsUpdate = dissolveInset(cur);
1672
1673         return needsUpdate;
1674 }
1675
1676
1677 bool LyXText::backspacePos0(LCursor & cur)
1678 {
1679         BOOST_ASSERT(this == cur.text());
1680         bool needsUpdate = false;
1681
1682         Paragraph & par = cur.paragraph();
1683         // is it an empty paragraph?
1684         pos_type lastpos = cur.lastpos();
1685         if (lastpos == 0 || (lastpos == 1 && par.isSeparator(0))) {
1686                 // This is an empty paragraph and we delete it just
1687                 // by moving the cursor one step
1688                 // left and let the DeleteEmptyParagraphMechanism
1689                 // handle the actual deletion of the paragraph.
1690
1691                 if (cur.pit() != 0) {
1692                         // For KeepEmpty layouts we need to get
1693                         // rid of the keepEmpty setting first.
1694                         // And the only way to do this is to
1695                         // reset the layout to something
1696                         // else: f.ex. the default layout.
1697                         if (par.allowEmpty()) {
1698                                 Buffer & buf = cur.buffer();
1699                                 BufferParams const & bparams = buf.params();
1700                                 par.layout(bparams.getLyXTextClass().defaultLayout());
1701                         }
1702
1703                         cursorLeft(cur);
1704                         return true;
1705                 }
1706         }
1707
1708         if (cur.pit() != 0)
1709                 recordUndo(cur, Undo::DELETE, cur.pit() - 1);
1710
1711         pit_type tmppit = cur.pit();
1712         // We used to do cursorLeftIntern() here, but it is
1713         // not a good idea since it triggers the auto-delete
1714         // mechanism. So we do a cursorLeftIntern()-lite,
1715         // without the dreaded mechanism. (JMarc)
1716         if (cur.pit() != 0) {
1717                 // steps into the above paragraph.
1718                 setCursorIntern(cur, cur.pit() - 1,
1719                                 pars_[cur.pit() - 1].size(),
1720                                 false);
1721         }
1722
1723         // Pasting is not allowed, if the paragraphs have different
1724         // layout. I think it is a real bug of all other
1725         // word processors to allow it. It confuses the user.
1726         // Correction: Pasting is always allowed with standard-layout
1727         // Correction (Jug 20050717): Remove check about alignment!
1728         Buffer & buf = cur.buffer();
1729         BufferParams const & bufparams = buf.params();
1730         LyXTextClass const & tclass = bufparams.getLyXTextClass();
1731         pit_type const cpit = cur.pit();
1732
1733         if (cpit != tmppit
1734             && (pars_[cpit].layout() == pars_[tmppit].layout()
1735                 || pars_[tmppit].layout() == tclass.defaultLayout()))
1736         {
1737                 mergeParagraph(bufparams, pars_, cpit);
1738                 needsUpdate = true;
1739
1740                 if (cur.pos() != 0 && pars_[cpit].isSeparator(cur.pos() - 1))
1741                                 --cur.pos();
1742
1743                 // the counters may have changed
1744                 ParIterator par_it(cur);
1745                 updateLabels(cur.buffer(), par_it);
1746
1747                 setCursor(cur, cur.pit(), cur.pos(), false);
1748         }
1749         return needsUpdate;
1750 }
1751
1752
1753 bool LyXText::backspace(LCursor & cur)
1754 {
1755         BOOST_ASSERT(this == cur.text());
1756         bool needsUpdate = false;
1757         if (cur.pos() == 0) {
1758                 if (cur.pit() == 0)
1759                         return dissolveInset(cur);
1760
1761                 // The cursor is at the beginning of a paragraph, so
1762                 // the the backspace will collapse two paragraphs into
1763                 // one.
1764
1765                 if (cur.pit() != 0 && cur.buffer().params().trackChanges) {
1766                         // FIXME: Change tracking (MG)
1767                         // Previous paragraph, mark "carriage return" as
1768                         // deleted:
1769                         Paragraph & par = pars_[cur.pit() - 1];
1770                         // Take care of a just inserted para break:
1771                         // FIXME: change tracking (MG)
1772                         if (par.lookupChange(par.size()) != Change(Change::INSERTED)) {
1773                                 // FIXME: change tracking (MG)
1774                                 par.setChange(par.size(), Change(Change::DELETED));
1775                                 setCursorIntern(cur, cur.pit() - 1, par.size());
1776                                 return true;
1777                         }
1778                 }
1779
1780                 needsUpdate = backspacePos0(cur);
1781
1782         } else {
1783                 // this is the code for a normal backspace, not pasting
1784                 // any paragraphs
1785                 recordUndo(cur, Undo::DELETE);
1786                 // We used to do cursorLeftIntern() here, but it is
1787                 // not a good idea since it triggers the auto-delete
1788                 // mechanism. So we do a cursorLeftIntern()-lite,
1789                 // without the dreaded mechanism. (JMarc)
1790                 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1791                                 false, cur.boundary());
1792                 // FIXME: change tracking (MG)
1793                 cur.paragraph().erase(cur.pos(), cur.buffer().params().trackChanges);
1794         }
1795
1796         if (cur.pos() == cur.lastpos())
1797                 setCurrentFont(cur);
1798
1799         setCursor(cur, cur.pit(), cur.pos(), false, cur.boundary());
1800
1801         return needsUpdate;
1802 }
1803
1804
1805 bool LyXText::dissolveInset(LCursor & cur) {
1806         BOOST_ASSERT(this == cur.text());
1807
1808         if (isMainText() || cur.inset().nargs() != 1)
1809                 return false;
1810
1811         recordUndoInset(cur);
1812         cur.selHandle(false);
1813         // save position
1814         lyx::pos_type spos = cur.pos();
1815         lyx::pit_type spit = cur.pit();
1816         ParagraphList plist;
1817         if (cur.lastpit() != 0 || cur.lastpos() != 0)
1818                 plist = paragraphs();
1819         cur.popLeft();
1820         // store cursor offset
1821         if (spit == 0)
1822                 spos += cur.pos();
1823         spit += cur.pit();
1824         Buffer & b = cur.buffer();
1825         // FIXME: change tracking (MG)
1826         cur.paragraph().erase(cur.pos(), b.params().trackChanges);
1827         if (!plist.empty()) {
1828                 pasteParagraphList(cur, plist, b.params().textclass,
1829                                    b.errorList("Paste"));
1830                 // restore position
1831                 cur.pit() = std::min(cur.lastpit(), spit);
1832                 cur.pos() = std::min(cur.lastpos(), spos);
1833         }
1834         cur.clearSelection();
1835         cur.resetAnchor();
1836         return true;
1837 }
1838
1839
1840 Row const & LyXText::firstRow() const
1841 {
1842         return *paragraphs().front().rows().begin();
1843 }
1844
1845
1846 bool LyXText::redoParagraph(pit_type const pit)
1847 {
1848         // remove rows of paragraph, keep track of height changes
1849         Paragraph & par = pars_[pit];
1850
1851         // Add bibitem insets if necessary
1852         if (par.layout()->labeltype == LABEL_BIBLIO) {
1853                 bool hasbibitem(false);
1854                 if (!par.insetlist.empty()
1855                         // Insist on it being in pos 0
1856                         && par.getChar(0) == Paragraph::META_INSET) {
1857                         InsetBase * inset = par.insetlist.begin()->inset;
1858                         if (inset->lyxCode() == InsetBase::BIBITEM_CODE)
1859                                 hasbibitem = true;
1860                 }
1861                 if (!hasbibitem) {
1862                         InsetBibitem * inset(new
1863                                 InsetBibitem(InsetCommandParams("bibitem")));
1864                         // FIXME: change tracking (MG)
1865                         par.insertInset(0, static_cast<InsetBase *>(inset), Change(Change::INSERTED));
1866                         bv()->cursor().posRight();
1867                 }
1868         }
1869
1870         // redo insets
1871         // FIXME: We should always use getFont(), see documentation of
1872         // noFontChange() in insetbase.h.
1873         LyXFont const bufferfont = bv()->buffer()->params().getFont();
1874         InsetList::iterator ii = par.insetlist.begin();
1875         InsetList::iterator iend = par.insetlist.end();
1876         for (; ii != iend; ++ii) {
1877                 Dimension dim;
1878                 int const w = maxwidth_ - leftMargin(pit, ii->pos) - rightMargin(par);
1879                 LyXFont const & font = ii->inset->noFontChange() ?
1880                         bufferfont :
1881                         getFont(par, ii->pos);
1882                 MetricsInfo mi(bv(), font, w);
1883                 ii->inset->metrics(mi, dim);
1884         }
1885
1886         // rebreak the paragraph
1887         par.rows().clear();
1888         Dimension dim;
1889
1890         par.setBeginOfBody();
1891         pos_type z = 0;
1892         do {
1893                 Row row(z);
1894                 rowBreakPoint(pit, row);
1895                 setRowWidth(pit, row);
1896                 setHeightOfRow(pit, row);
1897                 par.rows().push_back(row);
1898                 dim.wid = std::max(dim.wid, row.width());
1899                 dim.des += row.height();
1900                 z = row.endpos();
1901         } while (z < par.size());
1902
1903         // Make sure that if a par ends in newline, there is one more row
1904         // under it
1905         // FIXME this is a dirty trick. Now the _same_ position in the
1906         // paragraph occurs in _two_ different rows, and has two different
1907         // display positions, leading to weird behaviour when moving up/down.
1908         if (z > 0 && par.isNewline(z - 1)) {
1909                 Row row(z - 1);
1910                 row.endpos(z - 1);
1911                 setRowWidth(pit, row);
1912                 setHeightOfRow(pit, row);
1913                 par.rows().push_back(row);
1914                 dim.des += row.height();
1915         }
1916
1917         dim.asc += par.rows()[0].ascent();
1918         dim.des -= par.rows()[0].ascent();
1919
1920         bool const same = dim == par.dim();
1921
1922         par.dim() = dim;
1923         //lyxerr << "redoParagraph: " << par.rows().size() << " rows\n";
1924
1925         return !same;
1926 }
1927
1928
1929 void LyXText::metrics(MetricsInfo & mi, Dimension & dim)
1930 {
1931         //BOOST_ASSERT(mi.base.textwidth);
1932         if (mi.base.textwidth)
1933                 maxwidth_ = mi.base.textwidth;
1934         //lyxerr << "LyXText::metrics: width: " << mi.base.textwidth
1935         //      << " maxWidth: " << maxwidth_ << "\nfont: " << mi.base.font << endl;
1936         // save the caller's font locally:
1937         font_ = mi.base.font;
1938
1939         unsigned int h = 0;
1940         unsigned int w = 0;
1941         for (pit_type pit = 0, n = paragraphs().size(); pit != n; ++pit) {
1942                 redoParagraph(pit);
1943                 Paragraph & par = paragraphs()[pit];
1944                 h += par.height();
1945                 if (w < par.width())
1946                         w = par.width();
1947         }
1948
1949         dim.wid = w;
1950         dim.asc = pars_[0].ascent();
1951         dim.des = h - dim.asc;
1952
1953         dim_ = dim;
1954 }
1955
1956
1957 // only used for inset right now. should also be used for main text
1958 void LyXText::draw(PainterInfo & pi, int x, int y) const
1959 {
1960         paintTextInset(*this, pi, x, y);
1961 }
1962
1963
1964 #if 0
1965 // only used for inset right now. should also be used for main text
1966 void LyXText::drawSelection(PainterInfo & pi, int x , int) const
1967 {
1968         LCursor & cur = pi.base.bv->cursor();
1969         if (!cur.selection())
1970                 return;
1971         if (!ptr_cmp(cur.text(), this))
1972                 return;
1973
1974         lyxerr << "draw selection at " << x << endl;
1975
1976         DocIterator beg = cur.selectionBegin();
1977         DocIterator end = cur.selectionEnd();
1978
1979         // the selection doesn't touch the visible screen
1980         if (bv_funcs::status(pi.base.bv, beg) == bv_funcs::CUR_BELOW
1981             || bv_funcs::status(pi.base.bv, end) == bv_funcs::CUR_ABOVE)
1982                 return;
1983
1984         Paragraph const & par1 = pars_[beg.pit()];
1985         Paragraph const & par2 = pars_[end.pit()];
1986
1987         Row const & row1 = par1.getRow(beg.pos(), beg.boundary());
1988         Row const & row2 = par2.getRow(end.pos(), end.boundary());
1989
1990         int y1,x1,x2;
1991         if (bv_funcs::status(pi.base.bv, beg) == bv_funcs::CUR_ABOVE) {
1992                 y1 = 0;
1993                 x1 = 0;
1994                 x2 = 0;
1995         } else {
1996                 y1 = bv_funcs::getPos(beg).y_ - row1.ascent();
1997                 int const startx = cursorX(beg.top(), begin.boundary());
1998                 x1 = isRTL(par1) ? startx : 0;
1999                 x2 = isRTL(par1) ? 0 + dim_.wid : startx;
2000         }
2001
2002         int y2,X1,X2;
2003         if (bv_funcs::status(pi.base.bv, end) == bv_funcs::CUR_BELOW) {
2004                 y2 = pi.base.bv->workHeight();
2005                 X1 = 0;
2006                 X2 = 0;
2007         } else {
2008                 y2 = bv_funcs::getPos(end).y_ + row2.descent();
2009                 int const endx = cursorX(end.top(), end.boundary());
2010                 X1 = isRTL(par2) ? 0 : endx;
2011                 X2 = isRTL(par2) ? endx : 0 + dim_.wid;
2012         }
2013
2014         lyxerr << " y1: " << y1 << " y2: " << y2
2015                 << " xo: " << xo_ << " wid: " << dim_.wid
2016                 << endl;
2017
2018         // paint big rectangle in one go
2019         pi.pain.fillRectangle(x, y1, dim_.wid, y2 - y1, LColor::selection);
2020
2021         // reset background at begin of first selected line
2022         pi.pain.fillRectangle(x + x1, y1, x2 - x1, row1.height(),
2023                 LColor::background);
2024
2025         // reset background at end of last selected line
2026         pi.pain.fillRectangle(x + X1, y2  - row2.height(),
2027                 X2 - X1, row2.height(), LColor::background);
2028 }
2029
2030 #else
2031
2032 void LyXText::drawSelection(PainterInfo & pi, int x, int) const
2033 {
2034         LCursor & cur = pi.base.bv->cursor();
2035         if (!cur.selection())
2036                 return;
2037         if (!ptr_cmp(cur.text(), this))
2038                 return;
2039
2040         lyxerr[Debug::DEBUG]
2041                 << BOOST_CURRENT_FUNCTION
2042                 << "draw selection at " << x
2043                 << endl;
2044
2045         DocIterator beg = cur.selectionBegin();
2046         DocIterator end = cur.selectionEnd();
2047
2048         BufferView * bv = pi.base.bv;
2049
2050         // the selection doesn't touch the visible screen
2051         if (bv_funcs::status(bv, beg) == bv_funcs::CUR_BELOW
2052             || bv_funcs::status(bv, end) == bv_funcs::CUR_ABOVE)
2053                 return;
2054
2055         Paragraph const & par1 = pars_[beg.pit()];
2056         Paragraph const & par2 = pars_[end.pit()];
2057
2058         bool const above = (bv_funcs::status(bv, beg)
2059                             == bv_funcs::CUR_ABOVE);
2060         bool const below = (bv_funcs::status(bv, end)
2061                             == bv_funcs::CUR_BELOW);
2062         int y1,y2,x1,x2;
2063         if (above) {
2064                 y1 = 0;
2065                 y2 = 0;
2066                 x1 = 0;
2067                 x2 = dim_.wid;
2068         } else {
2069                 Row const & row1 = par1.getRow(beg.pos(), beg.boundary());
2070                 y1 = bv_funcs::getPos(*bv, beg, beg.boundary()).y_ - row1.ascent();
2071                 y2 = y1 + row1.height();
2072                 int const startx = cursorX(beg.top(), beg.boundary());
2073                 x1 = !isRTL(par1) ? startx : 0;
2074                 x2 = !isRTL(par1) ? 0 + dim_.wid : startx;
2075         }
2076
2077         int Y1,Y2,X1,X2;
2078         if (below) {
2079                 Y1 = bv->workHeight();
2080                 Y2 = bv->workHeight();
2081                 X1 = 0;
2082                 X2 = dim_.wid;
2083         } else {
2084                 Row const & row2 = par2.getRow(end.pos(), end.boundary());
2085                 Y1 = bv_funcs::getPos(*bv, end, end.boundary()).y_ - row2.ascent();
2086                 Y2 = Y1 + row2.height();
2087                 int const endx = cursorX(end.top(), end.boundary());
2088                 X1 = !isRTL(par2) ? 0 : endx;
2089                 X2 = !isRTL(par2) ? endx : 0 + dim_.wid;
2090         }
2091
2092         if (!above && !below && &par1.getRow(beg.pos(), beg.boundary())
2093             == &par2.getRow(end.pos(), end.boundary()))
2094         {
2095                 // paint only one rectangle
2096                 int const b( !isRTL(par1) ? x + x1 : x + X1 );
2097                 int const w( !isRTL(par1) ? X2 - x1 : x2 - X1 );
2098                 pi.pain.fillRectangle(b, y1, w, y2 - y1, LColor::selection);
2099                 return;
2100         }
2101
2102         lyxerr[Debug::DEBUG] << " y1: " << y1 << " y2: " << y2
2103                << "X1:" << X1 << " x2: " << X2 << " wid: " << dim_.wid
2104                 << endl;
2105
2106         // paint upper rectangle
2107         pi.pain.fillRectangle(x + x1, y1, x2 - x1, y2 - y1,
2108                                       LColor::selection);
2109         // paint bottom rectangle
2110         pi.pain.fillRectangle(x + X1, Y1, X2 - X1, Y2 - Y1,
2111                                       LColor::selection);
2112         // paint center rectangle
2113         pi.pain.fillRectangle(x, y2, dim_.wid,
2114                               Y1 - y2, LColor::selection);
2115 }
2116 #endif
2117
2118 bool LyXText::isLastRow(pit_type pit, Row const & row) const
2119 {
2120         return row.endpos() >= pars_[pit].size()
2121                 && pit + 1 == pit_type(paragraphs().size());
2122 }
2123
2124
2125 bool LyXText::isFirstRow(pit_type pit, Row const & row) const
2126 {
2127         return row.pos() == 0 && pit == 0;
2128 }
2129
2130
2131 void LyXText::getWord(CursorSlice & from, CursorSlice & to,
2132         word_location const loc)
2133 {
2134         Paragraph const & from_par = pars_[from.pit()];
2135         switch (loc) {
2136         case lyx::WHOLE_WORD_STRICT:
2137                 if (from.pos() == 0 || from.pos() == from_par.size()
2138                     || !from_par.isLetter(from.pos())
2139                     || !from_par.isLetter(from.pos() - 1)) {
2140                         to = from;
2141                         return;
2142                 }
2143                 // no break here, we go to the next
2144
2145         case lyx::WHOLE_WORD:
2146                 // If we are already at the beginning of a word, do nothing
2147                 if (!from.pos() || !from_par.isLetter(from.pos() - 1))
2148                         break;
2149                 // no break here, we go to the next
2150
2151         case lyx::PREVIOUS_WORD:
2152                 // always move the cursor to the beginning of previous word
2153                 while (from.pos() && from_par.isLetter(from.pos() - 1))
2154                         --from.pos();
2155                 break;
2156         case lyx::NEXT_WORD:
2157                 lyxerr << "LyXText::getWord: NEXT_WORD not implemented yet"
2158                        << endl;
2159                 break;
2160         case lyx::PARTIAL_WORD:
2161                 // no need to move the 'from' cursor
2162                 break;
2163         }
2164         to = from;
2165         Paragraph & to_par = pars_[to.pit()];
2166         while (to.pos() < to_par.size() && to_par.isLetter(to.pos()))
2167                 ++to.pos();
2168 }
2169
2170
2171 void LyXText::write(Buffer const & buf, std::ostream & os) const
2172 {
2173         ParagraphList::const_iterator pit = paragraphs().begin();
2174         ParagraphList::const_iterator end = paragraphs().end();
2175         Paragraph::depth_type dth = 0;
2176         for (; pit != end; ++pit)
2177                 pit->write(buf, os, buf.params(), dth);
2178 }
2179
2180
2181 bool LyXText::read(Buffer const & buf, LyXLex & lex, ErrorList & errorList)
2182 {
2183         Paragraph::depth_type depth = 0;
2184
2185         while (lex.isOK()) {
2186                 lex.nextToken();
2187                 string const token = lex.getString();
2188
2189                 if (token.empty())
2190                         continue;
2191
2192                 if (token == "\\end_inset") {
2193                         break;
2194                 }
2195
2196                 if (token == "\\end_body") {
2197                         continue;
2198                 }
2199
2200                 if (token == "\\begin_body") {
2201                         continue;
2202                 }
2203
2204                 if (token == "\\end_document") {
2205                         return false;
2206                 }
2207
2208                 if (token == "\\begin_layout") {
2209                         lex.pushToken(token);
2210
2211                         Paragraph par;
2212                         par.params().depth(depth);
2213                         par.setFont(0, LyXFont(LyXFont::ALL_INHERIT, buf.params().language));
2214                         pars_.push_back(par);
2215
2216                         // FIXME: goddamn InsetTabular makes us pass a Buffer
2217                         // not BufferParams
2218                         ::readParagraph(buf, pars_.back(), lex, errorList);
2219
2220                 } else if (token == "\\begin_deeper") {
2221                         ++depth;
2222                 } else if (token == "\\end_deeper") {
2223                         if (!depth) {
2224                                 lex.printError("\\end_deeper: " "depth is already null");
2225                         } else {
2226                                 --depth;
2227                         }
2228                 } else {
2229                         lyxerr << "Handling unknown body token: `"
2230                                << token << '\'' << endl;
2231                 }
2232         }
2233         return true;
2234 }
2235
2236
2237 int LyXText::ascent() const
2238 {
2239         return dim_.asc;
2240 }
2241
2242
2243 int LyXText::descent() const
2244 {
2245         return dim_.des;
2246 }
2247
2248
2249 int LyXText::cursorX(CursorSlice const & sl, bool boundary) const
2250 {
2251         pit_type const pit = sl.pit();
2252         Paragraph const & par = pars_[pit];
2253         if (par.rows().empty())
2254                 return 0;
2255
2256         pos_type ppos = sl.pos();
2257         // Correct position in front of big insets
2258         bool const boundary_correction = ppos != 0 && boundary;
2259         if (boundary_correction)
2260                 --ppos;
2261
2262         Row const & row = par.getRow(sl.pos(), boundary);
2263
2264         pos_type cursor_vpos = 0;
2265
2266         RowMetrics const m = computeRowMetrics(pit, row);
2267         double x = m.x;
2268
2269         pos_type const row_pos  = row.pos();
2270         pos_type const end      = row.endpos();
2271
2272         if (end <= row_pos)
2273                 cursor_vpos = row_pos;
2274         else if (ppos >= end)
2275                 cursor_vpos = isRTL(par) ? row_pos : end;
2276         else if (ppos > row_pos && ppos >= end)
2277                 // Place cursor after char at (logical) position pos - 1
2278                 cursor_vpos = (bidi.level(ppos - 1) % 2 == 0)
2279                         ? bidi.log2vis(ppos - 1) + 1 : bidi.log2vis(ppos - 1);
2280         else
2281                 // Place cursor before char at (logical) position ppos
2282                 cursor_vpos = (bidi.level(ppos) % 2 == 0)
2283                         ? bidi.log2vis(ppos) : bidi.log2vis(ppos) + 1;
2284
2285         pos_type body_pos = par.beginOfBody();
2286         if (body_pos > 0 &&
2287             (body_pos > end || !par.isLineSeparator(body_pos - 1)))
2288                 body_pos = 0;
2289
2290         // Use font span to speed things up, see below
2291         FontSpan font_span;
2292         LyXFont font;
2293         FontMetrics const & labelfm = theFontMetrics(getLabelFont(par));
2294
2295         for (pos_type vpos = row_pos; vpos < cursor_vpos; ++vpos) {
2296                 pos_type pos = bidi.vis2log(vpos);
2297                 if (body_pos > 0 && pos == body_pos - 1) {
2298                         // FIXME UNICODE
2299                         docstring const lsep = lyx::from_utf8(par.layout()->labelsep);
2300                         x += m.label_hfill + labelfm.width(lsep);
2301                         if (par.isLineSeparator(body_pos - 1))
2302                                 x -= singleWidth(par, body_pos - 1);
2303                 }
2304
2305                 // Use font span to speed things up, see above
2306                 if (pos < font_span.first || pos > font_span.last) {
2307                         font_span = par.fontSpan(pos);
2308                         font = getFont(par, pos);
2309                 }
2310
2311                 x += singleWidth(par, pos, par.getChar(pos), font);
2312
2313                 if (hfillExpansion(par, row, pos))
2314                         x += (pos >= body_pos) ? m.hfill : m.label_hfill;
2315                 else if (par.isSeparator(pos) && pos >= body_pos)
2316                         x += m.separator;
2317         }
2318
2319         // see correction above
2320         if (boundary_correction)
2321                 if (getFont(par, ppos).isVisibleRightToLeft())
2322                         x -= singleWidth(par, ppos);
2323                 else
2324                         x += singleWidth(par, ppos);
2325
2326         // Make sure inside an inset we always count from the left
2327         // edge (bidi!) -- MV
2328         if (sl.pos() < par.size()) {
2329                 font = getFont(par, sl.pos());
2330                 if (!boundary && font.isVisibleRightToLeft()
2331                   && par.isInset(sl.pos()))
2332                         x -= par.getInset(sl.pos())->width();
2333         }
2334         return int(x);
2335 }
2336
2337
2338 int LyXText::cursorY(CursorSlice const & sl, bool boundary) const
2339 {
2340         //lyxerr << "LyXText::cursorY: boundary: " << boundary << std::endl;
2341         Paragraph const & par = getPar(sl.pit());
2342         if (par.rows().empty())
2343                 return 0;
2344
2345         int h = 0;
2346         h -= pars_[0].rows()[0].ascent();
2347         for (pit_type pit = 0; pit < sl.pit(); ++pit)
2348                 h += pars_[pit].height();
2349         int pos = sl.pos();
2350         if (pos && boundary)
2351                 --pos;
2352         size_t const rend = par.pos2row(pos);
2353         for (size_t rit = 0; rit != rend; ++rit)
2354                 h += par.rows()[rit].height();
2355         h += par.rows()[rend].ascent();
2356         return h;
2357 }
2358
2359
2360 // Returns the current font and depth as a message.
2361 string LyXText::currentState(LCursor & cur)
2362 {
2363         BOOST_ASSERT(this == cur.text());
2364         Buffer & buf = cur.buffer();
2365         Paragraph const & par = cur.paragraph();
2366         std::ostringstream os;
2367
2368         // FIXME: change tracking (MG)
2369         bool const show_change = par.lookupChange(cur.pos()) != Change(Change::UNCHANGED);
2370
2371         if (buf.params().trackChanges)
2372                 os << "[C] ";
2373
2374         if (show_change) {
2375                 Change change = par.lookupChange(cur.pos());
2376                 Author const & a = buf.params().authors().get(change.author);
2377                 os << lyx::to_utf8(_("Change: ")) << a.name();
2378                 if (!a.email().empty())
2379                         os << " (" << a.email() << ")";
2380                 if (change.changetime)
2381                         os << lyx::to_utf8(_(" at ")) << ctime(&change.changetime);
2382                 os << " : ";
2383         }
2384
2385         // I think we should only show changes from the default
2386         // font. (Asger)
2387         // No, from the document font (MV)
2388         LyXFont font = real_current_font;
2389         font.reduce(buf.params().getFont());
2390
2391         // avoid lyx::to_utf8(_(...)) re-entrance problem
2392         string const s = font.stateText(&buf.params());
2393         os << lyx::to_utf8(bformat(_("Font: %1$s"), lyx::from_utf8(s)));
2394
2395         // os << lyx::to_utf8(bformat(_("Font: %1$s"), font.stateText(&buf.params)));
2396
2397         // The paragraph depth
2398         int depth = cur.paragraph().getDepth();
2399         if (depth > 0)
2400                 os << lyx::to_utf8(bformat(_(", Depth: %1$d"), depth));
2401
2402         // The paragraph spacing, but only if different from
2403         // buffer spacing.
2404         Spacing const & spacing = par.params().spacing();
2405         if (!spacing.isDefault()) {
2406                 os << lyx::to_utf8(_(", Spacing: "));
2407                 switch (spacing.getSpace()) {
2408                 case Spacing::Single:
2409                         os << lyx::to_utf8(_("Single"));
2410                         break;
2411                 case Spacing::Onehalf:
2412                         os << lyx::to_utf8(_("OneHalf"));
2413                         break;
2414                 case Spacing::Double:
2415                         os << lyx::to_utf8(_("Double"));
2416                         break;
2417                 case Spacing::Other:
2418                         os << lyx::to_utf8(_("Other (")) << spacing.getValueAsString() << ')';
2419                         break;
2420                 case Spacing::Default:
2421                         // should never happen, do nothing
2422                         break;
2423                 }
2424         }
2425
2426 #ifdef DEVEL_VERSION
2427         os << lyx::to_utf8(_(", Inset: ")) << &cur.inset();
2428         os << lyx::to_utf8(_(", Paragraph: ")) << cur.pit();
2429         os << lyx::to_utf8(_(", Id: ")) << par.id();
2430         os << lyx::to_utf8(_(", Position: ")) << cur.pos();
2431         os << lyx::to_utf8(_(", Boundary: ")) << cur.boundary();
2432 //      Row & row = cur.textRow();
2433 //      os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
2434 #endif
2435         return os.str();
2436 }
2437
2438
2439 string LyXText::getPossibleLabel(LCursor & cur) const
2440 {
2441         pit_type pit = cur.pit();
2442
2443         LyXLayout_ptr layout = pars_[pit].layout();
2444
2445         if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
2446                 LyXLayout_ptr const & layout2 = pars_[pit - 1].layout();
2447                 if (layout2->latextype != LATEX_PARAGRAPH) {
2448                         --pit;
2449                         layout = layout2;
2450                 }
2451         }
2452
2453         string name = layout->latexname();
2454
2455         // for captions, we want the abbreviation of the float type
2456         if (layout->labeltype == LABEL_SENSITIVE) {
2457                 // Search for the first float or wrap inset in the iterator
2458                 size_t i = cur.depth();
2459                 while (i > 0) {
2460                         --i;
2461                         InsetBase * const in = &cur[i].inset();
2462                         if (in->lyxCode() == InsetBase::FLOAT_CODE
2463                             || in->lyxCode() == InsetBase::WRAP_CODE) {
2464                                 name = in->getInsetName();
2465                                 break;
2466                         }
2467                 }
2468         }
2469
2470         string text = name.substr(0, 3);
2471         if (name == "theorem")
2472                 text = "thm"; // Create a correct prefix for prettyref
2473
2474         text += ':';
2475         if (layout->latextype == LATEX_PARAGRAPH || lyxrc.label_init_length < 0)
2476                 text.erase();
2477
2478         // FIXME UNICODE
2479         string par_text = lyx::to_utf8(pars_[pit].asString(cur.buffer(), false));
2480         for (int i = 0; i < lyxrc.label_init_length; ++i) {
2481                 if (par_text.empty())
2482                         break;
2483                 string head;
2484                 par_text = split(par_text, head, ' ');
2485                 // Is it legal to use spaces in labels ?
2486                 if (i > 0)
2487                         text += '-';
2488                 text += head;
2489         }
2490
2491         return text;
2492 }
2493
2494
2495 //pos_type LyXText::x2pos(pit_type pit, int row, int x) const
2496 //{
2497 //      int lastx = 0;
2498 //      int currx = 0;
2499 //      Paragraph const & par = pars_[pit];
2500 //      Row const & r = par.rows()[row];
2501 //      int pos = r.pos();
2502 //      for (; currx < x && pos < r.endpos(); ++pos) {
2503 //              lastx = currx;
2504 //              currx += singleWidth(par, pos);
2505 //      }
2506 //      if (abs(lastx - x) < abs(currx - x) && pos != r.pos())
2507 //              --pos;
2508 //      return pos;
2509 //}
2510
2511
2512 pos_type LyXText::x2pos(pit_type pit, int row, int x) const
2513 {
2514         BOOST_ASSERT(row < int(pars_[pit].rows().size()));
2515         bool bound = false;
2516         Row const & r = pars_[pit].rows()[row];
2517         return r.pos() + getColumnNearX(pit, r, x, bound);
2518 }
2519
2520
2521 //int LyXText::pos2x(pit_type pit, pos_type pos) const
2522 //{
2523 //      Paragraph const & par = pars_[pit];
2524 //      Row const & r = par.rows()[row];
2525 //      int x = 0;
2526 //      pos -= r.pos();
2527 //}
2528
2529
2530 // x,y are screen coordinates
2531 // sets cursor only within this LyXText
2532 bool LyXText::setCursorFromCoordinates(LCursor & cur, int const x, int const y)
2533 {
2534         BOOST_ASSERT(this == cur.text());
2535         pit_type pit = getPitNearY(y);
2536         int yy = cur.bv().coordCache().get(this, pit).y_ - pars_[pit].ascent();
2537         lyxerr[Debug::DEBUG]
2538                 << BOOST_CURRENT_FUNCTION
2539                 << ": x: " << x
2540                 << " y: " << y
2541                 << " pit: " << pit
2542                 << " yy: " << yy << endl;
2543
2544         Paragraph const & par = pars_[pit];
2545         int r = 0;
2546         BOOST_ASSERT(par.rows().size());
2547         for (; r < int(par.rows().size()) - 1; ++r) {
2548                 Row const & row = par.rows()[r];
2549                 if (int(yy + row.height()) > y)
2550                         break;
2551                 yy += row.height();
2552         }
2553
2554         Row const & row = par.rows()[r];
2555
2556         lyxerr[Debug::DEBUG]
2557                 << BOOST_CURRENT_FUNCTION
2558                 << ": row " << r
2559                 << " from pos: " << row.pos()
2560                 << endl;
2561
2562         bool bound = false;
2563         int xx = x;
2564         pos_type const pos = row.pos() + getColumnNearX(pit, row, xx, bound);
2565
2566         lyxerr[Debug::DEBUG]
2567                 << BOOST_CURRENT_FUNCTION
2568                 << ": setting cursor pit: " << pit
2569                 << " pos: " << pos
2570                 << endl;
2571
2572         return setCursor(cur, pit, pos, true, bound);
2573 }