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