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