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