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