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