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