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