]> git.lyx.org Git - lyx.git/blob - src/text.C
The bug-fix in revision 16531 introduced another bug. This is the right fix. I did...
[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 LColor_color LyXText::backgroundColor() const
583 {
584         return LColor_color(LColor::color(background_color_));
585 }
586
587
588 void LyXText::breakParagraph(LCursor & cur, bool keep_layout)
589 {
590         BOOST_ASSERT(this == cur.text());
591
592         Paragraph & cpar = cur.paragraph();
593         pit_type cpit = cur.pit();
594
595         LyXTextClass const & tclass = cur.buffer().params().getLyXTextClass();
596         LyXLayout_ptr const & layout = cpar.layout();
597
598         // this is only allowed, if the current paragraph is not empty
599         // or caption and if it has not the keepempty flag active
600         if (cur.lastpos() == 0 && !cpar.allowEmpty() &&
601             layout->labeltype != LABEL_SENSITIVE)
602                 return;
603
604         // a layout change may affect also the following paragraph
605         recUndo(cur, cur.pit(), undoSpan(cur.pit()) - 1);
606
607         // Always break behind a space
608         // It is better to erase the space (Dekel)
609         if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
610                 cpar.eraseChar(cur.pos(), cur.buffer().params().trackChanges);
611
612         // What should the layout for the new paragraph be?
613         int preserve_layout = 0;
614         if (keep_layout)
615                 preserve_layout = 2;
616         else
617                 preserve_layout = layout->isEnvironment();
618
619         // We need to remember this before we break the paragraph, because
620         // that invalidates the layout variable
621         bool sensitive = layout->labeltype == LABEL_SENSITIVE;
622
623         // we need to set this before we insert the paragraph.
624         bool const isempty = cpar.allowEmpty() && cpar.empty();
625
626         lyx::breakParagraph(cur.buffer().params(), paragraphs(), cpit,
627                          cur.pos(), preserve_layout);
628
629         // After this, neither paragraph contains any rows!
630
631         cpit = cur.pit();
632         pit_type next_par = cpit + 1;
633
634         // well this is the caption hack since one caption is really enough
635         if (sensitive) {
636                 if (cur.pos() == 0)
637                         // set to standard-layout
638                         pars_[cpit].applyLayout(tclass.defaultLayout());
639                 else
640                         // set to standard-layout
641                         pars_[next_par].applyLayout(tclass.defaultLayout());
642         }
643
644         while (!pars_[next_par].empty() && pars_[next_par].isNewline(0))
645                 pars_[next_par].eraseChar(0, cur.buffer().params().trackChanges);
646
647         ParIterator current_it(cur);
648         ParIterator last_it(cur);
649         ++last_it;
650         ++last_it;
651
652         updateLabels(cur.buffer(), current_it, last_it);
653
654         // A singlePar update is not enough in this case.
655         cur.updateFlags(Update::Force);
656
657         // This check is necessary. Otherwise the new empty paragraph will
658         // be deleted automatically. And it is more friendly for the user!
659         if (cur.pos() != 0 || isempty)
660                 setCursor(cur.top(), cur.pit() + 1, 0);
661         else
662                 setCursor(cur.top(), cur.pit(), 0);
663 }
664
665
666 // insert a character, moves all the following breaks in the
667 // same Paragraph one to the right and make a rebreak
668 void LyXText::insertChar(LCursor & cur, char_type c)
669 {
670         BOOST_ASSERT(this == cur.text());
671         BOOST_ASSERT(c != Paragraph::META_INSET);
672
673         recordUndo(cur, Undo::INSERT);
674
675         Buffer const & buffer = cur.buffer();
676         Paragraph & par = cur.paragraph();
677         // try to remove this
678         pit_type const pit = cur.pit();
679
680         bool const freeSpacing = par.layout()->free_spacing ||
681                 par.isFreeSpacing();
682
683         if (lyxrc.auto_number) {
684                 static docstring const number_operators = from_ascii("+-/*");
685                 static docstring const number_unary_operators = from_ascii("+-");
686                 static docstring const number_seperators = from_ascii(".,:");
687
688                 if (current_font.number() == LyXFont::ON) {
689                         if (!isDigit(c) && !contains(number_operators, c) &&
690                             !(contains(number_seperators, c) &&
691                               cur.pos() != 0 &&
692                               cur.pos() != cur.lastpos() &&
693                               getFont(buffer, par, cur.pos()).number() == LyXFont::ON &&
694                               getFont(buffer, par, cur.pos() - 1).number() == LyXFont::ON)
695                            )
696                                 number(cur); // Set current_font.number to OFF
697                 } else if (isDigit(c) &&
698                            real_current_font.isVisibleRightToLeft()) {
699                         number(cur); // Set current_font.number to ON
700
701                         if (cur.pos() != 0) {
702                                 char_type const c = par.getChar(cur.pos() - 1);
703                                 if (contains(number_unary_operators, c) &&
704                                     (cur.pos() == 1
705                                      || par.isSeparator(cur.pos() - 2)
706                                      || par.isNewline(cur.pos() - 2))
707                                   ) {
708                                         setCharFont(buffer, pit, cur.pos() - 1, current_font);
709                                 } else if (contains(number_seperators, c)
710                                      && cur.pos() >= 2
711                                      && getFont(buffer, par, cur.pos() - 2).number() == LyXFont::ON) {
712                                         setCharFont(buffer, pit, cur.pos() - 1, current_font);
713                                 }
714                         }
715                 }
716         }
717
718         // First check, if there will be two blanks together or a blank at
719         // the beginning of a paragraph.
720         // I decided to handle blanks like normal characters, the main
721         // difference are the special checks when calculating the row.fill
722         // (blank does not count at the end of a row) and the check here
723
724         // When the free-spacing option is set for the current layout,
725         // disable the double-space checking
726         if (!freeSpacing && isLineSeparatorChar(c)) {
727                 if (cur.pos() == 0) {
728                         static bool sent_space_message = false;
729                         if (!sent_space_message) {
730                                 cur.message(_("You cannot insert a space at the "
731                                                            "beginning of a paragraph. Please read the Tutorial."));
732                                 sent_space_message = true;
733                         }
734                         return;
735                 }
736                 BOOST_ASSERT(cur.pos() > 0);
737                 if ((par.isLineSeparator(cur.pos() - 1) || par.isNewline(cur.pos() - 1))
738                     && !par.isDeleted(cur.pos() - 1)) {
739                         static bool sent_space_message = false;
740                         if (!sent_space_message) {
741                                 cur.message(_("You cannot type two spaces this way. "
742                                                            "Please read the Tutorial."));
743                                 sent_space_message = true;
744                         }
745                         return;
746                 }
747         }
748
749         par.insertChar(cur.pos(), c, current_font, cur.buffer().params().trackChanges);
750
751 //              cur.updateFlags(Update::Force);
752         setCursor(cur.top(), cur.pit(), cur.pos() + 1);
753         charInserted();
754 }
755
756
757 void LyXText::charInserted()
758 {
759         // Here we call finishUndo for every 20 characters inserted.
760         // This is from my experience how emacs does it. (Lgb)
761         static unsigned int counter;
762         if (counter < 20) {
763                 ++counter;
764         } else {
765                 finishUndo();
766                 counter = 0;
767         }
768 }
769
770
771 // the cursor set functions have a special mechanism. When they
772 // realize, that you left an empty paragraph, they will delete it.
773
774 bool LyXText::cursorRightOneWord(LCursor & cur)
775 {
776         BOOST_ASSERT(this == cur.text());
777
778         LCursor old = cur;
779
780         if (old.pos() == old.lastpos() && old.pit() != old.lastpit()) {
781                 ++old.pit();
782                 old.pos() = 0;
783         } else {
784                 // Advance through word.
785                 while (old.pos() != old.lastpos() && old.paragraph().isLetter(old.pos()))
786                         ++old.pos();
787                 // Skip through trailing nonword stuff.
788                 while (old.pos() != old.lastpos() && !old.paragraph().isLetter(old.pos()))
789                         ++old.pos();
790         }
791         return setCursor(cur, old.pit(), old.pos());
792 }
793
794
795 bool LyXText::cursorLeftOneWord(LCursor & cur)
796 {
797         BOOST_ASSERT(this == cur.text());
798
799         LCursor old = cur;
800
801         if (old.pos() == 0 && old.pit() != 0) {
802                 --old.pit();
803                 old.pos() = old.lastpos();
804         } else {
805                 // Skip through initial nonword stuff.
806                 while (old.pos() != 0 && !old.paragraph().isLetter(old.pos() - 1))
807                         --old.pos();
808                 // Advance through word.
809                 while (old.pos() != 0 && old.paragraph().isLetter(old.pos() - 1))
810                         --old.pos();
811         }
812         return setCursor(cur, old.pit(), old.pos());
813 }
814
815
816 void LyXText::selectWord(LCursor & cur, word_location loc)
817 {
818         BOOST_ASSERT(this == cur.text());
819         CursorSlice from = cur.top();
820         CursorSlice to = cur.top();
821         getWord(from, to, loc);
822         if (cur.top() != from)
823                 setCursor(cur, from.pit(), from.pos());
824         if (to == from)
825                 return;
826         cur.resetAnchor();
827         setCursor(cur, to.pit(), to.pos());
828         cur.setSelection();
829 }
830
831
832 // Select the word currently under the cursor when no
833 // selection is currently set
834 bool LyXText::selectWordWhenUnderCursor(LCursor & cur, word_location loc)
835 {
836         BOOST_ASSERT(this == cur.text());
837         if (cur.selection())
838                 return false;
839         selectWord(cur, loc);
840         return cur.selection();
841 }
842
843
844 void LyXText::acceptChange(LCursor & cur)
845 {
846         // FIXME: change tracking (MG)
847
848         BOOST_ASSERT(this == cur.text());
849
850         if (!cur.selection() && cur.lastpos() != 0)
851                 return;
852
853         // FIXME: we must handle start = end = 0
854
855         recordUndoSelection(cur, Undo::INSERT);
856
857         DocIterator it = cur.selectionBegin();
858         DocIterator et = cur.selectionEnd();
859         pit_type pit = it.pit();
860         for (; pit <= et.pit(); ++pit) {
861                 pos_type left  = (pit == it.pit() ? it.pos() : 0);
862                 pos_type right = (pit == et.pit() ? et.pos() : pars_[pit].size());
863
864                 // handle imaginary end-of-par character first
865                 if (right == pars_[pit].size() && !pars_[pit].isUnchanged(right)) {
866                         if (pars_[pit].isInserted(right)) {
867                                 pars_[pit].setChange(right, Change(Change::UNCHANGED));
868                         } else {
869                                 // if (pit + 1 < et.pit()) {
870                                 //      setCursorIntern(cur, pit + 1, 0);
871                                 //      backspacePos0(cur);
872                                 // }
873                         }
874                 }
875
876                 pars_[pit].acceptChanges(left, right);
877         }
878         finishUndo();
879         cur.clearSelection();
880         setCursorIntern(cur, it.pit(), it.pos());
881         cur.updateFlags(Update::Force);
882 }
883
884
885 void LyXText::rejectChange(LCursor & cur)
886 {
887         // FIXME: change tracking (MG)
888
889         BOOST_ASSERT(this == cur.text());
890
891         if (!cur.selection() && cur.lastpos() != 0)
892                 return;
893
894         // FIXME: we must handle start = end = 0
895
896         recordUndoSelection(cur, Undo::INSERT);
897
898         DocIterator it = cur.selectionBegin();
899         DocIterator et = cur.selectionEnd();
900         pit_type pit = it.pit();
901         for (; pit <= et.pit(); ++pit) {
902                 pos_type left  = (pit == it.pit() ? it.pos() : 0);
903                 pos_type right = (pit == et.pit() ? et.pos() : pars_[pit].size());
904
905                 // handle imaginary end-of-par character first
906                 if (right == pars_[pit].size() && !pars_[pit].isUnchanged(right)) {
907                         if (pars_[pit].isDeleted(right)) {
908                                 pars_[pit].setChange(right, Change(Change::UNCHANGED));
909                         } else {
910                                 // if (pit + 1 < et.pit()) {
911                                 //      setCursorIntern(cur, pit + 1, 0);
912                                 //      backspacePos0(cur);
913                                 // }
914                         }
915                 }
916                 
917                 pars_[pit].rejectChanges(left, right);
918         }
919         finishUndo();
920         cur.clearSelection();
921         setCursorIntern(cur, it.pit(), it.pos());
922         cur.updateFlags(Update::Force);
923 }
924
925
926 // Delete from cursor up to the end of the current or next word.
927 void LyXText::deleteWordForward(LCursor & cur)
928 {
929         BOOST_ASSERT(this == cur.text());
930         if (cur.lastpos() == 0)
931                 cursorRight(cur);
932         else {
933                 cur.resetAnchor();
934                 cur.selection() = true;
935                 cursorRightOneWord(cur);
936                 cur.setSelection();
937                 cutSelection(cur, true, false);
938         }
939 }
940
941
942 // Delete from cursor to start of current or prior word.
943 void LyXText::deleteWordBackward(LCursor & cur)
944 {
945         BOOST_ASSERT(this == cur.text());
946         if (cur.lastpos() == 0)
947                 cursorLeft(cur);
948         else {
949                 cur.resetAnchor();
950                 cur.selection() = true;
951                 cursorLeftOneWord(cur);
952                 cur.setSelection();
953                 cutSelection(cur, true, false);
954         }
955 }
956
957
958 // Kill to end of line.
959 void LyXText::deleteLineForward(LCursor & cur)
960 {
961         BOOST_ASSERT(this == cur.text());
962         if (cur.lastpos() == 0) {
963                 // Paragraph is empty, so we just go to the right
964                 cursorRight(cur);
965         } else {
966                 cur.resetAnchor();
967                 cur.selection() = true; // to avoid deletion
968                 cursorEnd(cur);
969                 cur.setSelection();
970                 // What is this test for ??? (JMarc)
971                 if (!cur.selection())
972                         deleteWordForward(cur);
973                 else
974                         cutSelection(cur, true, false);
975         }
976 }
977
978
979 void LyXText::changeCase(LCursor & cur, LyXText::TextCase action)
980 {
981         BOOST_ASSERT(this == cur.text());
982         CursorSlice from;
983         CursorSlice to;
984
985         if (cur.selection()) {
986                 from = cur.selBegin();
987                 to = cur.selEnd();
988         } else {
989                 from = cur.top();
990                 getWord(from, to, PARTIAL_WORD);
991                 cursorRightOneWord(cur);
992         }
993
994         recordUndoSelection(cur);
995
996         pos_type pos = from.pos();
997         int par = from.pit();
998
999         while (par != int(pars_.size()) && (pos != to.pos() || par != to.pit())) {
1000                 pit_type pit = par;
1001                 if (pos == pars_[pit].size()) {
1002                         ++par;
1003                         pos = 0;
1004                         continue;
1005                 }
1006                 char_type c = pars_[pit].getChar(pos);
1007                 if (c != Paragraph::META_INSET) {
1008                         switch (action) {
1009                         case text_lowercase:
1010                                 c = lowercase(c);
1011                                 break;
1012                         case text_capitalization:
1013                                 c = uppercase(c);
1014                                 action = text_lowercase;
1015                                 break;
1016                         case text_uppercase:
1017                                 c = uppercase(c);
1018                                 break;
1019                         }
1020                 }
1021
1022                 // FIXME: change tracking (MG)
1023                 // sorry but we are no longer allowed to set a single character directly
1024                 // we have to rewrite this method in terms of erase&insert operations
1025                 //pars_[pit].setChar(pos, c);
1026                 ++pos;
1027         }
1028 }
1029
1030
1031 bool LyXText::erase(LCursor & cur)
1032 {
1033         BOOST_ASSERT(this == cur.text());
1034         bool needsUpdate = false;
1035         Paragraph & par = cur.paragraph();
1036
1037         if (cur.pos() != cur.lastpos()) {
1038                 // this is the code for a normal delete, not pasting
1039                 // any paragraphs
1040                 recordUndo(cur, Undo::DELETE);
1041                 par.eraseChar(cur.pos(), cur.buffer().params().trackChanges);
1042                 if (par.isDeleted(cur.pos()))
1043                         cur.forwardPosNoDescend();
1044                 needsUpdate = true;
1045         } else {
1046                 if (cur.pit() == cur.lastpit())
1047                         return dissolveInset(cur);
1048
1049                 if (!par.isMergedOnEndOfParDeletion(cur.buffer().params().trackChanges)) {
1050                         par.setChange(cur.pos(), Change(Change::DELETED));
1051                         cur.forwardPos();
1052                         needsUpdate = true;
1053                 } else {
1054                         setCursorIntern(cur, cur.pit() + 1, 0);
1055                         needsUpdate = backspacePos0(cur);
1056                 }
1057         }
1058
1059         if (needsUpdate) {
1060                 // Make sure the cursor is correct. Is this really needed?
1061                 // No, not really... at least not here!
1062                 cur.text()->setCursor(cur.top(), cur.pit(), cur.pos());
1063         }
1064         
1065         return needsUpdate;
1066 }
1067
1068
1069 bool LyXText::backspacePos0(LCursor & cur)
1070 {
1071         BOOST_ASSERT(this == cur.text());
1072         if (cur.pit() == 0)
1073                 return false;
1074
1075         bool needsUpdate = false;
1076
1077         BufferParams const & bufparams = cur.buffer().params();
1078         LyXTextClass const & tclass = bufparams.getLyXTextClass();
1079         ParagraphList & plist = cur.text()->paragraphs();
1080         Paragraph const & par = cur.paragraph();
1081         LCursor prevcur = cur;
1082         --prevcur.pit();
1083         prevcur.pos() = prevcur.lastpos();
1084         Paragraph const & prevpar = prevcur.paragraph();
1085
1086         // is it an empty paragraph?
1087         if (cur.lastpos() == 0 
1088             || (cur.lastpos() == 1 && par.isSeparator(0))) {
1089                 recordUndo(cur, Undo::ATOMIC, prevcur.pit(), cur.pit());
1090                 plist.erase(boost::next(plist.begin(), cur.pit()));
1091                 needsUpdate = true;
1092         }
1093         // is previous par empty?
1094         else if (prevcur.lastpos() == 0 
1095                  || (prevcur.lastpos() == 1 && prevpar.isSeparator(0))) {
1096                 recordUndo(cur, Undo::ATOMIC, prevcur.pit(), cur.pit());
1097                 plist.erase(boost::next(plist.begin(), prevcur.pit()));
1098                 needsUpdate = true;
1099         }
1100         // Pasting is not allowed, if the paragraphs have different
1101         // layouts. I think it is a real bug of all other
1102         // word processors to allow it. It confuses the user.
1103         // Correction: Pasting is always allowed with standard-layout
1104         else if (par.layout() == prevpar.layout()
1105                  || par.layout() == tclass.defaultLayout()) {
1106                 recordUndo(cur, Undo::ATOMIC, prevcur.pit());
1107                 mergeParagraph(bufparams, plist, prevcur.pit());
1108                 needsUpdate = true;
1109         }
1110
1111         if (needsUpdate) {
1112                 updateLabels(cur.buffer());
1113                 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1114         }
1115
1116         return needsUpdate;
1117 }
1118
1119
1120 bool LyXText::backspace(LCursor & cur)
1121 {
1122         BOOST_ASSERT(this == cur.text());
1123         bool needsUpdate = false;
1124         if (cur.pos() == 0) {
1125                 if (cur.pit() == 0)
1126                         return dissolveInset(cur);
1127
1128                 Paragraph & prev_par = pars_[cur.pit() - 1];
1129
1130                 if (!prev_par.isMergedOnEndOfParDeletion(cur.buffer().params().trackChanges)) {
1131                         prev_par.setChange(prev_par.size(), Change(Change::DELETED));
1132                         setCursorIntern(cur, cur.pit() - 1, prev_par.size());
1133                         return true;
1134                 }
1135                 // The cursor is at the beginning of a paragraph, so
1136                 // the backspace will collapse two paragraphs into one.
1137                 needsUpdate = backspacePos0(cur);
1138
1139         } else {
1140                 // this is the code for a normal backspace, not pasting
1141                 // any paragraphs
1142                 recordUndo(cur, Undo::DELETE);
1143                 // We used to do cursorLeftIntern() here, but it is
1144                 // not a good idea since it triggers the auto-delete
1145                 // mechanism. So we do a cursorLeftIntern()-lite,
1146                 // without the dreaded mechanism. (JMarc)
1147                 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1148                                 false, cur.boundary());
1149                 cur.paragraph().eraseChar(cur.pos(), cur.buffer().params().trackChanges);
1150         }
1151
1152         if (cur.pos() == cur.lastpos())
1153                 setCurrentFont(cur);
1154
1155         // A singlePar update is not enough in this case.
1156 //              cur.updateFlags(Update::Force);
1157         setCursor(cur.top(), cur.pit(), cur.pos());
1158
1159         return needsUpdate;
1160 }
1161
1162
1163 bool LyXText::dissolveInset(LCursor & cur) {
1164         BOOST_ASSERT(this == cur.text());
1165
1166         if (isMainText(*cur.bv().buffer()) || cur.inset().nargs() != 1)
1167                 return false;
1168
1169         recordUndoInset(cur);
1170         cur.selHandle(false);
1171         // save position
1172         pos_type spos = cur.pos();
1173         pit_type spit = cur.pit();
1174         ParagraphList plist;
1175         if (cur.lastpit() != 0 || cur.lastpos() != 0)
1176                 plist = paragraphs();
1177         cur.popLeft();
1178         // store cursor offset
1179         if (spit == 0)
1180                 spos += cur.pos();
1181         spit += cur.pit();
1182         Buffer & b = cur.buffer();
1183         cur.paragraph().eraseChar(cur.pos(), b.params().trackChanges);
1184         if (!plist.empty()) {
1185                 // ERT paragraphs have the Language latex_language.
1186                 // This is invalid outside of ERT, so we need to
1187                 // change it to the buffer language.
1188                 ParagraphList::iterator it = plist.begin();
1189                 ParagraphList::iterator it_end = plist.end();
1190                 for (; it != it_end; it++) {
1191                         it->changeLanguage(b.params(), latex_language,
1192                                         b.getLanguage());
1193                 }
1194
1195                 pasteParagraphList(cur, plist, b.params().textclass,
1196                                    b.errorList("Paste"));
1197                 // restore position
1198                 cur.pit() = std::min(cur.lastpit(), spit);
1199                 cur.pos() = std::min(cur.lastpos(), spos);
1200         }
1201         cur.clearSelection();
1202         cur.resetAnchor();
1203         return true;
1204 }
1205
1206
1207 // only used for inset right now. should also be used for main text
1208 void LyXText::draw(PainterInfo & pi, int x, int y) const
1209 {
1210         paintTextInset(*this, pi, x, y);
1211 }
1212
1213
1214 // only used for inset right now. should also be used for main text
1215 void LyXText::drawSelection(PainterInfo & pi, int x, int) const
1216 {
1217         LCursor & cur = pi.base.bv->cursor();
1218         if (!cur.selection())
1219                 return;
1220         if (!ptr_cmp(cur.text(), this))
1221                 return;
1222
1223         if (lyxerr.debugging(Debug::DEBUG)) {
1224                 lyxerr[Debug::DEBUG]
1225                         << BOOST_CURRENT_FUNCTION
1226                         << "draw selection at " << x
1227                         << endl;
1228         }
1229
1230         DocIterator beg = cur.selectionBegin();
1231         DocIterator end = cur.selectionEnd();
1232
1233         BufferView & bv = *pi.base.bv;
1234         Buffer const & buffer = *bv.buffer();
1235
1236         // the selection doesn't touch the visible screen
1237         if (bv_funcs::status(&bv, beg) == bv_funcs::CUR_BELOW
1238             || bv_funcs::status(&bv, end) == bv_funcs::CUR_ABOVE)
1239                 return;
1240
1241         Paragraph const & par1 = pars_[beg.pit()];
1242         Paragraph const & par2 = pars_[end.pit()];
1243         TextMetrics const & tm = bv.textMetrics(this);
1244         ParagraphMetrics const & pm1 = tm.parMetrics(beg.pit());
1245         ParagraphMetrics const & pm2 = tm.parMetrics(end.pit());
1246
1247         bool const above = (bv_funcs::status(&bv, beg)
1248                             == bv_funcs::CUR_ABOVE);
1249         bool const below = (bv_funcs::status(&bv, end)
1250                             == bv_funcs::CUR_BELOW);
1251         int y1,y2,x1,x2;
1252         if (above) {
1253                 y1 = 0;
1254                 y2 = 0;
1255                 x1 = 0;
1256                 x2 = tm.width();
1257         } else {
1258                 Row const & row1 = pm1.getRow(beg.pos(), beg.boundary());
1259                 y1 = bv_funcs::getPos(bv, beg, beg.boundary()).y_ - row1.ascent();
1260                 y2 = y1 + row1.height();
1261                 int const startx = cursorX(bv, beg.top(), beg.boundary());
1262                 if (!isRTL(buffer, par1)) {
1263                         x1 = startx;
1264                         x2 = 0 + tm.width();
1265                 }
1266                 else {
1267                         x1 = 0;
1268                         x2 = startx;
1269                 }
1270         }
1271
1272         int Y1,Y2,X1,X2;
1273         if (below) {
1274                 Y1 = bv.workHeight();
1275                 Y2 = bv.workHeight();
1276                 X1 = 0;
1277                 X2 = tm.width();
1278         } else {
1279                 Row const & row2 = pm2.getRow(end.pos(), end.boundary());
1280                 Y1 = bv_funcs::getPos(bv, end, end.boundary()).y_ - row2.ascent();
1281                 Y2 = Y1 + row2.height();
1282                 int const endx = cursorX(bv, end.top(), end.boundary());
1283                 if (!isRTL(buffer, par2)) {
1284                         X1 = 0;
1285                         X2 = endx;
1286                 }
1287                 else {
1288                         X1 = endx;
1289                         X2 = 0 + tm.width();
1290                 }
1291         }
1292
1293         if (!above && !below && &pm1.getRow(beg.pos(), beg.boundary())
1294             == &pm2.getRow(end.pos(), end.boundary()))
1295         {
1296                 // paint only one rectangle
1297                 int const b( !isRTL(*bv.buffer(), par1) ? x + x1 : x + X1 );
1298                 int const w( !isRTL(*bv.buffer(), par1) ? X2 - x1 : x2 - X1 );
1299                 pi.pain.fillRectangle(b, y1, w, y2 - y1, LColor::selection);
1300                 return;
1301         }
1302
1303         if (lyxerr.debugging(Debug::DEBUG)) {
1304                 lyxerr[Debug::DEBUG] << " y1: " << y1 << " y2: " << y2
1305                            << "X1:" << X1 << " x2: " << X2 << " wid: " << tm.width()
1306                         << endl;
1307         }
1308
1309         // paint upper rectangle
1310         pi.pain.fillRectangle(x + x1, y1, x2 - x1, y2 - y1,
1311                                       LColor::selection);
1312         // paint bottom rectangle
1313         pi.pain.fillRectangle(x + X1, Y1, X2 - X1, Y2 - Y1,
1314                                       LColor::selection);
1315         // paint center rectangle
1316         pi.pain.fillRectangle(x, y2, tm.width(),
1317                               Y1 - y2, LColor::selection);
1318 }
1319
1320
1321 bool LyXText::isLastRow(pit_type pit, Row const & row) const
1322 {
1323         return row.endpos() >= pars_[pit].size()
1324                 && pit + 1 == pit_type(paragraphs().size());
1325 }
1326
1327
1328 bool LyXText::isFirstRow(pit_type pit, Row const & row) const
1329 {
1330         return row.pos() == 0 && pit == 0;
1331 }
1332
1333
1334 void LyXText::getWord(CursorSlice & from, CursorSlice & to,
1335         word_location const loc)
1336 {
1337         Paragraph const & from_par = pars_[from.pit()];
1338         switch (loc) {
1339         case WHOLE_WORD_STRICT:
1340                 if (from.pos() == 0 || from.pos() == from_par.size()
1341                     || !from_par.isLetter(from.pos())
1342                     || !from_par.isLetter(from.pos() - 1)) {
1343                         to = from;
1344                         return;
1345                 }
1346                 // no break here, we go to the next
1347
1348         case WHOLE_WORD:
1349                 // If we are already at the beginning of a word, do nothing
1350                 if (!from.pos() || !from_par.isLetter(from.pos() - 1))
1351                         break;
1352                 // no break here, we go to the next
1353
1354         case PREVIOUS_WORD:
1355                 // always move the cursor to the beginning of previous word
1356                 while (from.pos() && from_par.isLetter(from.pos() - 1))
1357                         --from.pos();
1358                 break;
1359         case NEXT_WORD:
1360                 lyxerr << "LyXText::getWord: NEXT_WORD not implemented yet"
1361                        << endl;
1362                 break;
1363         case PARTIAL_WORD:
1364                 // no need to move the 'from' cursor
1365                 break;
1366         }
1367         to = from;
1368         Paragraph & to_par = pars_[to.pit()];
1369         while (to.pos() < to_par.size() && to_par.isLetter(to.pos()))
1370                 ++to.pos();
1371 }
1372
1373
1374 void LyXText::write(Buffer const & buf, std::ostream & os) const
1375 {
1376         ParagraphList::const_iterator pit = paragraphs().begin();
1377         ParagraphList::const_iterator end = paragraphs().end();
1378         depth_type dth = 0;
1379         for (; pit != end; ++pit)
1380                 pit->write(buf, os, buf.params(), dth);
1381 }
1382
1383
1384 bool LyXText::read(Buffer const & buf, LyXLex & lex, ErrorList & errorList)
1385 {
1386         depth_type depth = 0;
1387
1388         while (lex.isOK()) {
1389                 lex.nextToken();
1390                 string const token = lex.getString();
1391
1392                 if (token.empty())
1393                         continue;
1394
1395                 if (token == "\\end_inset")
1396                         break;
1397
1398                 if (token == "\\end_body")
1399                         continue;
1400
1401                 if (token == "\\begin_body")
1402                         continue;
1403
1404                 if (token == "\\end_document")
1405                         return false;
1406
1407                 if (token == "\\begin_layout") {
1408                         lex.pushToken(token);
1409
1410                         Paragraph par;
1411                         par.params().depth(depth);
1412                         par.setFont(0, LyXFont(LyXFont::ALL_INHERIT, buf.params().language));
1413                         pars_.push_back(par);
1414
1415                         // FIXME: goddamn InsetTabular makes us pass a Buffer
1416                         // not BufferParams
1417                         lyx::readParagraph(buf, pars_.back(), lex, errorList);
1418
1419                 } else if (token == "\\begin_deeper") {
1420                         ++depth;
1421                 } else if (token == "\\end_deeper") {
1422                         if (!depth) {
1423                                 lex.printError("\\end_deeper: " "depth is already null");
1424                         } else {
1425                                 --depth;
1426                         }
1427                 } else {
1428                         lyxerr << "Handling unknown body token: `"
1429                                << token << '\'' << endl;
1430                 }
1431         }
1432         return true;
1433 }
1434
1435 int LyXText::cursorX(BufferView const & bv, CursorSlice const & sl,
1436                 bool boundary) const
1437 {
1438         TextMetrics const & tm = bv.textMetrics(sl.text());
1439         pit_type const pit = sl.pit();
1440         Paragraph const & par = pars_[pit];
1441         ParagraphMetrics const & pm = tm.parMetrics(pit);
1442         if (pm.rows().empty())
1443                 return 0;
1444
1445         pos_type ppos = sl.pos();
1446         // Correct position in front of big insets
1447         bool const boundary_correction = ppos != 0 && boundary;
1448         if (boundary_correction)
1449                 --ppos;
1450
1451         Row const & row = pm.getRow(sl.pos(), boundary);
1452
1453         pos_type cursor_vpos = 0;
1454
1455         Buffer const & buffer = *bv.buffer();
1456         RowMetrics const m = tm.computeRowMetrics(pit, row);
1457         double x = m.x;
1458
1459         pos_type const row_pos  = row.pos();
1460         pos_type const end      = row.endpos();
1461
1462         if (end <= row_pos)
1463                 cursor_vpos = row_pos;
1464         else if (ppos >= end)
1465                 cursor_vpos = isRTL(buffer, par) ? row_pos : end;
1466         else if (ppos > row_pos && ppos >= end)
1467                 // Place cursor after char at (logical) position pos - 1
1468                 cursor_vpos = (bidi.level(ppos - 1) % 2 == 0)
1469                         ? bidi.log2vis(ppos - 1) + 1 : bidi.log2vis(ppos - 1);
1470         else
1471                 // Place cursor before char at (logical) position ppos
1472                 cursor_vpos = (bidi.level(ppos) % 2 == 0)
1473                         ? bidi.log2vis(ppos) : bidi.log2vis(ppos) + 1;
1474
1475         pos_type body_pos = par.beginOfBody();
1476         if (body_pos > 0 &&
1477             (body_pos > end || !par.isLineSeparator(body_pos - 1)))
1478                 body_pos = 0;
1479
1480         // Use font span to speed things up, see below
1481         FontSpan font_span;
1482         LyXFont font;
1483         FontMetrics const & labelfm = theFontMetrics(
1484                 getLabelFont(buffer, par));
1485
1486         for (pos_type vpos = row_pos; vpos < cursor_vpos; ++vpos) {
1487                 pos_type pos = bidi.vis2log(vpos);
1488                 if (body_pos > 0 && pos == body_pos - 1) {
1489                         // FIXME UNICODE
1490                         docstring const lsep = from_utf8(par.layout()->labelsep);
1491                         x += m.label_hfill + labelfm.width(lsep);
1492                         if (par.isLineSeparator(body_pos - 1))
1493                                 x -= singleWidth(buffer, par, body_pos - 1);
1494                 }
1495
1496                 // Use font span to speed things up, see above
1497                 if (pos < font_span.first || pos > font_span.last) {
1498                         font_span = par.fontSpan(pos);
1499                         font = getFont(buffer, par, pos);
1500                 }
1501
1502                 x += singleWidth(par, pos, par.getChar(pos), font);
1503
1504                 if (par.hfillExpansion(row, pos))
1505                         x += (pos >= body_pos) ? m.hfill : m.label_hfill;
1506                 else if (par.isSeparator(pos) && pos >= body_pos)
1507                         x += m.separator;
1508         }
1509
1510         // see correction above
1511         if (boundary_correction)
1512                 if (getFont(buffer, par, ppos).isVisibleRightToLeft())
1513                         x -= singleWidth(buffer, par, ppos);
1514                 else
1515                         x += singleWidth(buffer, par, ppos);
1516
1517         // Make sure inside an inset we always count from the left
1518         // edge (bidi!) -- MV
1519         if (sl.pos() < par.size()) {
1520                 font = getFont(buffer, par, sl.pos());
1521                 if (!boundary && font.isVisibleRightToLeft()
1522                   && par.isInset(sl.pos()))
1523                         x -= par.getInset(sl.pos())->width();
1524         }
1525         return int(x);
1526 }
1527
1528
1529 int LyXText::cursorY(BufferView const & bv, CursorSlice const & sl, bool boundary) const
1530 {
1531         //lyxerr << "LyXText::cursorY: boundary: " << boundary << std::endl;
1532         ParagraphMetrics const & pm = bv.parMetrics(this, sl.pit());
1533         if (pm.rows().empty())
1534                 return 0;
1535
1536         int h = 0;
1537         h -= bv.parMetrics(this, 0).rows()[0].ascent();
1538         for (pit_type pit = 0; pit < sl.pit(); ++pit) {
1539                 h += bv.parMetrics(this, pit).height();
1540         }
1541         int pos = sl.pos();
1542         if (pos && boundary)
1543                 --pos;
1544         size_t const rend = pm.pos2row(pos);
1545         for (size_t rit = 0; rit != rend; ++rit)
1546                 h += pm.rows()[rit].height();
1547         h += pm.rows()[rend].ascent();
1548         return h;
1549 }
1550
1551
1552 // Returns the current font and depth as a message.
1553 docstring LyXText::currentState(LCursor & cur)
1554 {
1555         BOOST_ASSERT(this == cur.text());
1556         Buffer & buf = cur.buffer();
1557         Paragraph const & par = cur.paragraph();
1558         odocstringstream os;
1559
1560         if (buf.params().trackChanges)
1561                 os << "[C] ";
1562
1563         Change change = par.lookupChange(cur.pos());
1564
1565         if (change.type != Change::UNCHANGED) {
1566                 Author const & a = buf.params().authors().get(change.author);
1567                 os << _("Change: ") << a.name();
1568                 if (!a.email().empty())
1569                         os << " (" << a.email() << ")";
1570                 // FIXME ctime is english, we should translate that
1571                 os << _(" at ") << ctime(&change.changetime);
1572                 os << " : ";
1573         }
1574
1575         // I think we should only show changes from the default
1576         // font. (Asger)
1577         // No, from the document font (MV)
1578         LyXFont font = real_current_font;
1579         font.reduce(buf.params().getFont());
1580
1581         os << bformat(_("Font: %1$s"), font.stateText(&buf.params()));
1582
1583         // The paragraph depth
1584         int depth = cur.paragraph().getDepth();
1585         if (depth > 0)
1586                 os << bformat(_(", Depth: %1$d"), depth);
1587
1588         // The paragraph spacing, but only if different from
1589         // buffer spacing.
1590         Spacing const & spacing = par.params().spacing();
1591         if (!spacing.isDefault()) {
1592                 os << _(", Spacing: ");
1593                 switch (spacing.getSpace()) {
1594                 case Spacing::Single:
1595                         os << _("Single");
1596                         break;
1597                 case Spacing::Onehalf:
1598                         os << _("OneHalf");
1599                         break;
1600                 case Spacing::Double:
1601                         os << _("Double");
1602                         break;
1603                 case Spacing::Other:
1604                         os << _("Other (") << from_ascii(spacing.getValueAsString()) << ')';
1605                         break;
1606                 case Spacing::Default:
1607                         // should never happen, do nothing
1608                         break;
1609                 }
1610         }
1611
1612 #ifdef DEVEL_VERSION
1613         os << _(", Inset: ") << &cur.inset();
1614         os << _(", Paragraph: ") << cur.pit();
1615         os << _(", Id: ") << par.id();
1616         os << _(", Position: ") << cur.pos();
1617         os << _(", Boundary: ") << cur.boundary();
1618 //      Row & row = cur.textRow();
1619 //      os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
1620 #endif
1621         return os.str();
1622 }
1623
1624
1625 docstring LyXText::getPossibleLabel(LCursor & cur) const
1626 {
1627         pit_type pit = cur.pit();
1628
1629         LyXLayout_ptr layout = pars_[pit].layout();
1630
1631         if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
1632                 LyXLayout_ptr const & layout2 = pars_[pit - 1].layout();
1633                 if (layout2->latextype != LATEX_PARAGRAPH) {
1634                         --pit;
1635                         layout = layout2;
1636                 }
1637         }
1638
1639         docstring name = from_ascii(layout->latexname());
1640
1641         // for captions, we want the abbreviation of the float type
1642         if (layout->labeltype == LABEL_SENSITIVE) {
1643                 // Search for the first float or wrap inset in the iterator
1644                 for (int i = cur.depth(); --i >= 0; ) {
1645                         InsetBase * const in = &cur[i].inset();
1646                         if (in->lyxCode() == InsetBase::FLOAT_CODE
1647                             || in->lyxCode() == InsetBase::WRAP_CODE) {
1648                                 name = in->getInsetName();
1649                                 break;
1650                         }
1651                 }
1652         }
1653
1654         docstring text = name.substr(0, 3);
1655         if (name == "theorem")
1656                 text = from_ascii("thm"); // Create a correct prefix for prettyref
1657
1658         text += ':';
1659         if (layout->latextype == LATEX_PARAGRAPH || lyxrc.label_init_length < 0)
1660                 text.erase();
1661
1662         docstring par_text = pars_[pit].asString(cur.buffer(), false);
1663         for (int i = 0; i < lyxrc.label_init_length; ++i) {
1664                 if (par_text.empty())
1665                         break;
1666                 docstring head;
1667                 par_text = split(par_text, head, ' ');
1668                 // Is it legal to use spaces in labels ?
1669                 if (i > 0)
1670                         text += '-';
1671                 text += head;
1672         }
1673
1674         return text;
1675 }
1676
1677
1678 void LyXText::setCursorFromCoordinates(LCursor & cur, int const x, int const y)
1679 {
1680         BOOST_ASSERT(this == cur.text());
1681         pit_type pit = getPitNearY(cur.bv(), y);
1682
1683         TextMetrics const & tm = cur.bv().textMetrics(this);
1684         ParagraphMetrics const & pm = tm.parMetrics(pit);
1685
1686         int yy = cur.bv().coordCache().get(this, pit).y_ - pm.ascent();
1687         lyxerr[Debug::DEBUG]
1688                 << BOOST_CURRENT_FUNCTION
1689                 << ": x: " << x
1690                 << " y: " << y
1691                 << " pit: " << pit
1692                 << " yy: " << yy << endl;
1693
1694         int r = 0;
1695         BOOST_ASSERT(pm.rows().size());
1696         for (; r < int(pm.rows().size()) - 1; ++r) {
1697                 Row const & row = pm.rows()[r];
1698                 if (int(yy + row.height()) > y)
1699                         break;
1700                 yy += row.height();
1701         }
1702
1703         Row const & row = pm.rows()[r];
1704
1705         lyxerr[Debug::DEBUG]
1706                 << BOOST_CURRENT_FUNCTION
1707                 << ": row " << r
1708                 << " from pos: " << row.pos()
1709                 << endl;
1710
1711         bool bound = false;
1712         int xx = x;
1713         pos_type const pos = row.pos() 
1714                 + tm.getColumnNearX(pit, row, xx, bound);
1715
1716         lyxerr[Debug::DEBUG]
1717                 << BOOST_CURRENT_FUNCTION
1718                 << ": setting cursor pit: " << pit
1719                 << " pos: " << pos
1720                 << endl;
1721
1722         setCursor(cur, pit, pos, true, bound);
1723 }
1724
1725
1726 void LyXText::charsTranspose(LCursor & cur)
1727 {
1728         BOOST_ASSERT(this == cur.text());
1729
1730         pos_type pos = cur.pos();
1731
1732         // If cursor is at beginning or end of paragraph, do nothing.
1733         if (pos == cur.lastpos() || pos == 0)
1734                 return;
1735
1736         Paragraph & par = cur.paragraph();
1737
1738         // Get the positions of the characters to be transposed. 
1739         pos_type pos1 = pos - 1;
1740         pos_type pos2 = pos;
1741
1742         // In change tracking mode, ignore deleted characters.
1743         while (pos2 < cur.lastpos() && par.isDeleted(pos2))
1744                 ++pos2;
1745         if (pos2 == cur.lastpos())
1746                 return;
1747
1748         while (pos1 >= 0 && par.isDeleted(pos1))
1749                 --pos1;
1750         if (pos1 < 0)
1751                 return;
1752
1753         // Don't do anything if one of the "characters" is not regular text.
1754         if (par.isInset(pos1) || par.isInset(pos2))
1755                 return;
1756
1757         // Store the characters to be transposed (including font information).
1758         char_type char1 = par.getChar(pos1);
1759         LyXFont const font1 =
1760                 par.getFontSettings(cur.buffer().params(), pos1);
1761         
1762         char_type char2 = par.getChar(pos2);
1763         LyXFont const font2 =
1764                 par.getFontSettings(cur.buffer().params(), pos2);
1765
1766         // And finally, we are ready to perform the transposition.
1767         // Track the changes if Change Tracking is enabled.
1768         bool const trackChanges = cur.buffer().params().trackChanges;
1769
1770         recordUndo(cur);
1771
1772         par.eraseChar(pos2, trackChanges);
1773         par.eraseChar(pos1, trackChanges);
1774         par.insertChar(pos1, char2, font2, trackChanges);
1775         par.insertChar(pos2, char1, font1, trackChanges);
1776
1777         // After the transposition, move cursor to after the transposition.
1778         setCursor(cur, cur.pit(), pos2);
1779         cur.forwardPos();
1780 }
1781
1782
1783 } // namespace lyx