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