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