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