]> git.lyx.org Git - lyx.git/blob - src/Text.cpp
Improve debugging info slightly.
[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/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 == "\\strikeout") {
191                 lex.next();
192                 font.fontInfo().setStrikeout(font.setLyXMisc(lex.getString()));
193         } else if (token == "\\uuline") {
194                 lex.next();
195                 font.fontInfo().setUuline(font.setLyXMisc(lex.getString()));
196         } else if (token == "\\uwave") {
197                 lex.next();
198                 font.fontInfo().setUwave(font.setLyXMisc(lex.getString()));
199         } else if (token == "\\noun") {
200                 lex.next();
201                 font.fontInfo().setNoun(font.setLyXMisc(lex.getString()));
202         } else if (token == "\\color") {
203                 lex.next();
204                 setLyXColor(lex.getString(), font.fontInfo());
205         } else if (token == "\\SpecialChar") {
206                         auto_ptr<Inset> inset;
207                         inset.reset(new InsetSpecialChar);
208                         inset->read(lex);
209                         par.insertInset(par.size(), inset.release(),
210                                         font, change);
211         } else if (token == "\\backslash") {
212                 par.appendChar('\\', font, change);
213         } else if (token == "\\LyXTable") {
214                 auto_ptr<Inset> inset(new InsetTabular(const_cast<Buffer &>(buf)));
215                 inset->read(lex);
216                 par.insertInset(par.size(), inset.release(), font, change);
217         } else if (token == "\\lyxline") {
218                 par.insertInset(par.size(), new InsetLine, font, change);
219         } else if (token == "\\change_unchanged") {
220                 change = Change(Change::UNCHANGED);
221         } else if (token == "\\change_inserted" || token == "\\change_deleted") {
222                 lex.eatLine();
223                 istringstream is(lex.getString());
224                 unsigned int aid;
225                 time_t ct;
226                 is >> aid >> ct;
227                 if (aid >= bp.author_map.size()) {
228                         errorList.push_back(ErrorItem(_("Change tracking error"),
229                                             bformat(_("Unknown author index for change: %1$d\n"), aid),
230                                             par.id(), 0, par.size()));
231                         change = Change(Change::UNCHANGED);
232                 } else {
233                         if (token == "\\change_inserted")
234                                 change = Change(Change::INSERTED, bp.author_map[aid], ct);
235                         else 
236                                 change = Change(Change::DELETED, bp.author_map[aid], ct);
237                 }
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.isWordSeparator(cur.pos() - 2)
569             && par.isWordSeparator(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.isWordSeparator(pos))
604                         ++pos;
605                 else while (pos != lastpos && !par.isWordSeparator(pos))
606                              ++pos;
607         } else {
608                 LASSERT(pos < lastpos, /**/); // see above
609                 if (!par.isWordSeparator(pos))
610                         while (pos != lastpos && !par.isWordSeparator(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.isWordSeparator(pos - 1) && !par.isChar(pos - 1))
646                         --pos;
647                 else while (pos != 0 && !par.isWordSeparator(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.isWordSeparator(pos - 1))
655                         while (pos != 0 && !par.isWordSeparator(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().isWordSeparator(left_pos) : false);
684                 right_is_letter = 
685                         (right_pos > -1 ? !temp_cur.paragraph().isWordSeparator(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().isWordSeparator(left_pos) : false);
721                 right_is_letter = 
722                         (right_pos > -1 ? !temp_cur.paragraph().isWordSeparator(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                 Change const & change = cur.paragraph().lookupChange(cur.pos());
797                 if (!(change.changed() && findNextChange(&cur.bv())))
798                         return;
799         }
800
801         cur.recordUndoSelection();
802
803         pit_type begPit = cur.selectionBegin().pit();
804         pit_type endPit = cur.selectionEnd().pit();
805
806         pos_type begPos = cur.selectionBegin().pos();
807         pos_type endPos = cur.selectionEnd().pos();
808
809         // keep selection info, because endPos becomes invalid after the first loop
810         bool endsBeforeEndOfPar = (endPos < pars_[endPit].size());
811
812         // first, accept/reject changes within each individual paragraph (do not consider end-of-par)
813
814         for (pit_type pit = begPit; pit <= endPit; ++pit) {
815                 pos_type parSize = pars_[pit].size();
816
817                 // ignore empty paragraphs; otherwise, an assertion will fail for
818                 // acceptChanges(bparams, 0, 0) or rejectChanges(bparams, 0, 0)
819                 if (parSize == 0)
820                         continue;
821
822                 // do not consider first paragraph if the cursor starts at pos size()
823                 if (pit == begPit && begPos == parSize)
824                         continue;
825
826                 // do not consider last paragraph if the cursor ends at pos 0
827                 if (pit == endPit && endPos == 0)
828                         break; // last iteration anyway
829
830                 pos_type left  = (pit == begPit ? begPos : 0);
831                 pos_type right = (pit == endPit ? endPos : parSize);
832
833                 if (op == ACCEPT) {
834                         pars_[pit].acceptChanges(left, right);
835                 } else {
836                         pars_[pit].rejectChanges(left, right);
837                 }
838         }
839
840         // next, accept/reject imaginary end-of-par characters
841
842         for (pit_type pit = begPit; pit <= endPit; ++pit) {
843                 pos_type pos = pars_[pit].size();
844
845                 // skip if the selection ends before the end-of-par
846                 if (pit == endPit && endsBeforeEndOfPar)
847                         break; // last iteration anyway
848
849                 // skip if this is not the last paragraph of the document
850                 // note: the user should be able to accept/reject the par break of the last par!
851                 if (pit == endPit && pit + 1 != int(pars_.size()))
852                         break; // last iteration anway
853
854                 if (op == ACCEPT) {
855                         if (pars_[pit].isInserted(pos)) {
856                                 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
857                         } else if (pars_[pit].isDeleted(pos)) {
858                                 if (pit + 1 == int(pars_.size())) {
859                                         // we cannot remove a par break at the end of the last paragraph;
860                                         // instead, we mark it unchanged
861                                         pars_[pit].setChange(pos, Change(Change::UNCHANGED));
862                                 } else {
863                                         mergeParagraph(cur.buffer()->params(), pars_, pit);
864                                         --endPit;
865                                         --pit;
866                                 }
867                         }
868                 } else {
869                         if (pars_[pit].isDeleted(pos)) {
870                                 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
871                         } else if (pars_[pit].isInserted(pos)) {
872                                 if (pit + 1 == int(pars_.size())) {
873                                         // we mark the par break at the end of the last paragraph unchanged
874                                         pars_[pit].setChange(pos, Change(Change::UNCHANGED));
875                                 } else {
876                                         mergeParagraph(cur.buffer()->params(), pars_, pit);
877                                         --endPit;
878                                         --pit;
879                                 }
880                         }
881                 }
882         }
883
884         // finally, invoke the DEPM
885
886         deleteEmptyParagraphMechanism(begPit, endPit, cur.buffer()->params().trackChanges);
887
888         //
889
890         cur.finishUndo();
891         cur.clearSelection();
892         setCursorIntern(cur, begPit, begPos);
893         cur.updateFlags(Update::Force);
894         cur.buffer()->updateLabels();
895 }
896
897
898 void Text::acceptChanges(BufferParams const & bparams)
899 {
900         lyx::acceptChanges(pars_, bparams);
901         deleteEmptyParagraphMechanism(0, pars_.size() - 1, bparams.trackChanges);
902 }
903
904
905 void Text::rejectChanges(BufferParams const & bparams)
906 {
907         pit_type pars_size = static_cast<pit_type>(pars_.size());
908
909         // first, reject changes within each individual paragraph
910         // (do not consider end-of-par)
911         for (pit_type pit = 0; pit < pars_size; ++pit) {
912                 if (!pars_[pit].empty())   // prevent assertion failure
913                         pars_[pit].rejectChanges(0, pars_[pit].size());
914         }
915
916         // next, reject imaginary end-of-par characters
917         for (pit_type pit = 0; pit < pars_size; ++pit) {
918                 pos_type pos = pars_[pit].size();
919
920                 if (pars_[pit].isDeleted(pos)) {
921                         pars_[pit].setChange(pos, Change(Change::UNCHANGED));
922                 } else if (pars_[pit].isInserted(pos)) {
923                         if (pit == pars_size - 1) {
924                                 // we mark the par break at the end of the last
925                                 // paragraph unchanged
926                                 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
927                         } else {
928                                 mergeParagraph(bparams, pars_, pit);
929                                 --pit;
930                                 --pars_size;
931                         }
932                 }
933         }
934
935         // finally, invoke the DEPM
936         deleteEmptyParagraphMechanism(0, pars_size - 1, bparams.trackChanges);
937 }
938
939
940 void Text::deleteWordForward(Cursor & cur)
941 {
942         LASSERT(this == cur.text(), /**/);
943         if (cur.lastpos() == 0)
944                 cursorForward(cur);
945         else {
946                 cur.resetAnchor();
947                 cur.setSelection(true);
948                 cursorForwardOneWord(cur);
949                 cur.setSelection();
950                 cutSelection(cur, true, false);
951                 cur.checkBufferStructure();
952         }
953 }
954
955
956 void Text::deleteWordBackward(Cursor & cur)
957 {
958         LASSERT(this == cur.text(), /**/);
959         if (cur.lastpos() == 0)
960                 cursorBackward(cur);
961         else {
962                 cur.resetAnchor();
963                 cur.setSelection(true);
964                 cursorBackwardOneWord(cur);
965                 cur.setSelection();
966                 cutSelection(cur, true, false);
967                 cur.checkBufferStructure();
968         }
969 }
970
971
972 // Kill to end of line.
973 void Text::changeCase(Cursor & cur, TextCase action)
974 {
975         LASSERT(this == cur.text(), /**/);
976         CursorSlice from;
977         CursorSlice to;
978
979         bool gotsel = false;
980         if (cur.selection()) {
981                 from = cur.selBegin();
982                 to = cur.selEnd();
983                 gotsel = true;
984         } else {
985                 from = cur.top();
986                 getWord(from, to, PARTIAL_WORD);
987                 cursorForwardOneWord(cur);
988         }
989
990         cur.recordUndoSelection();
991
992         pit_type begPit = from.pit();
993         pit_type endPit = to.pit();
994
995         pos_type begPos = from.pos();
996         pos_type endPos = to.pos();
997
998         pos_type right = 0; // needed after the for loop
999
1000         for (pit_type pit = begPit; pit <= endPit; ++pit) {
1001                 Paragraph & par = pars_[pit];
1002                 pos_type const pos = (pit == begPit ? begPos : 0);
1003                 right = (pit == endPit ? endPos : par.size());
1004                 par.changeCase(cur.buffer()->params(), pos, right, action);
1005         }
1006
1007         // the selection may have changed due to logically-only deleted chars
1008         if (gotsel) {
1009                 setCursor(cur, begPit, begPos);
1010                 cur.resetAnchor();
1011                 setCursor(cur, endPit, right);
1012                 cur.setSelection();
1013         } else
1014                 setCursor(cur, endPit, right);
1015
1016         cur.checkBufferStructure();
1017 }
1018
1019
1020 bool Text::handleBibitems(Cursor & cur)
1021 {
1022         if (cur.paragraph().layout().labeltype != LABEL_BIBLIO)
1023                 return false;
1024
1025         if (cur.pos() != 0)
1026                 return false;
1027
1028         BufferParams const & bufparams = cur.buffer()->params();
1029         Paragraph const & par = cur.paragraph();
1030         Cursor prevcur = cur;
1031         if (cur.pit() > 0) {
1032                 --prevcur.pit();
1033                 prevcur.pos() = prevcur.lastpos();
1034         }
1035         Paragraph const & prevpar = prevcur.paragraph();
1036
1037         // if a bibitem is deleted, merge with previous paragraph
1038         // if this is a bibliography item as well
1039         if (cur.pit() > 0 && par.layout() == prevpar.layout()) {
1040                 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
1041                 mergeParagraph(bufparams, cur.text()->paragraphs(),
1042                                                         prevcur.pit());
1043                 cur.buffer()->updateLabels();
1044                 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1045                 cur.updateFlags(Update::Force);
1046                 return true;
1047         } 
1048
1049         // otherwise reset to default
1050         cur.paragraph().setPlainOrDefaultLayout(bufparams.documentClass());
1051         return true;
1052 }
1053
1054
1055 bool Text::erase(Cursor & cur)
1056 {
1057         LASSERT(this == cur.text(), return false);
1058         bool needsUpdate = false;
1059         Paragraph & par = cur.paragraph();
1060
1061         if (cur.pos() != cur.lastpos()) {
1062                 // this is the code for a normal delete, not pasting
1063                 // any paragraphs
1064                 cur.recordUndo(DELETE_UNDO);
1065                 bool const was_inset = cur.paragraph().isInset(cur.pos());
1066                 if(!par.eraseChar(cur.pos(), cur.buffer()->params().trackChanges))
1067                         // the character has been logically deleted only => skip it
1068                         cur.top().forwardPos();
1069
1070                 if (was_inset)
1071                         cur.buffer()->updateLabels();
1072                 else
1073                         cur.checkBufferStructure();
1074                 needsUpdate = true;
1075         } else {
1076                 if (cur.pit() == cur.lastpit())
1077                         return dissolveInset(cur);
1078
1079                 if (!par.isMergedOnEndOfParDeletion(cur.buffer()->params().trackChanges)) {
1080                         par.setChange(cur.pos(), Change(Change::DELETED));
1081                         cur.forwardPos();
1082                         needsUpdate = true;
1083                 } else {
1084                         setCursorIntern(cur, cur.pit() + 1, 0);
1085                         needsUpdate = backspacePos0(cur);
1086                 }
1087         }
1088
1089         needsUpdate |= handleBibitems(cur);
1090
1091         if (needsUpdate) {
1092                 // Make sure the cursor is correct. Is this really needed?
1093                 // No, not really... at least not here!
1094                 cur.text()->setCursor(cur.top(), cur.pit(), cur.pos());
1095                 cur.checkBufferStructure();
1096         }
1097
1098         return needsUpdate;
1099 }
1100
1101
1102 bool Text::backspacePos0(Cursor & cur)
1103 {
1104         LASSERT(this == cur.text(), /**/);
1105         if (cur.pit() == 0)
1106                 return false;
1107
1108         bool needsUpdate = false;
1109
1110         BufferParams const & bufparams = cur.buffer()->params();
1111         DocumentClass const & tclass = bufparams.documentClass();
1112         ParagraphList & plist = cur.text()->paragraphs();
1113         Paragraph const & par = cur.paragraph();
1114         Cursor prevcur = cur;
1115         --prevcur.pit();
1116         prevcur.pos() = prevcur.lastpos();
1117         Paragraph const & prevpar = prevcur.paragraph();
1118
1119         // is it an empty paragraph?
1120         if (cur.lastpos() == 0
1121             || (cur.lastpos() == 1 && par.isSeparator(0))) {
1122                 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1123                 plist.erase(boost::next(plist.begin(), cur.pit()));
1124                 needsUpdate = true;
1125         }
1126         // is previous par empty?
1127         else if (prevcur.lastpos() == 0
1128                  || (prevcur.lastpos() == 1 && prevpar.isSeparator(0))) {
1129                 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1130                 plist.erase(boost::next(plist.begin(), prevcur.pit()));
1131                 needsUpdate = true;
1132         }
1133         // Pasting is not allowed, if the paragraphs have different
1134         // layouts. I think it is a real bug of all other
1135         // word processors to allow it. It confuses the user.
1136         // Correction: Pasting is always allowed with standard-layout
1137         // or the empty layout.
1138         else if (par.layout() == prevpar.layout()
1139                  || tclass.isDefaultLayout(par.layout())
1140                  || tclass.isPlainLayout(par.layout())) {
1141                 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
1142                 mergeParagraph(bufparams, plist, prevcur.pit());
1143                 needsUpdate = true;
1144         }
1145
1146         if (needsUpdate) {
1147                 cur.buffer()->updateLabels();
1148                 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1149         }
1150
1151         return needsUpdate;
1152 }
1153
1154
1155 bool Text::backspace(Cursor & cur)
1156 {
1157         LASSERT(this == cur.text(), /**/);
1158         bool needsUpdate = false;
1159         if (cur.pos() == 0) {
1160                 if (cur.pit() == 0)
1161                         return dissolveInset(cur);
1162
1163                 Paragraph & prev_par = pars_[cur.pit() - 1];
1164
1165                 if (!prev_par.isMergedOnEndOfParDeletion(cur.buffer()->params().trackChanges)) {
1166                         prev_par.setChange(prev_par.size(), Change(Change::DELETED));
1167                         setCursorIntern(cur, cur.pit() - 1, prev_par.size());
1168                         return true;
1169                 }
1170                 // The cursor is at the beginning of a paragraph, so
1171                 // the backspace will collapse two paragraphs into one.
1172                 needsUpdate = backspacePos0(cur);
1173
1174         } else {
1175                 // this is the code for a normal backspace, not pasting
1176                 // any paragraphs
1177                 cur.recordUndo(DELETE_UNDO);
1178                 // We used to do cursorBackwardIntern() here, but it is
1179                 // not a good idea since it triggers the auto-delete
1180                 // mechanism. So we do a cursorBackwardIntern()-lite,
1181                 // without the dreaded mechanism. (JMarc)
1182                 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1183                                 false, cur.boundary());
1184                 bool const was_inset = cur.paragraph().isInset(cur.pos());
1185                 cur.paragraph().eraseChar(cur.pos(), cur.buffer()->params().trackChanges);
1186                 if (was_inset)
1187                         cur.buffer()->updateLabels();
1188                 else
1189                         cur.checkBufferStructure();
1190         }
1191
1192         if (cur.pos() == cur.lastpos())
1193                 cur.setCurrentFont();
1194
1195         needsUpdate |= handleBibitems(cur);
1196
1197         // A singlePar update is not enough in this case.
1198 //              cur.updateFlags(Update::Force);
1199         setCursor(cur.top(), cur.pit(), cur.pos());
1200
1201         return needsUpdate;
1202 }
1203
1204
1205 bool Text::dissolveInset(Cursor & cur)
1206 {
1207         LASSERT(this == cur.text(), return false);
1208
1209         if (isMainText(cur.bv().buffer()) || cur.inset().nargs() != 1)
1210                 return false;
1211
1212         cur.recordUndoInset();
1213         cur.setMark(false);
1214         cur.selHandle(false);
1215         // save position
1216         pos_type spos = cur.pos();
1217         pit_type spit = cur.pit();
1218         ParagraphList plist;
1219         if (cur.lastpit() != 0 || cur.lastpos() != 0)
1220                 plist = paragraphs();
1221         cur.popBackward();
1222         // store cursor offset
1223         if (spit == 0)
1224                 spos += cur.pos();
1225         spit += cur.pit();
1226         Buffer & b = *cur.buffer();
1227         cur.paragraph().eraseChar(cur.pos(), b.params().trackChanges);
1228         if (!plist.empty()) {
1229                 // ERT paragraphs have the Language latex_language.
1230                 // This is invalid outside of ERT, so we need to
1231                 // change it to the buffer language.
1232                 ParagraphList::iterator it = plist.begin();
1233                 ParagraphList::iterator it_end = plist.end();
1234                 for (; it != it_end; it++)
1235                         it->changeLanguage(b.params(), latex_language, b.language());
1236
1237                 pasteParagraphList(cur, plist, b.params().documentClassPtr(),
1238                                    b.errorList("Paste"));
1239                 // restore position
1240                 cur.pit() = min(cur.lastpit(), spit);
1241                 cur.pos() = min(cur.lastpos(), spos);
1242         }
1243         cur.clearSelection();
1244         cur.resetAnchor();
1245         return true;
1246 }
1247
1248
1249 void Text::getWord(CursorSlice & from, CursorSlice & to,
1250         word_location const loc) const
1251 {
1252         to = from;
1253         pars_[to.pit()].locateWord(from.pos(), to.pos(), loc);
1254 }
1255
1256
1257 void Text::write(Buffer const & buf, ostream & os) const
1258 {
1259         ParagraphList::const_iterator pit = paragraphs().begin();
1260         ParagraphList::const_iterator end = paragraphs().end();
1261         depth_type dth = 0;
1262         for (; pit != end; ++pit)
1263                 pit->write(os, buf.params(), dth);
1264
1265         // Close begin_deeper
1266         for(; dth > 0; --dth)
1267                 os << "\n\\end_deeper";
1268 }
1269
1270
1271 bool Text::read(Buffer const & buf, Lexer & lex, 
1272                 ErrorList & errorList, InsetText * insetPtr)
1273 {
1274         depth_type depth = 0;
1275         bool res = true;
1276
1277         while (lex.isOK()) {
1278                 lex.nextToken();
1279                 string const token = lex.getString();
1280
1281                 if (token.empty())
1282                         continue;
1283
1284                 if (token == "\\end_inset")
1285                         break;
1286
1287                 if (token == "\\end_body")
1288                         continue;
1289
1290                 if (token == "\\begin_body")
1291                         continue;
1292
1293                 if (token == "\\end_document") {
1294                         res = false;
1295                         break;
1296                 }
1297
1298                 if (token == "\\begin_layout") {
1299                         lex.pushToken(token);
1300
1301                         Paragraph par;
1302                         par.setInsetOwner(insetPtr);
1303                         par.params().depth(depth);
1304                         par.setFont(0, Font(inherit_font, buf.params().language));
1305                         pars_.push_back(par);
1306
1307                         // FIXME: goddamn InsetTabular makes us pass a Buffer
1308                         // not BufferParams
1309                         lyx::readParagraph(buf, pars_.back(), lex, errorList);
1310
1311                         // register the words in the global word list
1312                         CursorSlice sl = CursorSlice(*insetPtr);
1313                         sl.pit() = pars_.size() - 1;
1314                         pars_.back().updateWords();
1315                 } else if (token == "\\begin_deeper") {
1316                         ++depth;
1317                 } else if (token == "\\end_deeper") {
1318                         if (!depth)
1319                                 lex.printError("\\end_deeper: " "depth is already null");
1320                         else
1321                                 --depth;
1322                 } else {
1323                         LYXERR0("Handling unknown body token: `" << token << '\'');
1324                 }
1325         }
1326
1327         // avoid a crash on weird documents (bug 4859)
1328         if (pars_.empty()) {
1329                 Paragraph par;
1330                 par.setInsetOwner(insetPtr);
1331                 par.params().depth(depth);
1332                 par.setFont(0, Font(inherit_font, 
1333                                     buf.params().language));
1334                 par.setPlainOrDefaultLayout(buf.params().documentClass());
1335                 pars_.push_back(par);
1336         }
1337         
1338         return res;
1339 }
1340
1341 // Returns the current font and depth as a message.
1342 docstring Text::currentState(Cursor const & cur) const
1343 {
1344         LASSERT(this == cur.text(), /**/);
1345         Buffer & buf = *cur.buffer();
1346         Paragraph const & par = cur.paragraph();
1347         odocstringstream os;
1348
1349         if (buf.params().trackChanges)
1350                 os << _("[Change Tracking] ");
1351
1352         Change change = par.lookupChange(cur.pos());
1353
1354         if (change.type != Change::UNCHANGED) {
1355                 Author const & a = buf.params().authors().get(change.author);
1356                 os << _("Change: ") << a.name();
1357                 if (!a.email().empty())
1358                         os << " (" << a.email() << ")";
1359                 // FIXME ctime is english, we should translate that
1360                 os << _(" at ") << ctime(&change.changetime);
1361                 os << " : ";
1362         }
1363
1364         // I think we should only show changes from the default
1365         // font. (Asger)
1366         // No, from the document font (MV)
1367         Font font = cur.real_current_font;
1368         font.fontInfo().reduce(buf.params().getFont().fontInfo());
1369
1370         os << bformat(_("Font: %1$s"), font.stateText(&buf.params()));
1371
1372         // The paragraph depth
1373         int depth = cur.paragraph().getDepth();
1374         if (depth > 0)
1375                 os << bformat(_(", Depth: %1$d"), depth);
1376
1377         // The paragraph spacing, but only if different from
1378         // buffer spacing.
1379         Spacing const & spacing = par.params().spacing();
1380         if (!spacing.isDefault()) {
1381                 os << _(", Spacing: ");
1382                 switch (spacing.getSpace()) {
1383                 case Spacing::Single:
1384                         os << _("Single");
1385                         break;
1386                 case Spacing::Onehalf:
1387                         os << _("OneHalf");
1388                         break;
1389                 case Spacing::Double:
1390                         os << _("Double");
1391                         break;
1392                 case Spacing::Other:
1393                         os << _("Other (") << from_ascii(spacing.getValueAsString()) << ')';
1394                         break;
1395                 case Spacing::Default:
1396                         // should never happen, do nothing
1397                         break;
1398                 }
1399         }
1400
1401 #ifdef DEVEL_VERSION
1402         os << _(", Inset: ") << &cur.inset();
1403         os << _(", Paragraph: ") << cur.pit();
1404         os << _(", Id: ") << par.id();
1405         os << _(", Position: ") << cur.pos();
1406         // FIXME: Why is the check for par.size() needed?
1407         // We are called with cur.pos() == par.size() quite often.
1408         if (!par.empty() && cur.pos() < par.size()) {
1409                 // Force output of code point, not character
1410                 size_t const c = par.getChar(cur.pos());
1411                 os << _(", Char: 0x") << hex << c;
1412         }
1413         os << _(", Boundary: ") << cur.boundary();
1414 //      Row & row = cur.textRow();
1415 //      os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
1416 #endif
1417         return os.str();
1418 }
1419
1420
1421 docstring Text::getPossibleLabel(Cursor const & cur) const
1422 {
1423         pit_type pit = cur.pit();
1424
1425         Layout const * layout = &(pars_[pit].layout());
1426
1427         docstring text;
1428         docstring par_text = pars_[pit].asString();
1429         string piece;
1430         // the return string of math matrices might contain linebreaks
1431         par_text = subst(par_text, '\n', '-');
1432         for (int i = 0; i < lyxrc.label_init_length; ++i) {
1433                 if (par_text.empty())
1434                         break;
1435                 docstring head;
1436                 par_text = split(par_text, head, ' ');
1437                 // Is it legal to use spaces in labels ?
1438                 if (i > 0)
1439                         text += '-';
1440                 text += head;
1441         }
1442
1443         // No need for a prefix if the user said so.
1444         if (lyxrc.label_init_length <= 0)
1445                 return text;
1446
1447         // Will contain the label type.
1448         docstring name;
1449
1450         // For section, subsection, etc...
1451         if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
1452                 Layout const * layout2 = &(pars_[pit - 1].layout());
1453                 if (layout2->latextype != LATEX_PARAGRAPH) {
1454                         --pit;
1455                         layout = layout2;
1456                 }
1457         }
1458         if (layout->latextype != LATEX_PARAGRAPH)
1459                 name = from_ascii(layout->latexname());
1460
1461         // for captions, we just take the caption type
1462         Inset * caption_inset = cur.innerInsetOfType(CAPTION_CODE);
1463         if (caption_inset)
1464                 name = from_ascii(static_cast<InsetCaption *>(caption_inset)->type());
1465
1466         // If none of the above worked, we'll see if we're inside various
1467         // types of insets and take our abbreviation from them.
1468         if (name.empty()) {
1469                 InsetCode const codes[] = {
1470                         FLOAT_CODE,
1471                         WRAP_CODE,
1472                         FOOT_CODE
1473                 };
1474                 for (unsigned int i = 0; i < (sizeof codes / sizeof codes[0]); ++i) {
1475                         Inset * float_inset = cur.innerInsetOfType(codes[i]);
1476                         if (float_inset) {
1477                                 name = float_inset->name();
1478                                 break;
1479                         }
1480                 }
1481         }
1482
1483         // Create a correct prefix for prettyref
1484         if (name == "theorem")
1485                 name = from_ascii("thm");
1486         else if (name == "Foot")
1487                 name = from_ascii("fn");
1488         else if (name == "listing")
1489                 name = from_ascii("lst");
1490
1491         if (!name.empty())
1492                 text = name.substr(0, 3) + ':' + text;
1493
1494         return text;
1495 }
1496
1497
1498 docstring Text::asString(int options) const
1499 {
1500         return asString(0, pars_.size(), options);
1501 }
1502
1503
1504 docstring Text::asString(pit_type beg, pit_type end, int options) const
1505 {
1506         size_t i = size_t(beg);
1507         docstring str = pars_[i].asString(options);
1508         for (++i; i != size_t(end); ++i) {
1509                 str += '\n';
1510                 str += pars_[i].asString(options);
1511         }
1512         return str;
1513 }
1514
1515
1516
1517 void Text::charsTranspose(Cursor & cur)
1518 {
1519         LASSERT(this == cur.text(), /**/);
1520
1521         pos_type pos = cur.pos();
1522
1523         // If cursor is at beginning or end of paragraph, do nothing.
1524         if (pos == cur.lastpos() || pos == 0)
1525                 return;
1526
1527         Paragraph & par = cur.paragraph();
1528
1529         // Get the positions of the characters to be transposed.
1530         pos_type pos1 = pos - 1;
1531         pos_type pos2 = pos;
1532
1533         // In change tracking mode, ignore deleted characters.
1534         while (pos2 < cur.lastpos() && par.isDeleted(pos2))
1535                 ++pos2;
1536         if (pos2 == cur.lastpos())
1537                 return;
1538
1539         while (pos1 >= 0 && par.isDeleted(pos1))
1540                 --pos1;
1541         if (pos1 < 0)
1542                 return;
1543
1544         // Don't do anything if one of the "characters" is not regular text.
1545         if (par.isInset(pos1) || par.isInset(pos2))
1546                 return;
1547
1548         // Store the characters to be transposed (including font information).
1549         char_type const char1 = par.getChar(pos1);
1550         Font const font1 =
1551                 par.getFontSettings(cur.buffer()->params(), pos1);
1552
1553         char_type const char2 = par.getChar(pos2);
1554         Font const font2 =
1555                 par.getFontSettings(cur.buffer()->params(), pos2);
1556
1557         // And finally, we are ready to perform the transposition.
1558         // Track the changes if Change Tracking is enabled.
1559         bool const trackChanges = cur.buffer()->params().trackChanges;
1560
1561         cur.recordUndo();
1562
1563         par.eraseChar(pos2, trackChanges);
1564         par.eraseChar(pos1, trackChanges);
1565         par.insertChar(pos1, char2, font2, trackChanges);
1566         par.insertChar(pos2, char1, font1, trackChanges);
1567
1568         cur.checkBufferStructure();
1569
1570         // After the transposition, move cursor to after the transposition.
1571         setCursor(cur, cur.pit(), pos2);
1572         cur.forwardPos();
1573 }
1574
1575
1576 DocIterator Text::macrocontextPosition() const
1577 {
1578         return macrocontext_position_;
1579 }
1580
1581
1582 void Text::setMacrocontextPosition(DocIterator const & pos)
1583 {
1584         macrocontext_position_ = pos;
1585 }
1586
1587
1588 docstring Text::previousWord(CursorSlice const & sl) const
1589 {
1590         CursorSlice from = sl;
1591         CursorSlice to = sl;
1592         getWord(from, to, PREVIOUS_WORD);
1593         if (sl == from || to == from)
1594                 return docstring();
1595         
1596         Paragraph const & par = sl.paragraph();
1597         return par.asString(from.pos(), to.pos());
1598 }
1599
1600
1601 bool Text::completionSupported(Cursor const & cur) const
1602 {
1603         Paragraph const & par = cur.paragraph();
1604         return cur.pos() > 0
1605                 && (cur.pos() >= par.size() || par.isWordSeparator(cur.pos()))
1606                 && !par.isWordSeparator(cur.pos() - 1);
1607 }
1608
1609
1610 CompletionList const * Text::createCompletionList(Cursor const & cur) const
1611 {
1612         return new TextCompletionList(cur);
1613 }
1614
1615
1616 bool Text::insertCompletion(Cursor & cur, docstring const & s, bool /*finished*/)
1617 {       
1618         LASSERT(cur.bv().cursor() == cur, /**/);
1619         cur.insert(s);
1620         cur.bv().cursor() = cur;
1621         if (!(cur.disp_.update() & Update::Force))
1622                 cur.updateFlags(cur.disp_.update() | Update::SinglePar);
1623         return true;
1624 }
1625         
1626         
1627 docstring Text::completionPrefix(Cursor const & cur) const
1628 {
1629         return previousWord(cur.top());
1630 }
1631
1632 } // namespace lyx