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