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