]> git.lyx.org Git - lyx.git/blob - src/Text.cpp
* disable some invalid insets in description items (covers bug 5937).
[lyx.git] / src / Text.cpp
1 /**
2  * \file src/Text.cpp
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 Dov Feldstern
9  * \author Jean-Marc Lasgouttes
10  * \author John Levon
11  * \author André Pönitz
12  * \author Stefan Schimanski
13  * \author Dekel Tsur
14  * \author Jürgen Vigna
15  *
16  * Full author contact details are available in file CREDITS.
17  */
18
19 #include <config.h>
20
21 #include "Text.h"
22
23 #include "Author.h"
24 #include "Buffer.h"
25 #include "buffer_funcs.h"
26 #include "BufferParams.h"
27 #include "BufferView.h"
28 #include "Changes.h"
29 #include "CompletionList.h"
30 #include "Cursor.h"
31 #include "CutAndPaste.h"
32 #include "DispatchResult.h"
33 #include "Encoding.h"
34 #include "ErrorList.h"
35 #include "FuncRequest.h"
36 #include "factory.h"
37 #include "Language.h"
38 #include "Length.h"
39 #include "Lexer.h"
40 #include "lyxfind.h"
41 #include "LyXRC.h"
42 #include "Paragraph.h"
43 #include "paragraph_funcs.h"
44 #include "ParagraphParameters.h"
45 #include "ParIterator.h"
46 #include "TextClass.h"
47 #include "TextMetrics.h"
48 #include "VSpace.h"
49 #include "WordLangTuple.h"
50 #include "WordList.h"
51
52 #include "insets/InsetText.h"
53 #include "insets/InsetBibitem.h"
54 #include "insets/InsetCaption.h"
55 #include "insets/InsetLine.h"
56 #include "insets/InsetNewline.h"
57 #include "insets/InsetNewpage.h"
58 #include "insets/InsetOptArg.h"
59 #include "insets/InsetSpace.h"
60 #include "insets/InsetSpecialChar.h"
61 #include "insets/InsetTabular.h"
62
63 #include "support/convert.h"
64 #include "support/debug.h"
65 #include "support/docstream.h"
66 #include "support/gettext.h"
67 #include "support/lassert.h"
68 #include "support/lstrings.h"
69 #include "support/textutils.h"
70
71 #include <boost/next_prior.hpp>
72
73 #include <sstream>
74
75 using namespace std;
76 using namespace lyx::support;
77
78 namespace lyx {
79
80 using cap::cutSelection;
81 using cap::pasteParagraphList;
82
83 namespace {
84
85 void readParToken(Buffer const & buf, Paragraph & par, Lexer & lex,
86         string const & token, Font & font, Change & change, ErrorList & errorList)
87 {
88         BufferParams const & bp = buf.params();
89
90         if (token[0] != '\\') {
91                 docstring dstr = lex.getDocString();
92                 par.appendString(dstr, font, change);
93
94         } else if (token == "\\begin_layout") {
95                 lex.eatLine();
96                 docstring layoutname = lex.getDocString();
97
98                 font = Font(inherit_font, bp.language);
99                 change = Change(Change::UNCHANGED);
100
101                 DocumentClass const & tclass = bp.documentClass();
102
103                 if (layoutname.empty())
104                         layoutname = tclass.defaultLayoutName();
105
106                 if (par.forcePlainLayout()) {
107                         // in this case only the empty layout is allowed
108                         layoutname = tclass.plainLayoutName();
109                 } else if (par.usePlainLayout()) {
110                         // in this case, default layout maps to empty layout 
111                         if (layoutname == tclass.defaultLayoutName())
112                                 layoutname = tclass.plainLayoutName();
113                 } else { 
114                         // otherwise, the empty layout maps to the default
115                         if (layoutname == tclass.plainLayoutName())
116                                 layoutname = tclass.defaultLayoutName();
117                 }
118
119                 // When we apply an unknown layout to a document, we add this layout to the textclass
120                 // of this document. For example, when you apply class article to a beamer document,
121                 // all unknown layouts such as frame will be added to document class article so that
122                 // these layouts can keep their original names.
123                 tclass.addLayoutIfNeeded(layoutname);
124
125                 par.setLayout(bp.documentClass()[layoutname]);
126
127                 // Test whether the layout is obsolete.
128                 Layout const & layout = par.layout();
129                 if (!layout.obsoleted_by().empty())
130                         par.setLayout(bp.documentClass()[layout.obsoleted_by()]);
131
132                 par.params().read(lex);
133
134         } else if (token == "\\end_layout") {
135                 LYXERR0("Solitary \\end_layout in line " << lex.lineNumber() << "\n"
136                        << "Missing \\begin_layout ?");
137         } else if (token == "\\end_inset") {
138                 LYXERR0("Solitary \\end_inset in line " << lex.lineNumber() << "\n"
139                        << "Missing \\begin_inset ?");
140         } else if (token == "\\begin_inset") {
141                 Inset * inset = readInset(lex, buf);
142                 if (inset)
143                         par.insertInset(par.size(), inset, font, change);
144                 else {
145                         lex.eatLine();
146                         docstring line = lex.getDocString();
147                         errorList.push_back(ErrorItem(_("Unknown Inset"), line,
148                                             par.id(), 0, par.size()));
149                 }
150         } else if (token == "\\family") {
151                 lex.next();
152                 setLyXFamily(lex.getString(), font.fontInfo());
153         } else if (token == "\\series") {
154                 lex.next();
155                 setLyXSeries(lex.getString(), font.fontInfo());
156         } else if (token == "\\shape") {
157                 lex.next();
158                 setLyXShape(lex.getString(), font.fontInfo());
159         } else if (token == "\\size") {
160                 lex.next();
161                 setLyXSize(lex.getString(), font.fontInfo());
162         } else if (token == "\\lang") {
163                 lex.next();
164                 string const tok = lex.getString();
165                 Language const * lang = languages.getLanguage(tok);
166                 if (lang) {
167                         font.setLanguage(lang);
168                 } else {
169                         font.setLanguage(bp.language);
170                         lex.printError("Unknown language `$$Token'");
171                 }
172         } else if (token == "\\numeric") {
173                 lex.next();
174                 font.fontInfo().setNumber(font.setLyXMisc(lex.getString()));
175         } else if (token == "\\emph") {
176                 lex.next();
177                 font.fontInfo().setEmph(font.setLyXMisc(lex.getString()));
178         } else if (token == "\\bar") {
179                 lex.next();
180                 string const tok = lex.getString();
181
182                 if (tok == "under")
183                         font.fontInfo().setUnderbar(FONT_ON);
184                 else if (tok == "no")
185                         font.fontInfo().setUnderbar(FONT_OFF);
186                 else if (tok == "default")
187                         font.fontInfo().setUnderbar(FONT_INHERIT);
188                 else
189                         lex.printError("Unknown bar font flag "
190                                        "`$$Token'");
191         } else if (token == "\\strikeout") {
192                 lex.next();
193                 font.fontInfo().setStrikeout(font.setLyXMisc(lex.getString()));
194         } else if (token == "\\uuline") {
195                 lex.next();
196                 font.fontInfo().setUuline(font.setLyXMisc(lex.getString()));
197         } else if (token == "\\uwave") {
198                 lex.next();
199                 font.fontInfo().setUwave(font.setLyXMisc(lex.getString()));
200         } else if (token == "\\noun") {
201                 lex.next();
202                 font.fontInfo().setNoun(font.setLyXMisc(lex.getString()));
203         } else if (token == "\\color") {
204                 lex.next();
205                 setLyXColor(lex.getString(), font.fontInfo());
206         } else if (token == "\\SpecialChar") {
207                         auto_ptr<Inset> inset;
208                         inset.reset(new InsetSpecialChar);
209                         inset->read(lex);
210                         par.insertInset(par.size(), inset.release(),
211                                         font, change);
212         } else if (token == "\\backslash") {
213                 par.appendChar('\\', font, change);
214         } else if (token == "\\LyXTable") {
215                 auto_ptr<Inset> inset(new InsetTabular(const_cast<Buffer &>(buf)));
216                 inset->read(lex);
217                 par.insertInset(par.size(), inset.release(), font, change);
218         } else if (token == "\\lyxline") {
219                 par.insertInset(par.size(), new InsetLine, font, change);
220         } else if (token == "\\change_unchanged") {
221                 change = Change(Change::UNCHANGED);
222         } else if (token == "\\change_inserted") {
223                 lex.eatLine();
224                 istringstream is(lex.getString());
225                 unsigned int aid;
226                 time_t ct;
227                 is >> aid >> ct;
228                 if (aid >= bp.author_map.size()) {
229                         errorList.push_back(ErrorItem(_("Change tracking error"),
230                                             bformat(_("Unknown author index for insertion: %1$d\n"), aid),
231                                             par.id(), 0, par.size()));
232                         change = Change(Change::UNCHANGED);
233                 } else
234                         change = Change(Change::INSERTED, bp.author_map[aid], ct);
235         } else if (token == "\\change_deleted") {
236                 lex.eatLine();
237                 istringstream is(lex.getString());
238                 unsigned int aid;
239                 time_t ct;
240                 is >> aid >> ct;
241                 if (aid >= bp.author_map.size()) {
242                         errorList.push_back(ErrorItem(_("Change tracking error"),
243                                             bformat(_("Unknown author index for deletion: %1$d\n"), aid),
244                                             par.id(), 0, par.size()));
245                         change = Change(Change::UNCHANGED);
246                 } else
247                         change = Change(Change::DELETED, bp.author_map[aid], ct);
248         } else {
249                 lex.eatLine();
250                 errorList.push_back(ErrorItem(_("Unknown token"),
251                         bformat(_("Unknown token: %1$s %2$s\n"), from_utf8(token),
252                         lex.getDocString()),
253                         par.id(), 0, par.size()));
254         }
255 }
256
257
258 void readParagraph(Buffer const & buf, Paragraph & par, Lexer & lex,
259         ErrorList & errorList)
260 {
261         lex.nextToken();
262         string token = lex.getString();
263         Font font;
264         Change change(Change::UNCHANGED);
265
266         while (lex.isOK()) {
267                 readParToken(buf, par, lex, token, font, change, errorList);
268
269                 lex.nextToken();
270                 token = lex.getString();
271
272                 if (token.empty())
273                         continue;
274
275                 if (token == "\\end_layout") {
276                         //Ok, paragraph finished
277                         break;
278                 }
279
280                 LYXERR(Debug::PARSER, "Handling paragraph token: `" << token << '\'');
281                 if (token == "\\begin_layout" || token == "\\end_document"
282                     || token == "\\end_inset" || token == "\\begin_deeper"
283                     || token == "\\end_deeper") {
284                         lex.pushToken(token);
285                         lyxerr << "Paragraph ended in line "
286                                << lex.lineNumber() << "\n"
287                                << "Missing \\end_layout.\n";
288                         break;
289                 }
290         }
291         // Final change goes to paragraph break:
292         par.setChange(par.size(), change);
293
294         // Initialize begin_of_body_ on load; redoParagraph maintains
295         par.setBeginOfBody();
296 }
297
298
299 } // namespace anon
300
301 class TextCompletionList : public CompletionList
302 {
303 public:
304         ///
305         TextCompletionList(Cursor const & cur)
306                 : buffer_(cur.buffer()), pos_(0)
307         {}
308         ///
309         virtual ~TextCompletionList() {}
310         
311         ///
312         virtual bool sorted() const { return true; }
313         ///
314         virtual size_t size() const
315         {
316                 return theWordList().size();
317         }
318         ///
319         virtual docstring const & data(size_t idx) const
320         {
321                 return theWordList().word(idx);
322         }
323         
324 private:
325         ///
326         Buffer const * buffer_;
327         ///
328         size_t pos_;
329 };
330
331
332 bool Text::empty() const
333 {
334         return pars_.empty() || (pars_.size() == 1 && pars_[0].empty()
335                 // FIXME: Should we consider the labeled type as empty too? 
336                 && pars_[0].layout().labeltype == LABEL_NO_LABEL);
337 }
338
339
340 double Text::spacing(Buffer const & buffer, Paragraph const & par) const
341 {
342         if (par.params().spacing().isDefault())
343                 return buffer.params().spacing().getValue();
344         return par.params().spacing().getValue();
345 }
346
347
348 void Text::breakParagraph(Cursor & cur, bool inverse_logic)
349 {
350         LASSERT(this == cur.text(), /**/);
351
352         Paragraph & cpar = cur.paragraph();
353         pit_type cpit = cur.pit();
354
355         DocumentClass const & tclass = cur.buffer()->params().documentClass();
356         Layout const & layout = cpar.layout();
357
358         // this is only allowed, if the current paragraph is not empty
359         // or caption and if it has not the keepempty flag active
360         if (cur.lastpos() == 0 && !cpar.allowEmpty() &&
361             layout.labeltype != LABEL_SENSITIVE)
362                 return;
363
364         // a layout change may affect also the following paragraph
365         recUndo(cur, cur.pit(), undoSpan(cur.pit()) - 1);
366
367         // Always break behind a space
368         // It is better to erase the space (Dekel)
369         if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
370                 cpar.eraseChar(cur.pos(), cur.buffer()->params().trackChanges);
371
372         // What should the layout for the new paragraph be?
373         bool keep_layout = inverse_logic ? 
374                 !layout.isEnvironment() 
375                 : layout.isEnvironment();
376
377         // We need to remember this before we break the paragraph, because
378         // that invalidates the layout variable
379         bool sensitive = layout.labeltype == LABEL_SENSITIVE;
380
381         // we need to set this before we insert the paragraph.
382         bool const isempty = cpar.allowEmpty() && cpar.empty();
383
384         lyx::breakParagraph(cur.buffer()->params(), paragraphs(), cpit,
385                          cur.pos(), keep_layout);
386
387         // After this, neither paragraph contains any rows!
388
389         cpit = cur.pit();
390         pit_type next_par = cpit + 1;
391
392         // well this is the caption hack since one caption is really enough
393         if (sensitive) {
394                 if (cur.pos() == 0)
395                         // set to standard-layout
396                 //FIXME Check if this should be plainLayout() in some cases
397                         pars_[cpit].applyLayout(tclass.defaultLayout());
398                 else
399                         // set to standard-layout
400                         //FIXME Check if this should be plainLayout() in some cases
401                         pars_[next_par].applyLayout(tclass.defaultLayout());
402         }
403
404         while (!pars_[next_par].empty() && pars_[next_par].isNewline(0)) {
405                 if (!pars_[next_par].eraseChar(0, cur.buffer()->params().trackChanges))
406                         break; // the character couldn't be deleted physically due to change tracking
407         }
408
409         cur.buffer()->updateLabels();
410
411         // A singlePar update is not enough in this case.
412         cur.updateFlags(Update::Force);
413
414         // This check is necessary. Otherwise the new empty paragraph will
415         // be deleted automatically. And it is more friendly for the user!
416         if (cur.pos() != 0 || isempty)
417                 setCursor(cur, cur.pit() + 1, 0);
418         else
419                 setCursor(cur, cur.pit(), 0);
420 }
421
422
423 // insert a character, moves all the following breaks in the
424 // same Paragraph one to the right and make a rebreak
425 void Text::insertChar(Cursor & cur, char_type c)
426 {
427         LASSERT(this == cur.text(), /**/);
428
429         cur.recordUndo(INSERT_UNDO);
430
431         TextMetrics const & tm = cur.bv().textMetrics(this);
432         Buffer const & buffer = *cur.buffer();
433         Paragraph & par = cur.paragraph();
434         // try to remove this
435         pit_type const pit = cur.pit();
436
437         bool const freeSpacing = par.layout().free_spacing ||
438                 par.isFreeSpacing();
439
440         if (lyxrc.auto_number) {
441                 static docstring const number_operators = from_ascii("+-/*");
442                 static docstring const number_unary_operators = from_ascii("+-");
443                 static docstring const number_seperators = from_ascii(".,:");
444
445                 if (cur.current_font.fontInfo().number() == FONT_ON) {
446                         if (!isDigit(c) && !contains(number_operators, c) &&
447                             !(contains(number_seperators, c) &&
448                               cur.pos() != 0 &&
449                               cur.pos() != cur.lastpos() &&
450                               tm.displayFont(pit, cur.pos()).fontInfo().number() == FONT_ON &&
451                               tm.displayFont(pit, cur.pos() - 1).fontInfo().number() == FONT_ON)
452                            )
453                                 number(cur); // Set current_font.number to OFF
454                 } else if (isDigit(c) &&
455                            cur.real_current_font.isVisibleRightToLeft()) {
456                         number(cur); // Set current_font.number to ON
457
458                         if (cur.pos() != 0) {
459                                 char_type const c = par.getChar(cur.pos() - 1);
460                                 if (contains(number_unary_operators, c) &&
461                                     (cur.pos() == 1
462                                      || par.isSeparator(cur.pos() - 2)
463                                      || par.isNewline(cur.pos() - 2))
464                                   ) {
465                                         setCharFont(buffer, pit, cur.pos() - 1, cur.current_font,
466                                                 tm.font_);
467                                 } else if (contains(number_seperators, c)
468                                      && cur.pos() >= 2
469                                      && tm.displayFont(pit, cur.pos() - 2).fontInfo().number() == FONT_ON) {
470                                         setCharFont(buffer, pit, cur.pos() - 1, cur.current_font,
471                                                 tm.font_);
472                                 }
473                         }
474                 }
475         }
476
477         // In Bidi text, we want spaces to be treated in a special way: spaces
478         // which are between words in different languages should get the 
479         // paragraph's language; otherwise, spaces should keep the language 
480         // they were originally typed in. This is only in effect while typing;
481         // after the text is already typed in, the user can always go back and
482         // explicitly set the language of a space as desired. But 99.9% of the
483         // time, what we're doing here is what the user actually meant.
484         // 
485         // The following cases are the ones in which the language of the space
486         // should be changed to match that of the containing paragraph. In the
487         // depictions, lowercase is LTR, uppercase is RTL, underscore (_) 
488         // represents a space, pipe (|) represents the cursor position (so the
489         // character before it is the one just typed in). The different cases
490         // are depicted logically (not visually), from left to right:
491         // 
492         // 1. A_a|
493         // 2. a_A|
494         //
495         // Theoretically, there are other situations that we should, perhaps, deal
496         // with (e.g.: a|_A, A|_a). In practice, though, there really isn't any 
497         // point (to understand why, just try to create this situation...).
498
499         if ((cur.pos() >= 2) && (par.isLineSeparator(cur.pos() - 1))) {
500                 // get font in front and behind the space in question. But do NOT 
501                 // use getFont(cur.pos()) because the character c is not inserted yet
502                 Font const pre_space_font  = tm.displayFont(cur.pit(), cur.pos() - 2);
503                 Font const & post_space_font = cur.real_current_font;
504                 bool pre_space_rtl  = pre_space_font.isVisibleRightToLeft();
505                 bool post_space_rtl = post_space_font.isVisibleRightToLeft();
506                 
507                 if (pre_space_rtl != post_space_rtl) {
508                         // Set the space's language to match the language of the 
509                         // adjacent character whose direction is the paragraph's
510                         // direction; don't touch other properties of the font
511                         Language const * lang = 
512                                 (pre_space_rtl == par.isRTL(buffer.params())) ?
513                                 pre_space_font.language() : post_space_font.language();
514
515                         Font space_font = tm.displayFont(cur.pit(), cur.pos() - 1);
516                         space_font.setLanguage(lang);
517                         par.setFont(cur.pos() - 1, space_font);
518                 }
519         }
520         
521         // Next check, if there will be two blanks together or a blank at
522         // the beginning of a paragraph.
523         // I decided to handle blanks like normal characters, the main
524         // difference are the special checks when calculating the row.fill
525         // (blank does not count at the end of a row) and the check here
526
527         // When the free-spacing option is set for the current layout,
528         // disable the double-space checking
529         if (!freeSpacing && isLineSeparatorChar(c)) {
530                 if (cur.pos() == 0) {
531                         static bool sent_space_message = false;
532                         if (!sent_space_message) {
533                                 cur.message(_("You cannot insert a space at the "
534                                                            "beginning of a paragraph. Please read the Tutorial."));
535                                 sent_space_message = true;
536                         }
537                         return;
538                 }
539                 LASSERT(cur.pos() > 0, /**/);
540                 if ((par.isLineSeparator(cur.pos() - 1) || par.isNewline(cur.pos() - 1))
541                     && !par.isDeleted(cur.pos() - 1)) {
542                         static bool sent_space_message = false;
543                         if (!sent_space_message) {
544                                 cur.message(_("You cannot type two spaces this way. "
545                                                            "Please read the Tutorial."));
546                                 sent_space_message = true;
547                         }
548                         return;
549                 }
550         }
551
552         par.insertChar(cur.pos(), c, cur.current_font,
553                 cur.buffer()->params().trackChanges);
554         cur.checkBufferStructure();
555
556 //              cur.updateFlags(Update::Force);
557         setCursor(cur.top(), cur.pit(), cur.pos() + 1);
558         charInserted(cur);
559 }
560
561
562 void Text::charInserted(Cursor & cur)
563 {
564         Paragraph & par = cur.paragraph();
565
566         // Here we call finishUndo for every 20 characters inserted.
567         // This is from my experience how emacs does it. (Lgb)
568         static unsigned int counter;
569         if (counter < 20) {
570                 ++counter;
571         } else {
572                 cur.finishUndo();
573                 counter = 0;
574         }
575
576         // register word if a non-letter was entered
577         if (cur.pos() > 1
578             && par.isLetter(cur.pos() - 2)
579             && !par.isLetter(cur.pos() - 1)) {
580                 // get the word in front of cursor
581                 LASSERT(this == cur.text(), /**/);
582                 cur.paragraph().updateWords();
583         }
584 }
585
586
587 // the cursor set functions have a special mechanism. When they
588 // realize, that you left an empty paragraph, they will delete it.
589
590 bool Text::cursorForwardOneWord(Cursor & cur)
591 {
592         LASSERT(this == cur.text(), /**/);
593
594         pos_type const lastpos = cur.lastpos();
595         pit_type pit = cur.pit();
596         pos_type pos = cur.pos();
597         Paragraph const & par = cur.paragraph();
598
599         // Paragraph boundary is a word boundary
600         if (pos == lastpos) {
601                 if (pit != cur.lastpit())
602                         return setCursor(cur, pit + 1, 0);
603                 else
604                         return false;
605         }
606
607         if (lyxrc.mac_like_word_movement) {
608                 // Skip through trailing punctuation and spaces.
609                 while (pos != lastpos && (par.isChar(pos) || par.isSpace(pos)))
610                         ++pos;
611
612                 // Skip over either a non-char inset or a full word
613                 if (pos != lastpos && !par.isLetter(pos))
614                         ++pos;
615                 else while (pos != lastpos && par.isLetter(pos))
616                              ++pos;
617         } else {
618                 LASSERT(pos < lastpos, /**/); // see above
619                 if (par.isLetter(pos))
620                         while (pos != lastpos && par.isLetter(pos))
621                                 ++pos;
622                 else if (par.isChar(pos))
623                         while (pos != lastpos && par.isChar(pos))
624                                 ++pos;
625                 else if (!par.isSpace(pos)) // non-char inset
626                         ++pos;
627
628                 // Skip over white space
629                 while (pos != lastpos && par.isSpace(pos))
630                              ++pos;             
631         }
632
633         return setCursor(cur, pit, pos);
634 }
635
636
637 bool Text::cursorBackwardOneWord(Cursor & cur)
638 {
639         LASSERT(this == cur.text(), /**/);
640
641         pit_type pit = cur.pit();
642         pos_type pos = cur.pos();
643         Paragraph & par = cur.paragraph();
644
645         // Paragraph boundary is a word boundary
646         if (pos == 0 && pit != 0)
647                 return setCursor(cur, pit - 1, getPar(pit - 1).size());
648
649         if (lyxrc.mac_like_word_movement) {
650                 // Skip through punctuation and spaces.
651                 while (pos != 0 && (par.isChar(pos - 1) || par.isSpace(pos - 1)))
652                         --pos;
653
654                 // Skip over either a non-char inset or a full word
655                 if (pos != 0 && !par.isLetter(pos - 1) && !par.isChar(pos - 1))
656                         --pos;
657                 else while (pos != 0 && par.isLetter(pos - 1))
658                              --pos;
659         } else {
660                 // Skip over white space
661                 while (pos != 0 && par.isSpace(pos - 1))
662                              --pos;
663
664                 if (pos != 0 && par.isLetter(pos - 1))
665                         while (pos != 0 && par.isLetter(pos - 1))
666                                 --pos;
667                 else if (pos != 0 && par.isChar(pos - 1))
668                         while (pos != 0 && par.isChar(pos - 1))
669                                 --pos;
670                 else if (pos != 0 && !par.isSpace(pos - 1)) // non-char inset
671                         --pos;
672         }
673
674         return setCursor(cur, pit, pos);
675 }
676
677
678 bool Text::cursorVisLeftOneWord(Cursor & cur)
679 {
680         LASSERT(this == cur.text(), /**/);
681
682         pos_type left_pos, right_pos;
683         bool left_is_letter, right_is_letter;
684
685         Cursor temp_cur = cur;
686
687         // always try to move at least once...
688         while (temp_cur.posVisLeft(true /* skip_inset */)) {
689
690                 // collect some information about current cursor position
691                 temp_cur.getSurroundingPos(left_pos, right_pos);
692                 left_is_letter = 
693                         (left_pos > -1 ? temp_cur.paragraph().isLetter(left_pos) : false);
694                 right_is_letter = 
695                         (right_pos > -1 ? temp_cur.paragraph().isLetter(right_pos) : false);
696
697                 // if we're not at a letter/non-letter boundary, continue moving
698                 if (left_is_letter == right_is_letter)
699                         continue;
700
701                 // we should stop when we have an LTR word on our right or an RTL word
702                 // on our left
703                 if ((left_is_letter && temp_cur.paragraph().getFontSettings(
704                                 temp_cur.buffer()->params(), left_pos).isRightToLeft())
705                         || (right_is_letter && !temp_cur.paragraph().getFontSettings(
706                                 temp_cur.buffer()->params(), right_pos).isRightToLeft()))
707                         break;
708         }
709
710         return setCursor(cur, temp_cur.pit(), temp_cur.pos(), 
711                                          true, temp_cur.boundary());
712 }
713
714
715 bool Text::cursorVisRightOneWord(Cursor & cur)
716 {
717         LASSERT(this == cur.text(), /**/);
718
719         pos_type left_pos, right_pos;
720         bool left_is_letter, right_is_letter;
721
722         Cursor temp_cur = cur;
723
724         // always try to move at least once...
725         while (temp_cur.posVisRight(true /* skip_inset */)) {
726
727                 // collect some information about current cursor position
728                 temp_cur.getSurroundingPos(left_pos, right_pos);
729                 left_is_letter = 
730                         (left_pos > -1 ? temp_cur.paragraph().isLetter(left_pos) : false);
731                 right_is_letter = 
732                         (right_pos > -1 ? temp_cur.paragraph().isLetter(right_pos) : false);
733
734                 // if we're not at a letter/non-letter boundary, continue moving
735                 if (left_is_letter == right_is_letter)
736                         continue;
737
738                 // we should stop when we have an LTR word on our right or an RTL word
739                 // on our left
740                 if ((left_is_letter && temp_cur.paragraph().getFontSettings(
741                                 temp_cur.buffer()->params(), 
742                                 left_pos).isRightToLeft())
743                         || (right_is_letter && !temp_cur.paragraph().getFontSettings(
744                                 temp_cur.buffer()->params(), 
745                                 right_pos).isRightToLeft()))
746                         break;
747         }
748
749         return setCursor(cur, temp_cur.pit(), temp_cur.pos(), 
750                                          true, temp_cur.boundary());
751 }
752
753
754 void Text::selectWord(Cursor & cur, word_location loc)
755 {
756         LASSERT(this == cur.text(), /**/);
757         CursorSlice from = cur.top();
758         CursorSlice to = cur.top();
759         getWord(from, to, loc);
760         if (cur.top() != from)
761                 setCursor(cur, from.pit(), from.pos());
762         if (to == from)
763                 return;
764         cur.resetAnchor();
765         setCursor(cur, to.pit(), to.pos());
766         cur.setSelection();
767 }
768
769
770 void Text::selectAll(Cursor & cur)
771 {
772         LASSERT(this == cur.text(), /**/);
773         if (cur.lastpos() == 0 && cur.lastpit() == 0)
774                 return;
775         // If the cursor is at the beginning, make sure the cursor ends there
776         if (cur.pit() == 0 && cur.pos() == 0) {
777                 setCursor(cur, cur.lastpit(), getPar(cur.lastpit()).size());
778                 cur.resetAnchor();
779                 setCursor(cur, 0, 0);           
780         } else {
781                 setCursor(cur, 0, 0);
782                 cur.resetAnchor();
783                 setCursor(cur, cur.lastpit(), getPar(cur.lastpit()).size());
784         }
785         cur.setSelection();
786 }
787
788
789 // Select the word currently under the cursor when no
790 // selection is currently set
791 bool Text::selectWordWhenUnderCursor(Cursor & cur, word_location loc)
792 {
793         LASSERT(this == cur.text(), /**/);
794         if (cur.selection())
795                 return false;
796         selectWord(cur, loc);
797         return cur.selection();
798 }
799
800
801 void Text::acceptOrRejectChanges(Cursor & cur, ChangeOp op)
802 {
803         LASSERT(this == cur.text(), /**/);
804
805         if (!cur.selection()) {
806                 Change const & change = cur.paragraph().lookupChange(cur.pos());
807                 if (!(change.changed() && findNextChange(&cur.bv())))
808                         return;
809         }
810
811         cur.recordUndoSelection();
812
813         pit_type begPit = cur.selectionBegin().pit();
814         pit_type endPit = cur.selectionEnd().pit();
815
816         pos_type begPos = cur.selectionBegin().pos();
817         pos_type endPos = cur.selectionEnd().pos();
818
819         // keep selection info, because endPos becomes invalid after the first loop
820         bool endsBeforeEndOfPar = (endPos < pars_[endPit].size());
821
822         // first, accept/reject changes within each individual paragraph (do not consider end-of-par)
823
824         for (pit_type pit = begPit; pit <= endPit; ++pit) {
825                 pos_type parSize = pars_[pit].size();
826
827                 // ignore empty paragraphs; otherwise, an assertion will fail for
828                 // acceptChanges(bparams, 0, 0) or rejectChanges(bparams, 0, 0)
829                 if (parSize == 0)
830                         continue;
831
832                 // do not consider first paragraph if the cursor starts at pos size()
833                 if (pit == begPit && begPos == parSize)
834                         continue;
835
836                 // do not consider last paragraph if the cursor ends at pos 0
837                 if (pit == endPit && endPos == 0)
838                         break; // last iteration anyway
839
840                 pos_type left  = (pit == begPit ? begPos : 0);
841                 pos_type right = (pit == endPit ? endPos : parSize);
842
843                 if (op == ACCEPT) {
844                         pars_[pit].acceptChanges(cur.buffer()->params(), left, right);
845                 } else {
846                         pars_[pit].rejectChanges(cur.buffer()->params(), left, right);
847                 }
848         }
849
850         // next, accept/reject imaginary end-of-par characters
851
852         for (pit_type pit = begPit; pit <= endPit; ++pit) {
853                 pos_type pos = pars_[pit].size();
854
855                 // skip if the selection ends before the end-of-par
856                 if (pit == endPit && endsBeforeEndOfPar)
857                         break; // last iteration anyway
858
859                 // skip if this is not the last paragraph of the document
860                 // note: the user should be able to accept/reject the par break of the last par!
861                 if (pit == endPit && pit + 1 != int(pars_.size()))
862                         break; // last iteration anway
863
864                 if (op == ACCEPT) {
865                         if (pars_[pit].isInserted(pos)) {
866                                 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
867                         } else if (pars_[pit].isDeleted(pos)) {
868                                 if (pit + 1 == int(pars_.size())) {
869                                         // we cannot remove a par break at the end of the last paragraph;
870                                         // instead, we mark it unchanged
871                                         pars_[pit].setChange(pos, Change(Change::UNCHANGED));
872                                 } else {
873                                         mergeParagraph(cur.buffer()->params(), pars_, pit);
874                                         --endPit;
875                                         --pit;
876                                 }
877                         }
878                 } else {
879                         if (pars_[pit].isDeleted(pos)) {
880                                 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
881                         } else if (pars_[pit].isInserted(pos)) {
882                                 if (pit + 1 == int(pars_.size())) {
883                                         // we mark the par break at the end of the last paragraph unchanged
884                                         pars_[pit].setChange(pos, Change(Change::UNCHANGED));
885                                 } else {
886                                         mergeParagraph(cur.buffer()->params(), pars_, pit);
887                                         --endPit;
888                                         --pit;
889                                 }
890                         }
891                 }
892         }
893
894         // finally, invoke the DEPM
895
896         deleteEmptyParagraphMechanism(begPit, endPit, cur.buffer()->params().trackChanges);
897
898         //
899
900         cur.finishUndo();
901         cur.clearSelection();
902         setCursorIntern(cur, begPit, begPos);
903         cur.updateFlags(Update::Force);
904         cur.buffer()->updateLabels();
905 }
906
907
908 void Text::acceptChanges(BufferParams const & bparams)
909 {
910         lyx::acceptChanges(pars_, bparams);
911         deleteEmptyParagraphMechanism(0, pars_.size() - 1, bparams.trackChanges);
912 }
913
914
915 void Text::rejectChanges(BufferParams const & bparams)
916 {
917         pit_type pars_size = static_cast<pit_type>(pars_.size());
918
919         // first, reject changes within each individual paragraph
920         // (do not consider end-of-par)
921         for (pit_type pit = 0; pit < pars_size; ++pit) {
922                 if (!pars_[pit].empty())   // prevent assertion failure
923                         pars_[pit].rejectChanges(bparams, 0, pars_[pit].size());
924         }
925
926         // next, reject imaginary end-of-par characters
927         for (pit_type pit = 0; pit < pars_size; ++pit) {
928                 pos_type pos = pars_[pit].size();
929
930                 if (pars_[pit].isDeleted(pos)) {
931                         pars_[pit].setChange(pos, Change(Change::UNCHANGED));
932                 } else if (pars_[pit].isInserted(pos)) {
933                         if (pit == pars_size - 1) {
934                                 // we mark the par break at the end of the last
935                                 // paragraph unchanged
936                                 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
937                         } else {
938                                 mergeParagraph(bparams, pars_, pit);
939                                 --pit;
940                                 --pars_size;
941                         }
942                 }
943         }
944
945         // finally, invoke the DEPM
946         deleteEmptyParagraphMechanism(0, pars_size - 1, bparams.trackChanges);
947 }
948
949
950 void Text::deleteWordForward(Cursor & cur)
951 {
952         LASSERT(this == cur.text(), /**/);
953         if (cur.lastpos() == 0)
954                 cursorForward(cur);
955         else {
956                 cur.resetAnchor();
957                 cur.setSelection(true);
958                 cursorForwardOneWord(cur);
959                 cur.setSelection();
960                 cutSelection(cur, true, false);
961                 cur.checkBufferStructure();
962         }
963 }
964
965
966 void Text::deleteWordBackward(Cursor & cur)
967 {
968         LASSERT(this == cur.text(), /**/);
969         if (cur.lastpos() == 0)
970                 cursorBackward(cur);
971         else {
972                 cur.resetAnchor();
973                 cur.setSelection(true);
974                 cursorBackwardOneWord(cur);
975                 cur.setSelection();
976                 cutSelection(cur, true, false);
977                 cur.checkBufferStructure();
978         }
979 }
980
981
982 // Kill to end of line.
983 void Text::changeCase(Cursor & cur, TextCase action)
984 {
985         LASSERT(this == cur.text(), /**/);
986         CursorSlice from;
987         CursorSlice to;
988
989         bool gotsel = false;
990         if (cur.selection()) {
991                 from = cur.selBegin();
992                 to = cur.selEnd();
993                 gotsel = true;
994         } else {
995                 from = cur.top();
996                 getWord(from, to, PARTIAL_WORD);
997                 cursorForwardOneWord(cur);
998         }
999
1000         cur.recordUndoSelection();
1001
1002         pit_type begPit = from.pit();
1003         pit_type endPit = to.pit();
1004
1005         pos_type begPos = from.pos();
1006         pos_type endPos = to.pos();
1007
1008         pos_type right = 0; // needed after the for loop
1009
1010         for (pit_type pit = begPit; pit <= endPit; ++pit) {
1011                 Paragraph & par = pars_[pit];
1012                 pos_type const pos = (pit == begPit ? begPos : 0);
1013                 right = (pit == endPit ? endPos : par.size());
1014                 par.changeCase(cur.buffer()->params(), pos, right, action);
1015         }
1016
1017         // the selection may have changed due to logically-only deleted chars
1018         if (gotsel) {
1019                 setCursor(cur, begPit, begPos);
1020                 cur.resetAnchor();
1021                 setCursor(cur, endPit, right);
1022                 cur.setSelection();
1023         } else
1024                 setCursor(cur, endPit, right);
1025
1026         cur.checkBufferStructure();
1027 }
1028
1029
1030 bool Text::handleBibitems(Cursor & cur)
1031 {
1032         if (cur.paragraph().layout().labeltype != LABEL_BIBLIO)
1033                 return false;
1034
1035         if (cur.pos() != 0)
1036                 return false;
1037
1038         BufferParams const & bufparams = cur.buffer()->params();
1039         Paragraph const & par = cur.paragraph();
1040         Cursor prevcur = cur;
1041         if (cur.pit() > 0) {
1042                 --prevcur.pit();
1043                 prevcur.pos() = prevcur.lastpos();
1044         }
1045         Paragraph const & prevpar = prevcur.paragraph();
1046
1047         // if a bibitem is deleted, merge with previous paragraph
1048         // if this is a bibliography item as well
1049         if (cur.pit() > 0 && par.layout() == prevpar.layout()) {
1050                 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
1051                 mergeParagraph(bufparams, cur.text()->paragraphs(),
1052                                                         prevcur.pit());
1053                 cur.buffer()->updateLabels();
1054                 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1055                 cur.updateFlags(Update::Force);
1056                 return true;
1057         } 
1058
1059         // otherwise reset to default
1060         cur.paragraph().setPlainOrDefaultLayout(bufparams.documentClass());
1061         return true;
1062 }
1063
1064
1065 bool Text::erase(Cursor & cur)
1066 {
1067         LASSERT(this == cur.text(), return false);
1068         bool needsUpdate = false;
1069         Paragraph & par = cur.paragraph();
1070
1071         if (cur.pos() != cur.lastpos()) {
1072                 // this is the code for a normal delete, not pasting
1073                 // any paragraphs
1074                 cur.recordUndo(DELETE_UNDO);
1075                 bool const was_inset = cur.paragraph().isInset(cur.pos());
1076                 if(!par.eraseChar(cur.pos(), cur.buffer()->params().trackChanges))
1077                         // the character has been logically deleted only => skip it
1078                         cur.top().forwardPos();
1079
1080                 if (was_inset)
1081                         cur.buffer()->updateLabels();
1082                 else
1083                         cur.checkBufferStructure();
1084                 needsUpdate = true;
1085         } else {
1086                 if (cur.pit() == cur.lastpit())
1087                         return dissolveInset(cur);
1088
1089                 if (!par.isMergedOnEndOfParDeletion(cur.buffer()->params().trackChanges)) {
1090                         par.setChange(cur.pos(), Change(Change::DELETED));
1091                         cur.forwardPos();
1092                         needsUpdate = true;
1093                 } else {
1094                         setCursorIntern(cur, cur.pit() + 1, 0);
1095                         needsUpdate = backspacePos0(cur);
1096                 }
1097         }
1098
1099         needsUpdate |= handleBibitems(cur);
1100
1101         if (needsUpdate) {
1102                 // Make sure the cursor is correct. Is this really needed?
1103                 // No, not really... at least not here!
1104                 cur.text()->setCursor(cur.top(), cur.pit(), cur.pos());
1105                 cur.checkBufferStructure();
1106         }
1107
1108         return needsUpdate;
1109 }
1110
1111
1112 bool Text::backspacePos0(Cursor & cur)
1113 {
1114         LASSERT(this == cur.text(), /**/);
1115         if (cur.pit() == 0)
1116                 return false;
1117
1118         bool needsUpdate = false;
1119
1120         BufferParams const & bufparams = cur.buffer()->params();
1121         DocumentClass const & tclass = bufparams.documentClass();
1122         ParagraphList & plist = cur.text()->paragraphs();
1123         Paragraph const & par = cur.paragraph();
1124         Cursor prevcur = cur;
1125         --prevcur.pit();
1126         prevcur.pos() = prevcur.lastpos();
1127         Paragraph const & prevpar = prevcur.paragraph();
1128
1129         // is it an empty paragraph?
1130         if (cur.lastpos() == 0
1131             || (cur.lastpos() == 1 && par.isSeparator(0))) {
1132                 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1133                 plist.erase(boost::next(plist.begin(), cur.pit()));
1134                 needsUpdate = true;
1135         }
1136         // is previous par empty?
1137         else if (prevcur.lastpos() == 0
1138                  || (prevcur.lastpos() == 1 && prevpar.isSeparator(0))) {
1139                 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1140                 plist.erase(boost::next(plist.begin(), prevcur.pit()));
1141                 needsUpdate = true;
1142         }
1143         // Pasting is not allowed, if the paragraphs have different
1144         // layouts. I think it is a real bug of all other
1145         // word processors to allow it. It confuses the user.
1146         // Correction: Pasting is always allowed with standard-layout
1147         // or the empty layout.
1148         else if (par.layout() == prevpar.layout()
1149                  || tclass.isDefaultLayout(par.layout())
1150                  || tclass.isPlainLayout(par.layout())) {
1151                 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
1152                 mergeParagraph(bufparams, plist, prevcur.pit());
1153                 needsUpdate = true;
1154         }
1155
1156         if (needsUpdate) {
1157                 cur.buffer()->updateLabels();
1158                 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1159         }
1160
1161         return needsUpdate;
1162 }
1163
1164
1165 bool Text::backspace(Cursor & cur)
1166 {
1167         LASSERT(this == cur.text(), /**/);
1168         bool needsUpdate = false;
1169         if (cur.pos() == 0) {
1170                 if (cur.pit() == 0)
1171                         return dissolveInset(cur);
1172
1173                 Paragraph & prev_par = pars_[cur.pit() - 1];
1174
1175                 if (!prev_par.isMergedOnEndOfParDeletion(cur.buffer()->params().trackChanges)) {
1176                         prev_par.setChange(prev_par.size(), Change(Change::DELETED));
1177                         setCursorIntern(cur, cur.pit() - 1, prev_par.size());
1178                         return true;
1179                 }
1180                 // The cursor is at the beginning of a paragraph, so
1181                 // the backspace will collapse two paragraphs into one.
1182                 needsUpdate = backspacePos0(cur);
1183
1184         } else {
1185                 // this is the code for a normal backspace, not pasting
1186                 // any paragraphs
1187                 cur.recordUndo(DELETE_UNDO);
1188                 // We used to do cursorBackwardIntern() here, but it is
1189                 // not a good idea since it triggers the auto-delete
1190                 // mechanism. So we do a cursorBackwardIntern()-lite,
1191                 // without the dreaded mechanism. (JMarc)
1192                 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1193                                 false, cur.boundary());
1194                 bool const was_inset = cur.paragraph().isInset(cur.pos());
1195                 cur.paragraph().eraseChar(cur.pos(), cur.buffer()->params().trackChanges);
1196                 if (was_inset)
1197                         cur.buffer()->updateLabels();
1198                 else
1199                         cur.checkBufferStructure();
1200         }
1201
1202         if (cur.pos() == cur.lastpos())
1203                 cur.setCurrentFont();
1204
1205         needsUpdate |= handleBibitems(cur);
1206
1207         // A singlePar update is not enough in this case.
1208 //              cur.updateFlags(Update::Force);
1209         setCursor(cur.top(), cur.pit(), cur.pos());
1210
1211         return needsUpdate;
1212 }
1213
1214
1215 bool Text::dissolveInset(Cursor & cur)
1216 {
1217         LASSERT(this == cur.text(), return false);
1218
1219         if (isMainText(cur.bv().buffer()) || cur.inset().nargs() != 1)
1220                 return false;
1221
1222         cur.recordUndoInset();
1223         cur.setMark(false);
1224         cur.selHandle(false);
1225         // save position
1226         pos_type spos = cur.pos();
1227         pit_type spit = cur.pit();
1228         ParagraphList plist;
1229         if (cur.lastpit() != 0 || cur.lastpos() != 0)
1230                 plist = paragraphs();
1231         cur.popBackward();
1232         // store cursor offset
1233         if (spit == 0)
1234                 spos += cur.pos();
1235         spit += cur.pit();
1236         Buffer & b = *cur.buffer();
1237         cur.paragraph().eraseChar(cur.pos(), b.params().trackChanges);
1238         if (!plist.empty()) {
1239                 // ERT paragraphs have the Language latex_language.
1240                 // This is invalid outside of ERT, so we need to
1241                 // change it to the buffer language.
1242                 ParagraphList::iterator it = plist.begin();
1243                 ParagraphList::iterator it_end = plist.end();
1244                 for (; it != it_end; it++)
1245                         it->changeLanguage(b.params(), latex_language, b.language());
1246
1247                 pasteParagraphList(cur, plist, b.params().documentClassPtr(),
1248                                    b.errorList("Paste"));
1249                 // restore position
1250                 cur.pit() = min(cur.lastpit(), spit);
1251                 cur.pos() = min(cur.lastpos(), spos);
1252         }
1253         cur.clearSelection();
1254         cur.resetAnchor();
1255         return true;
1256 }
1257
1258
1259 void Text::getWord(CursorSlice & from, CursorSlice & to,
1260         word_location const loc) const
1261 {
1262         to = from;
1263         pars_[to.pit()].locateWord(from.pos(), to.pos(), loc);
1264 }
1265
1266
1267 void Text::write(Buffer const & buf, ostream & os) const
1268 {
1269         ParagraphList::const_iterator pit = paragraphs().begin();
1270         ParagraphList::const_iterator end = paragraphs().end();
1271         depth_type dth = 0;
1272         for (; pit != end; ++pit)
1273                 pit->write(os, buf.params(), dth);
1274
1275         // Close begin_deeper
1276         for(; dth > 0; --dth)
1277                 os << "\n\\end_deeper";
1278 }
1279
1280
1281 bool Text::read(Buffer const & buf, Lexer & lex, 
1282                 ErrorList & errorList, InsetText * insetPtr)
1283 {
1284         depth_type depth = 0;
1285         bool res = true;
1286
1287         while (lex.isOK()) {
1288                 lex.nextToken();
1289                 string const token = lex.getString();
1290
1291                 if (token.empty())
1292                         continue;
1293
1294                 if (token == "\\end_inset")
1295                         break;
1296
1297                 if (token == "\\end_body")
1298                         continue;
1299
1300                 if (token == "\\begin_body")
1301                         continue;
1302
1303                 if (token == "\\end_document") {
1304                         res = false;
1305                         break;
1306                 }
1307
1308                 if (token == "\\begin_layout") {
1309                         lex.pushToken(token);
1310
1311                         Paragraph par;
1312                         par.setInsetOwner(insetPtr);
1313                         par.params().depth(depth);
1314                         par.setFont(0, Font(inherit_font, buf.params().language));
1315                         pars_.push_back(par);
1316
1317                         // FIXME: goddamn InsetTabular makes us pass a Buffer
1318                         // not BufferParams
1319                         lyx::readParagraph(buf, pars_.back(), lex, errorList);
1320
1321                         // register the words in the global word list
1322                         CursorSlice sl = CursorSlice(*insetPtr);
1323                         sl.pit() = pars_.size() - 1;
1324                         pars_.back().updateWords();
1325                 } else if (token == "\\begin_deeper") {
1326                         ++depth;
1327                 } else if (token == "\\end_deeper") {
1328                         if (!depth)
1329                                 lex.printError("\\end_deeper: " "depth is already null");
1330                         else
1331                                 --depth;
1332                 } else {
1333                         LYXERR0("Handling unknown body token: `" << token << '\'');
1334                 }
1335         }
1336
1337         // avoid a crash on weird documents (bug 4859)
1338         if (pars_.empty()) {
1339                 Paragraph par;
1340                 par.setInsetOwner(insetPtr);
1341                 par.params().depth(depth);
1342                 par.setFont(0, Font(inherit_font, 
1343                                     buf.params().language));
1344                 par.setPlainOrDefaultLayout(buf.params().documentClass());
1345                 pars_.push_back(par);
1346         }
1347         
1348         return res;
1349 }
1350
1351 // Returns the current font and depth as a message.
1352 docstring Text::currentState(Cursor const & cur) const
1353 {
1354         LASSERT(this == cur.text(), /**/);
1355         Buffer & buf = *cur.buffer();
1356         Paragraph const & par = cur.paragraph();
1357         odocstringstream os;
1358
1359         if (buf.params().trackChanges)
1360                 os << _("[Change Tracking] ");
1361
1362         Change change = par.lookupChange(cur.pos());
1363
1364         if (change.type != Change::UNCHANGED) {
1365                 Author const & a = buf.params().authors().get(change.author);
1366                 os << _("Change: ") << a.name();
1367                 if (!a.email().empty())
1368                         os << " (" << a.email() << ")";
1369                 // FIXME ctime is english, we should translate that
1370                 os << _(" at ") << ctime(&change.changetime);
1371                 os << " : ";
1372         }
1373
1374         // I think we should only show changes from the default
1375         // font. (Asger)
1376         // No, from the document font (MV)
1377         Font font = cur.real_current_font;
1378         font.fontInfo().reduce(buf.params().getFont().fontInfo());
1379
1380         os << bformat(_("Font: %1$s"), font.stateText(&buf.params()));
1381
1382         // The paragraph depth
1383         int depth = cur.paragraph().getDepth();
1384         if (depth > 0)
1385                 os << bformat(_(", Depth: %1$d"), depth);
1386
1387         // The paragraph spacing, but only if different from
1388         // buffer spacing.
1389         Spacing const & spacing = par.params().spacing();
1390         if (!spacing.isDefault()) {
1391                 os << _(", Spacing: ");
1392                 switch (spacing.getSpace()) {
1393                 case Spacing::Single:
1394                         os << _("Single");
1395                         break;
1396                 case Spacing::Onehalf:
1397                         os << _("OneHalf");
1398                         break;
1399                 case Spacing::Double:
1400                         os << _("Double");
1401                         break;
1402                 case Spacing::Other:
1403                         os << _("Other (") << from_ascii(spacing.getValueAsString()) << ')';
1404                         break;
1405                 case Spacing::Default:
1406                         // should never happen, do nothing
1407                         break;
1408                 }
1409         }
1410
1411 #ifdef DEVEL_VERSION
1412         os << _(", Inset: ") << &cur.inset();
1413         os << _(", Paragraph: ") << cur.pit();
1414         os << _(", Id: ") << par.id();
1415         os << _(", Position: ") << cur.pos();
1416         // FIXME: Why is the check for par.size() needed?
1417         // We are called with cur.pos() == par.size() quite often.
1418         if (!par.empty() && cur.pos() < par.size()) {
1419                 // Force output of code point, not character
1420                 size_t const c = par.getChar(cur.pos());
1421                 os << _(", Char: 0x") << hex << c;
1422         }
1423         os << _(", Boundary: ") << cur.boundary();
1424 //      Row & row = cur.textRow();
1425 //      os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
1426 #endif
1427         return os.str();
1428 }
1429
1430
1431 docstring Text::getPossibleLabel(Cursor const & cur) const
1432 {
1433         pit_type pit = cur.pit();
1434
1435         Layout const * layout = &(pars_[pit].layout());
1436
1437         docstring text;
1438         docstring par_text = pars_[pit].asString();
1439         string piece;
1440         // the return string of math matrices might contain linebreaks
1441         par_text = subst(par_text, '\n', '-');
1442         for (int i = 0; i < lyxrc.label_init_length; ++i) {
1443                 if (par_text.empty())
1444                         break;
1445                 docstring head;
1446                 par_text = split(par_text, head, ' ');
1447                 // Is it legal to use spaces in labels ?
1448                 if (i > 0)
1449                         text += '-';
1450                 text += head;
1451         }
1452
1453         // No need for a prefix if the user said so.
1454         if (lyxrc.label_init_length <= 0)
1455                 return text;
1456
1457         // Will contain the label type.
1458         docstring name;
1459
1460         // For section, subsection, etc...
1461         if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
1462                 Layout const * layout2 = &(pars_[pit - 1].layout());
1463                 if (layout2->latextype != LATEX_PARAGRAPH) {
1464                         --pit;
1465                         layout = layout2;
1466                 }
1467         }
1468         if (layout->latextype != LATEX_PARAGRAPH)
1469                 name = from_ascii(layout->latexname());
1470
1471         // for captions, we just take the caption type
1472         Inset * caption_inset = cur.innerInsetOfType(CAPTION_CODE);
1473         if (caption_inset)
1474                 name = from_ascii(static_cast<InsetCaption *>(caption_inset)->type());
1475
1476         // If none of the above worked, we'll see if we're inside various
1477         // types of insets and take our abbreviation from them.
1478         if (name.empty()) {
1479                 InsetCode const codes[] = {
1480                         FLOAT_CODE,
1481                         WRAP_CODE,
1482                         FOOT_CODE
1483                 };
1484                 for (unsigned int i = 0; i < (sizeof codes / sizeof codes[0]); ++i) {
1485                         Inset * float_inset = cur.innerInsetOfType(codes[i]);
1486                         if (float_inset) {
1487                                 name = float_inset->name();
1488                                 break;
1489                         }
1490                 }
1491         }
1492
1493         // Create a correct prefix for prettyref
1494         if (name == "theorem")
1495                 name = from_ascii("thm");
1496         else if (name == "Foot")
1497                 name = from_ascii("fn");
1498         else if (name == "listing")
1499                 name = from_ascii("lst");
1500
1501         if (!name.empty())
1502                 text = name.substr(0, 3) + ':' + text;
1503
1504         return text;
1505 }
1506
1507
1508 docstring Text::asString(int options) const
1509 {
1510         return asString(0, pars_.size(), options);
1511 }
1512
1513
1514 docstring Text::asString(pit_type beg, pit_type end, int options) const
1515 {
1516         size_t i = size_t(beg);
1517         docstring str = pars_[i].asString(options);
1518         for (++i; i != size_t(end); ++i) {
1519                 str += '\n';
1520                 str += pars_[i].asString(options);
1521         }
1522         return str;
1523 }
1524
1525
1526
1527 void Text::charsTranspose(Cursor & cur)
1528 {
1529         LASSERT(this == cur.text(), /**/);
1530
1531         pos_type pos = cur.pos();
1532
1533         // If cursor is at beginning or end of paragraph, do nothing.
1534         if (pos == cur.lastpos() || pos == 0)
1535                 return;
1536
1537         Paragraph & par = cur.paragraph();
1538
1539         // Get the positions of the characters to be transposed.
1540         pos_type pos1 = pos - 1;
1541         pos_type pos2 = pos;
1542
1543         // In change tracking mode, ignore deleted characters.
1544         while (pos2 < cur.lastpos() && par.isDeleted(pos2))
1545                 ++pos2;
1546         if (pos2 == cur.lastpos())
1547                 return;
1548
1549         while (pos1 >= 0 && par.isDeleted(pos1))
1550                 --pos1;
1551         if (pos1 < 0)
1552                 return;
1553
1554         // Don't do anything if one of the "characters" is not regular text.
1555         if (par.isInset(pos1) || par.isInset(pos2))
1556                 return;
1557
1558         // Store the characters to be transposed (including font information).
1559         char_type const char1 = par.getChar(pos1);
1560         Font const font1 =
1561                 par.getFontSettings(cur.buffer()->params(), pos1);
1562
1563         char_type const char2 = par.getChar(pos2);
1564         Font const font2 =
1565                 par.getFontSettings(cur.buffer()->params(), pos2);
1566
1567         // And finally, we are ready to perform the transposition.
1568         // Track the changes if Change Tracking is enabled.
1569         bool const trackChanges = cur.buffer()->params().trackChanges;
1570
1571         cur.recordUndo();
1572
1573         par.eraseChar(pos2, trackChanges);
1574         par.eraseChar(pos1, trackChanges);
1575         par.insertChar(pos1, char2, font2, trackChanges);
1576         par.insertChar(pos2, char1, font1, trackChanges);
1577
1578         cur.checkBufferStructure();
1579
1580         // After the transposition, move cursor to after the transposition.
1581         setCursor(cur, cur.pit(), pos2);
1582         cur.forwardPos();
1583 }
1584
1585
1586 DocIterator Text::macrocontextPosition() const
1587 {
1588         return macrocontext_position_;
1589 }
1590
1591
1592 void Text::setMacrocontextPosition(DocIterator const & pos)
1593 {
1594         macrocontext_position_ = pos;
1595 }
1596
1597
1598 docstring Text::previousWord(CursorSlice const & sl) const
1599 {
1600         CursorSlice from = sl;
1601         CursorSlice to = sl;
1602         getWord(from, to, PREVIOUS_WORD);
1603         if (sl == from || to == from)
1604                 return docstring();
1605         
1606         Paragraph const & par = sl.paragraph();
1607         return par.asString(from.pos(), to.pos());
1608 }
1609
1610
1611 bool Text::completionSupported(Cursor const & cur) const
1612 {
1613         Paragraph const & par = cur.paragraph();
1614         return cur.pos() > 0
1615                 && (cur.pos() >= par.size() || !par.isLetter(cur.pos()))
1616                 && par.isLetter(cur.pos() - 1);
1617 }
1618
1619
1620 CompletionList const * Text::createCompletionList(Cursor const & cur) const
1621 {
1622         return new TextCompletionList(cur);
1623 }
1624
1625
1626 bool Text::insertCompletion(Cursor & cur, docstring const & s, bool /*finished*/)
1627 {       
1628         LASSERT(cur.bv().cursor() == cur, /**/);
1629         cur.insert(s);
1630         cur.bv().cursor() = cur;
1631         if (!(cur.disp_.update() & Update::Force))
1632                 cur.updateFlags(cur.disp_.update() | Update::SinglePar);
1633         return true;
1634 }
1635         
1636         
1637 docstring Text::completionPrefix(Cursor const & cur) const
1638 {
1639         return previousWord(cur.top());
1640 }
1641
1642 } // namespace lyx