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