whitespace.
[lyx.git] / src / Text.cpp
blob91b8a5f02a456ad58c5df78fd1736cfc0c0e8030
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.
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
16 * Full author contact details are available in file CREDITS.
19 #include <config.h>
21 #include "Text.h"
23 #include "Author.h"
24 #include "Buffer.h"
25 #include "buffer_funcs.h"
26 #include "BufferParams.h"
27 #include "BufferView.h"
28 #include "Changes.h"
29 #include "CompletionList.h"
30 #include "Cursor.h"
31 #include "CutAndPaste.h"
32 #include "DispatchResult.h"
33 #include "Encoding.h"
34 #include "ErrorList.h"
35 #include "FuncRequest.h"
36 #include "factory.h"
37 #include "Language.h"
38 #include "Length.h"
39 #include "Lexer.h"
40 #include "LyXRC.h"
41 #include "Paragraph.h"
42 #include "paragraph_funcs.h"
43 #include "ParagraphParameters.h"
44 #include "ParIterator.h"
45 #include "TextClass.h"
46 #include "TextMetrics.h"
47 #include "VSpace.h"
48 #include "WordLangTuple.h"
49 #include "WordList.h"
51 #include "insets/InsetText.h"
52 #include "insets/InsetBibitem.h"
53 #include "insets/InsetCaption.h"
54 #include "insets/InsetLine.h"
55 #include "insets/InsetNewline.h"
56 #include "insets/InsetNewpage.h"
57 #include "insets/InsetOptArg.h"
58 #include "insets/InsetSpace.h"
59 #include "insets/InsetSpecialChar.h"
60 #include "insets/InsetTabular.h"
62 #include "support/convert.h"
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"
70 #include <boost/next_prior.hpp>
72 #include <sstream>
74 using namespace std;
75 using namespace lyx::support;
77 namespace lyx {
79 using cap::cutSelection;
80 using cap::pasteParagraphList;
82 namespace {
84 void readParToken(Buffer const & buf, Paragraph & par, Lexer & lex,
85 string const & token, Font & font, Change & change, ErrorList & errorList)
87 BufferParams const & bp = buf.params();
89 if (token[0] != '\\') {
90 docstring dstr = lex.getDocString();
91 par.appendString(dstr, font, change);
93 } else if (token == "\\begin_layout") {
94 lex.eatLine();
95 docstring layoutname = lex.getDocString();
97 font = Font(inherit_font, bp.language);
98 change = Change(Change::UNCHANGED);
100 DocumentClass const & tclass = bp.documentClass();
102 if (layoutname.empty())
103 layoutname = tclass.defaultLayoutName();
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();
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);
124 par.setLayout(bp.documentClass()[layoutname]);
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()]);
131 par.params().read(lex);
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()));
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'");
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();
181 if (tok == "under")
182 font.fontInfo().setUnderbar(FONT_ON);
183 else if (tok == "no")
184 font.fontInfo().setUnderbar(FONT_OFF);
185 else if (tok == "default")
186 font.fontInfo().setUnderbar(FONT_INHERIT);
187 else
188 lex.printError("Unknown bar font flag "
189 "`$$Token'");
190 } else if (token == "\\noun") {
191 lex.next();
192 font.fontInfo().setNoun(font.setLyXMisc(lex.getString()));
193 } else if (token == "\\color") {
194 lex.next();
195 setLyXColor(lex.getString(), font.fontInfo());
196 } else if (token == "\\SpecialChar") {
197 auto_ptr<Inset> inset;
198 inset.reset(new InsetSpecialChar);
199 inset->read(lex);
200 par.insertInset(par.size(), inset.release(),
201 font, change);
202 } else if (token == "\\backslash") {
203 par.appendChar('\\', font, change);
204 } else if (token == "\\LyXTable") {
205 auto_ptr<Inset> inset(new InsetTabular(const_cast<Buffer &>(buf)));
206 inset->read(lex);
207 par.insertInset(par.size(), inset.release(), font, change);
208 } else if (token == "\\lyxline") {
209 par.insertInset(par.size(), new InsetLine, font, change);
210 } else if (token == "\\change_unchanged") {
211 change = Change(Change::UNCHANGED);
212 } else if (token == "\\change_inserted") {
213 lex.eatLine();
214 istringstream is(lex.getString());
215 unsigned int aid;
216 time_t ct;
217 is >> aid >> ct;
218 if (aid >= bp.author_map.size()) {
219 errorList.push_back(ErrorItem(_("Change tracking error"),
220 bformat(_("Unknown author index for insertion: %1$d\n"), aid),
221 par.id(), 0, par.size()));
222 change = Change(Change::UNCHANGED);
223 } else
224 change = Change(Change::INSERTED, bp.author_map[aid], ct);
225 } else if (token == "\\change_deleted") {
226 lex.eatLine();
227 istringstream is(lex.getString());
228 unsigned int aid;
229 time_t ct;
230 is >> aid >> ct;
231 if (aid >= bp.author_map.size()) {
232 errorList.push_back(ErrorItem(_("Change tracking error"),
233 bformat(_("Unknown author index for deletion: %1$d\n"), aid),
234 par.id(), 0, par.size()));
235 change = Change(Change::UNCHANGED);
236 } else
237 change = Change(Change::DELETED, bp.author_map[aid], ct);
238 } else {
239 lex.eatLine();
240 errorList.push_back(ErrorItem(_("Unknown token"),
241 bformat(_("Unknown token: %1$s %2$s\n"), from_utf8(token),
242 lex.getDocString()),
243 par.id(), 0, par.size()));
248 void readParagraph(Buffer const & buf, Paragraph & par, Lexer & lex,
249 ErrorList & errorList)
251 lex.nextToken();
252 string token = lex.getString();
253 Font font;
254 Change change(Change::UNCHANGED);
256 while (lex.isOK()) {
257 readParToken(buf, par, lex, token, font, change, errorList);
259 lex.nextToken();
260 token = lex.getString();
262 if (token.empty())
263 continue;
265 if (token == "\\end_layout") {
266 //Ok, paragraph finished
267 break;
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;
281 // Final change goes to paragraph break:
282 par.setChange(par.size(), change);
284 // Initialize begin_of_body_ on load; redoParagraph maintains
285 par.setBeginOfBody();
289 } // namespace anon
291 class TextCompletionList : public CompletionList
293 public:
295 TextCompletionList(Cursor const & cur)
296 : buffer_(cur.buffer()), pos_(0)
299 virtual ~TextCompletionList() {}
302 virtual bool sorted() const { return true; }
304 virtual size_t size() const
306 return theWordList().size();
309 virtual docstring const & data(size_t idx) const
311 return theWordList().word(idx);
314 private:
316 Buffer const * buffer_;
318 size_t pos_;
322 bool Text::empty() const
324 return pars_.empty() || (pars_.size() == 1 && pars_[0].empty()
325 // FIXME: Should we consider the labeled type as empty too?
326 && pars_[0].layout().labeltype == LABEL_NO_LABEL);
330 double Text::spacing(Buffer const & buffer, Paragraph const & par) const
332 if (par.params().spacing().isDefault())
333 return buffer.params().spacing().getValue();
334 return par.params().spacing().getValue();
338 void Text::breakParagraph(Cursor & cur, bool inverse_logic)
340 LASSERT(this == cur.text(), /**/);
342 Paragraph & cpar = cur.paragraph();
343 pit_type cpit = cur.pit();
345 DocumentClass const & tclass = cur.buffer()->params().documentClass();
346 Layout const & layout = cpar.layout();
348 // this is only allowed, if the current paragraph is not empty
349 // or caption and if it has not the keepempty flag active
350 if (cur.lastpos() == 0 && !cpar.allowEmpty() &&
351 layout.labeltype != LABEL_SENSITIVE)
352 return;
354 // a layout change may affect also the following paragraph
355 recUndo(cur, cur.pit(), undoSpan(cur.pit()) - 1);
357 // Always break behind a space
358 // It is better to erase the space (Dekel)
359 if (cur.pos() != cur.lastpos() && cpar.isLineSeparator(cur.pos()))
360 cpar.eraseChar(cur.pos(), cur.buffer()->params().trackChanges);
362 // What should the layout for the new paragraph be?
363 bool keep_layout = inverse_logic ?
364 !layout.isEnvironment()
365 : layout.isEnvironment();
367 // We need to remember this before we break the paragraph, because
368 // that invalidates the layout variable
369 bool sensitive = layout.labeltype == LABEL_SENSITIVE;
371 // we need to set this before we insert the paragraph.
372 bool const isempty = cpar.allowEmpty() && cpar.empty();
374 lyx::breakParagraph(cur.buffer()->params(), paragraphs(), cpit,
375 cur.pos(), keep_layout);
377 // After this, neither paragraph contains any rows!
379 cpit = cur.pit();
380 pit_type next_par = cpit + 1;
382 // well this is the caption hack since one caption is really enough
383 if (sensitive) {
384 if (cur.pos() == 0)
385 // set to standard-layout
386 //FIXME Check if this should be plainLayout() in some cases
387 pars_[cpit].applyLayout(tclass.defaultLayout());
388 else
389 // set to standard-layout
390 //FIXME Check if this should be plainLayout() in some cases
391 pars_[next_par].applyLayout(tclass.defaultLayout());
394 while (!pars_[next_par].empty() && pars_[next_par].isNewline(0)) {
395 if (!pars_[next_par].eraseChar(0, cur.buffer()->params().trackChanges))
396 break; // the character couldn't be deleted physically due to change tracking
399 cur.buffer()->updateLabels();
401 // A singlePar update is not enough in this case.
402 cur.updateFlags(Update::Force);
404 // This check is necessary. Otherwise the new empty paragraph will
405 // be deleted automatically. And it is more friendly for the user!
406 if (cur.pos() != 0 || isempty)
407 setCursor(cur, cur.pit() + 1, 0);
408 else
409 setCursor(cur, cur.pit(), 0);
413 // insert a character, moves all the following breaks in the
414 // same Paragraph one to the right and make a rebreak
415 void Text::insertChar(Cursor & cur, char_type c)
417 LASSERT(this == cur.text(), /**/);
419 cur.recordUndo(INSERT_UNDO);
421 TextMetrics const & tm = cur.bv().textMetrics(this);
422 Buffer const & buffer = *cur.buffer();
423 Paragraph & par = cur.paragraph();
424 // try to remove this
425 pit_type const pit = cur.pit();
427 bool const freeSpacing = par.layout().free_spacing ||
428 par.isFreeSpacing();
430 if (lyxrc.auto_number) {
431 static docstring const number_operators = from_ascii("+-/*");
432 static docstring const number_unary_operators = from_ascii("+-");
433 static docstring const number_seperators = from_ascii(".,:");
435 if (cur.current_font.fontInfo().number() == FONT_ON) {
436 if (!isDigit(c) && !contains(number_operators, c) &&
437 !(contains(number_seperators, c) &&
438 cur.pos() != 0 &&
439 cur.pos() != cur.lastpos() &&
440 tm.displayFont(pit, cur.pos()).fontInfo().number() == FONT_ON &&
441 tm.displayFont(pit, cur.pos() - 1).fontInfo().number() == FONT_ON)
443 number(cur); // Set current_font.number to OFF
444 } else if (isDigit(c) &&
445 cur.real_current_font.isVisibleRightToLeft()) {
446 number(cur); // Set current_font.number to ON
448 if (cur.pos() != 0) {
449 char_type const c = par.getChar(cur.pos() - 1);
450 if (contains(number_unary_operators, c) &&
451 (cur.pos() == 1
452 || par.isSeparator(cur.pos() - 2)
453 || par.isNewline(cur.pos() - 2))
455 setCharFont(buffer, pit, cur.pos() - 1, cur.current_font,
456 tm.font_);
457 } else if (contains(number_seperators, c)
458 && cur.pos() >= 2
459 && tm.displayFont(pit, cur.pos() - 2).fontInfo().number() == FONT_ON) {
460 setCharFont(buffer, pit, cur.pos() - 1, cur.current_font,
461 tm.font_);
467 // In Bidi text, we want spaces to be treated in a special way: spaces
468 // which are between words in different languages should get the
469 // paragraph's language; otherwise, spaces should keep the language
470 // they were originally typed in. This is only in effect while typing;
471 // after the text is already typed in, the user can always go back and
472 // explicitly set the language of a space as desired. But 99.9% of the
473 // time, what we're doing here is what the user actually meant.
475 // The following cases are the ones in which the language of the space
476 // should be changed to match that of the containing paragraph. In the
477 // depictions, lowercase is LTR, uppercase is RTL, underscore (_)
478 // represents a space, pipe (|) represents the cursor position (so the
479 // character before it is the one just typed in). The different cases
480 // are depicted logically (not visually), from left to right:
482 // 1. A_a|
483 // 2. a_A|
485 // Theoretically, there are other situations that we should, perhaps, deal
486 // with (e.g.: a|_A, A|_a). In practice, though, there really isn't any
487 // point (to understand why, just try to create this situation...).
489 if ((cur.pos() >= 2) && (par.isLineSeparator(cur.pos() - 1))) {
490 // get font in front and behind the space in question. But do NOT
491 // use getFont(cur.pos()) because the character c is not inserted yet
492 Font const pre_space_font = tm.displayFont(cur.pit(), cur.pos() - 2);
493 Font const & post_space_font = cur.real_current_font;
494 bool pre_space_rtl = pre_space_font.isVisibleRightToLeft();
495 bool post_space_rtl = post_space_font.isVisibleRightToLeft();
497 if (pre_space_rtl != post_space_rtl) {
498 // Set the space's language to match the language of the
499 // adjacent character whose direction is the paragraph's
500 // direction; don't touch other properties of the font
501 Language const * lang =
502 (pre_space_rtl == par.isRTL(buffer.params())) ?
503 pre_space_font.language() : post_space_font.language();
505 Font space_font = tm.displayFont(cur.pit(), cur.pos() - 1);
506 space_font.setLanguage(lang);
507 par.setFont(cur.pos() - 1, space_font);
511 // Next check, if there will be two blanks together or a blank at
512 // the beginning of a paragraph.
513 // I decided to handle blanks like normal characters, the main
514 // difference are the special checks when calculating the row.fill
515 // (blank does not count at the end of a row) and the check here
517 // When the free-spacing option is set for the current layout,
518 // disable the double-space checking
519 if (!freeSpacing && isLineSeparatorChar(c)) {
520 if (cur.pos() == 0) {
521 static bool sent_space_message = false;
522 if (!sent_space_message) {
523 cur.message(_("You cannot insert a space at the "
524 "beginning of a paragraph. Please read the Tutorial."));
525 sent_space_message = true;
527 return;
529 LASSERT(cur.pos() > 0, /**/);
530 if ((par.isLineSeparator(cur.pos() - 1) || par.isNewline(cur.pos() - 1))
531 && !par.isDeleted(cur.pos() - 1)) {
532 static bool sent_space_message = false;
533 if (!sent_space_message) {
534 cur.message(_("You cannot type two spaces this way. "
535 "Please read the Tutorial."));
536 sent_space_message = true;
538 return;
542 par.insertChar(cur.pos(), c, cur.current_font,
543 cur.buffer()->params().trackChanges);
544 cur.checkBufferStructure();
546 // cur.updateFlags(Update::Force);
547 setCursor(cur.top(), cur.pit(), cur.pos() + 1);
548 charInserted(cur);
552 void Text::charInserted(Cursor & cur)
554 Paragraph & par = cur.paragraph();
556 // Here we call finishUndo for every 20 characters inserted.
557 // This is from my experience how emacs does it. (Lgb)
558 static unsigned int counter;
559 if (counter < 20) {
560 ++counter;
561 } else {
562 cur.finishUndo();
563 counter = 0;
566 // register word if a non-letter was entered
567 if (cur.pos() > 1
568 && par.isLetter(cur.pos() - 2)
569 && !par.isLetter(cur.pos() - 1)) {
570 // get the word in front of cursor
571 LASSERT(this == cur.text(), /**/);
572 cur.paragraph().updateWords(cur.top());
577 // the cursor set functions have a special mechanism. When they
578 // realize, that you left an empty paragraph, they will delete it.
580 bool Text::cursorForwardOneWord(Cursor & cur)
582 LASSERT(this == cur.text(), /**/);
584 pos_type const lastpos = cur.lastpos();
585 pit_type pit = cur.pit();
586 pos_type pos = cur.pos();
587 Paragraph const & par = cur.paragraph();
589 // Paragraph boundary is a word boundary
590 if (pos == lastpos) {
591 if (pit != cur.lastpit())
592 return setCursor(cur, pit + 1, 0);
593 else
594 return false;
597 if (lyxrc.mac_like_word_movement) {
598 // Skip through trailing punctuation and spaces.
599 while (pos != lastpos && (par.isChar(pos) || par.isSpace(pos)))
600 ++pos;
602 // Skip over either a non-char inset or a full word
603 if (pos != lastpos && !par.isLetter(pos))
604 ++pos;
605 else while (pos != lastpos && par.isLetter(pos))
606 ++pos;
607 } else {
608 LASSERT(pos < lastpos, /**/); // see above
609 if (par.isLetter(pos))
610 while (pos != lastpos && par.isLetter(pos))
611 ++pos;
612 else if (par.isChar(pos))
613 while (pos != lastpos && par.isChar(pos))
614 ++pos;
615 else if (!par.isSpace(pos)) // non-char inset
616 ++pos;
618 // Skip over white space
619 while (pos != lastpos && par.isSpace(pos))
620 ++pos;
623 return setCursor(cur, pit, pos);
627 bool Text::cursorBackwardOneWord(Cursor & cur)
629 LASSERT(this == cur.text(), /**/);
631 pit_type pit = cur.pit();
632 pos_type pos = cur.pos();
633 Paragraph & par = cur.paragraph();
635 // Paragraph boundary is a word boundary
636 if (pos == 0 && pit != 0)
637 return setCursor(cur, pit - 1, getPar(pit - 1).size());
639 if (lyxrc.mac_like_word_movement) {
640 // Skip through punctuation and spaces.
641 while (pos != 0 && (par.isChar(pos - 1) || par.isSpace(pos - 1)))
642 --pos;
644 // Skip over either a non-char inset or a full word
645 if (pos != 0 && !par.isLetter(pos - 1) && !par.isChar(pos - 1))
646 --pos;
647 else while (pos != 0 && par.isLetter(pos - 1))
648 --pos;
649 } else {
650 // Skip over white space
651 while (pos != 0 && par.isSpace(pos - 1))
652 --pos;
654 if (pos != 0 && par.isLetter(pos - 1))
655 while (pos != 0 && par.isLetter(pos - 1))
656 --pos;
657 else if (pos != 0 && par.isChar(pos - 1))
658 while (pos != 0 && par.isChar(pos - 1))
659 --pos;
660 else if (pos != 0 && !par.isSpace(pos - 1)) // non-char inset
661 --pos;
664 return setCursor(cur, pit, pos);
668 bool Text::cursorVisLeftOneWord(Cursor & cur)
670 LASSERT(this == cur.text(), /**/);
672 pos_type left_pos, right_pos;
673 bool left_is_letter, right_is_letter;
675 Cursor temp_cur = cur;
677 // always try to move at least once...
678 while (temp_cur.posVisLeft(true /* skip_inset */)) {
680 // collect some information about current cursor position
681 temp_cur.getSurroundingPos(left_pos, right_pos);
682 left_is_letter =
683 (left_pos > -1 ? temp_cur.paragraph().isLetter(left_pos) : false);
684 right_is_letter =
685 (right_pos > -1 ? temp_cur.paragraph().isLetter(right_pos) : false);
687 // if we're not at a letter/non-letter boundary, continue moving
688 if (left_is_letter == right_is_letter)
689 continue;
691 // we should stop when we have an LTR word on our right or an RTL word
692 // on our left
693 if ((left_is_letter && temp_cur.paragraph().getFontSettings(
694 temp_cur.buffer()->params(), left_pos).isRightToLeft())
695 || (right_is_letter && !temp_cur.paragraph().getFontSettings(
696 temp_cur.buffer()->params(), right_pos).isRightToLeft()))
697 break;
700 return setCursor(cur, temp_cur.pit(), temp_cur.pos(),
701 true, temp_cur.boundary());
705 bool Text::cursorVisRightOneWord(Cursor & cur)
707 LASSERT(this == cur.text(), /**/);
709 pos_type left_pos, right_pos;
710 bool left_is_letter, right_is_letter;
712 Cursor temp_cur = cur;
714 // always try to move at least once...
715 while (temp_cur.posVisRight(true /* skip_inset */)) {
717 // collect some information about current cursor position
718 temp_cur.getSurroundingPos(left_pos, right_pos);
719 left_is_letter =
720 (left_pos > -1 ? temp_cur.paragraph().isLetter(left_pos) : false);
721 right_is_letter =
722 (right_pos > -1 ? temp_cur.paragraph().isLetter(right_pos) : false);
724 // if we're not at a letter/non-letter boundary, continue moving
725 if (left_is_letter == right_is_letter)
726 continue;
728 // we should stop when we have an LTR word on our right or an RTL word
729 // on our left
730 if ((left_is_letter && temp_cur.paragraph().getFontSettings(
731 temp_cur.buffer()->params(),
732 left_pos).isRightToLeft())
733 || (right_is_letter && !temp_cur.paragraph().getFontSettings(
734 temp_cur.buffer()->params(),
735 right_pos).isRightToLeft()))
736 break;
739 return setCursor(cur, temp_cur.pit(), temp_cur.pos(),
740 true, temp_cur.boundary());
744 void Text::selectWord(Cursor & cur, word_location loc)
746 LASSERT(this == cur.text(), /**/);
747 CursorSlice from = cur.top();
748 CursorSlice to = cur.top();
749 getWord(from, to, loc);
750 if (cur.top() != from)
751 setCursor(cur, from.pit(), from.pos());
752 if (to == from)
753 return;
754 cur.resetAnchor();
755 setCursor(cur, to.pit(), to.pos());
756 cur.setSelection();
760 void Text::selectAll(Cursor & cur)
762 LASSERT(this == cur.text(), /**/);
763 if (cur.lastpos() == 0 && cur.lastpit() == 0)
764 return;
765 // If the cursor is at the beginning, make sure the cursor ends there
766 if (cur.pit() == 0 && cur.pos() == 0) {
767 setCursor(cur, cur.lastpit(), getPar(cur.lastpit()).size());
768 cur.resetAnchor();
769 setCursor(cur, 0, 0);
770 } else {
771 setCursor(cur, 0, 0);
772 cur.resetAnchor();
773 setCursor(cur, cur.lastpit(), getPar(cur.lastpit()).size());
775 cur.setSelection();
779 // Select the word currently under the cursor when no
780 // selection is currently set
781 bool Text::selectWordWhenUnderCursor(Cursor & cur, word_location loc)
783 LASSERT(this == cur.text(), /**/);
784 if (cur.selection())
785 return false;
786 selectWord(cur, loc);
787 return cur.selection();
791 void Text::acceptOrRejectChanges(Cursor & cur, ChangeOp op)
793 LASSERT(this == cur.text(), /**/);
795 if (!cur.selection())
796 return;
798 cur.recordUndoSelection();
800 pit_type begPit = cur.selectionBegin().pit();
801 pit_type endPit = cur.selectionEnd().pit();
803 pos_type begPos = cur.selectionBegin().pos();
804 pos_type endPos = cur.selectionEnd().pos();
806 // keep selection info, because endPos becomes invalid after the first loop
807 bool endsBeforeEndOfPar = (endPos < pars_[endPit].size());
809 // first, accept/reject changes within each individual paragraph (do not consider end-of-par)
811 for (pit_type pit = begPit; pit <= endPit; ++pit) {
812 pos_type parSize = pars_[pit].size();
814 // ignore empty paragraphs; otherwise, an assertion will fail for
815 // acceptChanges(bparams, 0, 0) or rejectChanges(bparams, 0, 0)
816 if (parSize == 0)
817 continue;
819 // do not consider first paragraph if the cursor starts at pos size()
820 if (pit == begPit && begPos == parSize)
821 continue;
823 // do not consider last paragraph if the cursor ends at pos 0
824 if (pit == endPit && endPos == 0)
825 break; // last iteration anyway
827 pos_type left = (pit == begPit ? begPos : 0);
828 pos_type right = (pit == endPit ? endPos : parSize);
830 if (op == ACCEPT) {
831 pars_[pit].acceptChanges(cur.buffer()->params(), left, right);
832 } else {
833 pars_[pit].rejectChanges(cur.buffer()->params(), left, right);
837 // next, accept/reject imaginary end-of-par characters
839 for (pit_type pit = begPit; pit <= endPit; ++pit) {
840 pos_type pos = pars_[pit].size();
842 // skip if the selection ends before the end-of-par
843 if (pit == endPit && endsBeforeEndOfPar)
844 break; // last iteration anyway
846 // skip if this is not the last paragraph of the document
847 // note: the user should be able to accept/reject the par break of the last par!
848 if (pit == endPit && pit + 1 != int(pars_.size()))
849 break; // last iteration anway
851 if (op == ACCEPT) {
852 if (pars_[pit].isInserted(pos)) {
853 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
854 } else if (pars_[pit].isDeleted(pos)) {
855 if (pit + 1 == int(pars_.size())) {
856 // we cannot remove a par break at the end of the last paragraph;
857 // instead, we mark it unchanged
858 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
859 } else {
860 mergeParagraph(cur.buffer()->params(), pars_, pit);
861 --endPit;
862 --pit;
865 } else {
866 if (pars_[pit].isDeleted(pos)) {
867 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
868 } else if (pars_[pit].isInserted(pos)) {
869 if (pit + 1 == int(pars_.size())) {
870 // we mark the par break at the end of the last paragraph unchanged
871 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
872 } else {
873 mergeParagraph(cur.buffer()->params(), pars_, pit);
874 --endPit;
875 --pit;
881 // finally, invoke the DEPM
883 deleteEmptyParagraphMechanism(begPit, endPit, cur.buffer()->params().trackChanges);
887 cur.finishUndo();
888 cur.clearSelection();
889 setCursorIntern(cur, begPit, begPos);
890 cur.updateFlags(Update::Force);
891 cur.buffer()->updateLabels();
895 void Text::acceptChanges(BufferParams const & bparams)
897 lyx::acceptChanges(pars_, bparams);
898 deleteEmptyParagraphMechanism(0, pars_.size() - 1, bparams.trackChanges);
902 void Text::rejectChanges(BufferParams const & bparams)
904 pit_type pars_size = static_cast<pit_type>(pars_.size());
906 // first, reject changes within each individual paragraph
907 // (do not consider end-of-par)
908 for (pit_type pit = 0; pit < pars_size; ++pit) {
909 if (!pars_[pit].empty()) // prevent assertion failure
910 pars_[pit].rejectChanges(bparams, 0, pars_[pit].size());
913 // next, reject imaginary end-of-par characters
914 for (pit_type pit = 0; pit < pars_size; ++pit) {
915 pos_type pos = pars_[pit].size();
917 if (pars_[pit].isDeleted(pos)) {
918 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
919 } else if (pars_[pit].isInserted(pos)) {
920 if (pit == pars_size - 1) {
921 // we mark the par break at the end of the last
922 // paragraph unchanged
923 pars_[pit].setChange(pos, Change(Change::UNCHANGED));
924 } else {
925 mergeParagraph(bparams, pars_, pit);
926 --pit;
927 --pars_size;
932 // finally, invoke the DEPM
933 deleteEmptyParagraphMechanism(0, pars_size - 1, bparams.trackChanges);
937 void Text::deleteWordForward(Cursor & cur)
939 LASSERT(this == cur.text(), /**/);
940 if (cur.lastpos() == 0)
941 cursorForward(cur);
942 else {
943 cur.resetAnchor();
944 cur.setSelection(true);
945 cursorForwardOneWord(cur);
946 cur.setSelection();
947 cutSelection(cur, true, false);
948 cur.checkBufferStructure();
953 void Text::deleteWordBackward(Cursor & cur)
955 LASSERT(this == cur.text(), /**/);
956 if (cur.lastpos() == 0)
957 cursorBackward(cur);
958 else {
959 cur.resetAnchor();
960 cur.setSelection(true);
961 cursorBackwardOneWord(cur);
962 cur.setSelection();
963 cutSelection(cur, true, false);
964 cur.checkBufferStructure();
969 // Kill to end of line.
970 void Text::changeCase(Cursor & cur, TextCase action)
972 LASSERT(this == cur.text(), /**/);
973 CursorSlice from;
974 CursorSlice to;
976 bool gotsel = false;
977 if (cur.selection()) {
978 from = cur.selBegin();
979 to = cur.selEnd();
980 gotsel = true;
981 } else {
982 from = cur.top();
983 getWord(from, to, PARTIAL_WORD);
984 cursorForwardOneWord(cur);
987 cur.recordUndoSelection();
989 pit_type begPit = from.pit();
990 pit_type endPit = to.pit();
992 pos_type begPos = from.pos();
993 pos_type endPos = to.pos();
995 pos_type right = 0; // needed after the for loop
997 for (pit_type pit = begPit; pit <= endPit; ++pit) {
998 Paragraph & par = pars_[pit];
999 pos_type const pos = (pit == begPit ? begPos : 0);
1000 right = (pit == endPit ? endPos : par.size());
1001 par.changeCase(cur.buffer()->params(), pos, right, action);
1004 // the selection may have changed due to logically-only deleted chars
1005 if (gotsel) {
1006 setCursor(cur, begPit, begPos);
1007 cur.resetAnchor();
1008 setCursor(cur, endPit, right);
1009 cur.setSelection();
1010 } else
1011 setCursor(cur, endPit, right);
1013 cur.checkBufferStructure();
1017 bool Text::handleBibitems(Cursor & cur)
1019 if (cur.paragraph().layout().labeltype != LABEL_BIBLIO)
1020 return false;
1022 if (cur.pos() != 0)
1023 return false;
1025 BufferParams const & bufparams = cur.buffer()->params();
1026 Paragraph const & par = cur.paragraph();
1027 Cursor prevcur = cur;
1028 if (cur.pit() > 0) {
1029 --prevcur.pit();
1030 prevcur.pos() = prevcur.lastpos();
1032 Paragraph const & prevpar = prevcur.paragraph();
1034 // if a bibitem is deleted, merge with previous paragraph
1035 // if this is a bibliography item as well
1036 if (cur.pit() > 0 && par.layout() == prevpar.layout()) {
1037 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
1038 mergeParagraph(bufparams, cur.text()->paragraphs(),
1039 prevcur.pit());
1040 cur.buffer()->updateLabels();
1041 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1042 cur.updateFlags(Update::Force);
1043 return true;
1046 // otherwise reset to default
1047 cur.paragraph().setPlainOrDefaultLayout(bufparams.documentClass());
1048 return true;
1052 bool Text::erase(Cursor & cur)
1054 LASSERT(this == cur.text(), return false);
1055 bool needsUpdate = false;
1056 Paragraph & par = cur.paragraph();
1058 if (cur.pos() != cur.lastpos()) {
1059 // this is the code for a normal delete, not pasting
1060 // any paragraphs
1061 cur.recordUndo(DELETE_UNDO);
1062 bool const was_inset = cur.paragraph().isInset(cur.pos());
1063 if(!par.eraseChar(cur.pos(), cur.buffer()->params().trackChanges))
1064 // the character has been logically deleted only => skip it
1065 cur.top().forwardPos();
1067 if (was_inset)
1068 cur.buffer()->updateLabels();
1069 else
1070 cur.checkBufferStructure();
1071 needsUpdate = true;
1072 } else {
1073 if (cur.pit() == cur.lastpit())
1074 return dissolveInset(cur);
1076 if (!par.isMergedOnEndOfParDeletion(cur.buffer()->params().trackChanges)) {
1077 par.setChange(cur.pos(), Change(Change::DELETED));
1078 cur.forwardPos();
1079 needsUpdate = true;
1080 } else {
1081 setCursorIntern(cur, cur.pit() + 1, 0);
1082 needsUpdate = backspacePos0(cur);
1086 needsUpdate |= handleBibitems(cur);
1088 if (needsUpdate) {
1089 // Make sure the cursor is correct. Is this really needed?
1090 // No, not really... at least not here!
1091 cur.text()->setCursor(cur.top(), cur.pit(), cur.pos());
1092 cur.checkBufferStructure();
1095 return needsUpdate;
1099 bool Text::backspacePos0(Cursor & cur)
1101 LASSERT(this == cur.text(), /**/);
1102 if (cur.pit() == 0)
1103 return false;
1105 bool needsUpdate = false;
1107 BufferParams const & bufparams = cur.buffer()->params();
1108 DocumentClass const & tclass = bufparams.documentClass();
1109 ParagraphList & plist = cur.text()->paragraphs();
1110 Paragraph const & par = cur.paragraph();
1111 Cursor prevcur = cur;
1112 --prevcur.pit();
1113 prevcur.pos() = prevcur.lastpos();
1114 Paragraph const & prevpar = prevcur.paragraph();
1116 // is it an empty paragraph?
1117 if (cur.lastpos() == 0
1118 || (cur.lastpos() == 1 && par.isSeparator(0))) {
1119 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1120 plist.erase(boost::next(plist.begin(), cur.pit()));
1121 needsUpdate = true;
1123 // is previous par empty?
1124 else if (prevcur.lastpos() == 0
1125 || (prevcur.lastpos() == 1 && prevpar.isSeparator(0))) {
1126 cur.recordUndo(ATOMIC_UNDO, prevcur.pit(), cur.pit());
1127 plist.erase(boost::next(plist.begin(), prevcur.pit()));
1128 needsUpdate = true;
1130 // Pasting is not allowed, if the paragraphs have different
1131 // layouts. I think it is a real bug of all other
1132 // word processors to allow it. It confuses the user.
1133 // Correction: Pasting is always allowed with standard-layout
1134 // or the empty layout.
1135 else if (par.layout() == prevpar.layout()
1136 || tclass.isDefaultLayout(par.layout())
1137 || tclass.isPlainLayout(par.layout())) {
1138 cur.recordUndo(ATOMIC_UNDO, prevcur.pit());
1139 mergeParagraph(bufparams, plist, prevcur.pit());
1140 needsUpdate = true;
1143 if (needsUpdate) {
1144 cur.buffer()->updateLabels();
1145 setCursorIntern(cur, prevcur.pit(), prevcur.pos());
1148 return needsUpdate;
1152 bool Text::backspace(Cursor & cur)
1154 LASSERT(this == cur.text(), /**/);
1155 bool needsUpdate = false;
1156 if (cur.pos() == 0) {
1157 if (cur.pit() == 0)
1158 return dissolveInset(cur);
1160 Paragraph & prev_par = pars_[cur.pit() - 1];
1162 if (!prev_par.isMergedOnEndOfParDeletion(cur.buffer()->params().trackChanges)) {
1163 prev_par.setChange(prev_par.size(), Change(Change::DELETED));
1164 setCursorIntern(cur, cur.pit() - 1, prev_par.size());
1165 return true;
1167 // The cursor is at the beginning of a paragraph, so
1168 // the backspace will collapse two paragraphs into one.
1169 needsUpdate = backspacePos0(cur);
1171 } else {
1172 // this is the code for a normal backspace, not pasting
1173 // any paragraphs
1174 cur.recordUndo(DELETE_UNDO);
1175 // We used to do cursorBackwardIntern() here, but it is
1176 // not a good idea since it triggers the auto-delete
1177 // mechanism. So we do a cursorBackwardIntern()-lite,
1178 // without the dreaded mechanism. (JMarc)
1179 setCursorIntern(cur, cur.pit(), cur.pos() - 1,
1180 false, cur.boundary());
1181 bool const was_inset = cur.paragraph().isInset(cur.pos());
1182 cur.paragraph().eraseChar(cur.pos(), cur.buffer()->params().trackChanges);
1183 if (was_inset)
1184 cur.buffer()->updateLabels();
1185 else
1186 cur.checkBufferStructure();
1189 if (cur.pos() == cur.lastpos())
1190 cur.setCurrentFont();
1192 needsUpdate |= handleBibitems(cur);
1194 // A singlePar update is not enough in this case.
1195 // cur.updateFlags(Update::Force);
1196 setCursor(cur.top(), cur.pit(), cur.pos());
1198 return needsUpdate;
1202 bool Text::dissolveInset(Cursor & cur)
1204 LASSERT(this == cur.text(), return false);
1206 if (isMainText(cur.bv().buffer()) || cur.inset().nargs() != 1)
1207 return false;
1209 cur.recordUndoInset();
1210 cur.setMark(false);
1211 cur.selHandle(false);
1212 // save position
1213 pos_type spos = cur.pos();
1214 pit_type spit = cur.pit();
1215 ParagraphList plist;
1216 if (cur.lastpit() != 0 || cur.lastpos() != 0)
1217 plist = paragraphs();
1218 cur.popBackward();
1219 // store cursor offset
1220 if (spit == 0)
1221 spos += cur.pos();
1222 spit += cur.pit();
1223 Buffer & b = *cur.buffer();
1224 cur.paragraph().eraseChar(cur.pos(), b.params().trackChanges);
1225 if (!plist.empty()) {
1226 // ERT paragraphs have the Language latex_language.
1227 // This is invalid outside of ERT, so we need to
1228 // change it to the buffer language.
1229 ParagraphList::iterator it = plist.begin();
1230 ParagraphList::iterator it_end = plist.end();
1231 for (; it != it_end; it++)
1232 it->changeLanguage(b.params(), latex_language, b.language());
1234 pasteParagraphList(cur, plist, b.params().documentClassPtr(),
1235 b.errorList("Paste"));
1236 // restore position
1237 cur.pit() = min(cur.lastpit(), spit);
1238 cur.pos() = min(cur.lastpos(), spos);
1240 cur.clearSelection();
1241 cur.resetAnchor();
1242 return true;
1246 void Text::getWord(CursorSlice & from, CursorSlice & to,
1247 word_location const loc) const
1249 Paragraph const & from_par = pars_[from.pit()];
1250 switch (loc) {
1251 case WHOLE_WORD_STRICT:
1252 if (from.pos() == 0 || from.pos() == from_par.size()
1253 || !from_par.isLetter(from.pos())
1254 || !from_par.isLetter(from.pos() - 1)) {
1255 to = from;
1256 return;
1258 // no break here, we go to the next
1260 case WHOLE_WORD:
1261 // If we are already at the beginning of a word, do nothing
1262 if (!from.pos() || !from_par.isLetter(from.pos() - 1))
1263 break;
1264 // no break here, we go to the next
1266 case PREVIOUS_WORD:
1267 // always move the cursor to the beginning of previous word
1268 while (from.pos() && from_par.isLetter(from.pos() - 1))
1269 --from.pos();
1270 break;
1271 case NEXT_WORD:
1272 LYXERR0("Text::getWord: NEXT_WORD not implemented yet");
1273 break;
1274 case PARTIAL_WORD:
1275 // no need to move the 'from' cursor
1276 break;
1278 to = from;
1279 Paragraph const & to_par = pars_[to.pit()];
1280 while (to.pos() < to_par.size() && to_par.isLetter(to.pos()))
1281 ++to.pos();
1285 void Text::write(Buffer const & buf, ostream & os) const
1287 ParagraphList::const_iterator pit = paragraphs().begin();
1288 ParagraphList::const_iterator end = paragraphs().end();
1289 depth_type dth = 0;
1290 for (; pit != end; ++pit)
1291 pit->write(os, buf.params(), dth);
1293 // Close begin_deeper
1294 for(; dth > 0; --dth)
1295 os << "\n\\end_deeper";
1299 bool Text::read(Buffer const & buf, Lexer & lex,
1300 ErrorList & errorList, InsetText * insetPtr)
1302 depth_type depth = 0;
1303 bool res = true;
1305 while (lex.isOK()) {
1306 lex.nextToken();
1307 string const token = lex.getString();
1309 if (token.empty())
1310 continue;
1312 if (token == "\\end_inset")
1313 break;
1315 if (token == "\\end_body")
1316 continue;
1318 if (token == "\\begin_body")
1319 continue;
1321 if (token == "\\end_document") {
1322 res = false;
1323 break;
1326 if (token == "\\begin_layout") {
1327 lex.pushToken(token);
1329 Paragraph par;
1330 par.setInsetOwner(insetPtr);
1331 par.params().depth(depth);
1332 par.setFont(0, Font(inherit_font, buf.params().language));
1333 pars_.push_back(par);
1335 // FIXME: goddamn InsetTabular makes us pass a Buffer
1336 // not BufferParams
1337 lyx::readParagraph(buf, pars_.back(), lex, errorList);
1339 // register the words in the global word list
1340 CursorSlice sl = CursorSlice(*insetPtr);
1341 sl.pit() = pars_.size() - 1;
1342 pars_.back().updateWords(sl);
1343 } else if (token == "\\begin_deeper") {
1344 ++depth;
1345 } else if (token == "\\end_deeper") {
1346 if (!depth)
1347 lex.printError("\\end_deeper: " "depth is already null");
1348 else
1349 --depth;
1350 } else {
1351 LYXERR0("Handling unknown body token: `" << token << '\'');
1355 // avoid a crash on weird documents (bug 4859)
1356 if (pars_.empty()) {
1357 Paragraph par;
1358 par.setInsetOwner(insetPtr);
1359 par.params().depth(depth);
1360 par.setFont(0, Font(inherit_font,
1361 buf.params().language));
1362 par.setPlainOrDefaultLayout(buf.params().documentClass());
1363 pars_.push_back(par);
1366 return res;
1369 // Returns the current font and depth as a message.
1370 docstring Text::currentState(Cursor const & cur) const
1372 LASSERT(this == cur.text(), /**/);
1373 Buffer & buf = *cur.buffer();
1374 Paragraph const & par = cur.paragraph();
1375 odocstringstream os;
1377 if (buf.params().trackChanges)
1378 os << _("[Change Tracking] ");
1380 Change change = par.lookupChange(cur.pos());
1382 if (change.type != Change::UNCHANGED) {
1383 Author const & a = buf.params().authors().get(change.author);
1384 os << _("Change: ") << a.name();
1385 if (!a.email().empty())
1386 os << " (" << a.email() << ")";
1387 // FIXME ctime is english, we should translate that
1388 os << _(" at ") << ctime(&change.changetime);
1389 os << " : ";
1392 // I think we should only show changes from the default
1393 // font. (Asger)
1394 // No, from the document font (MV)
1395 Font font = cur.real_current_font;
1396 font.fontInfo().reduce(buf.params().getFont().fontInfo());
1398 os << bformat(_("Font: %1$s"), font.stateText(&buf.params()));
1400 // The paragraph depth
1401 int depth = cur.paragraph().getDepth();
1402 if (depth > 0)
1403 os << bformat(_(", Depth: %1$d"), depth);
1405 // The paragraph spacing, but only if different from
1406 // buffer spacing.
1407 Spacing const & spacing = par.params().spacing();
1408 if (!spacing.isDefault()) {
1409 os << _(", Spacing: ");
1410 switch (spacing.getSpace()) {
1411 case Spacing::Single:
1412 os << _("Single");
1413 break;
1414 case Spacing::Onehalf:
1415 os << _("OneHalf");
1416 break;
1417 case Spacing::Double:
1418 os << _("Double");
1419 break;
1420 case Spacing::Other:
1421 os << _("Other (") << from_ascii(spacing.getValueAsString()) << ')';
1422 break;
1423 case Spacing::Default:
1424 // should never happen, do nothing
1425 break;
1429 #ifdef DEVEL_VERSION
1430 os << _(", Inset: ") << &cur.inset();
1431 os << _(", Paragraph: ") << cur.pit();
1432 os << _(", Id: ") << par.id();
1433 os << _(", Position: ") << cur.pos();
1434 // FIXME: Why is the check for par.size() needed?
1435 // We are called with cur.pos() == par.size() quite often.
1436 if (!par.empty() && cur.pos() < par.size()) {
1437 // Force output of code point, not character
1438 size_t const c = par.getChar(cur.pos());
1439 os << _(", Char: 0x") << hex << c;
1441 os << _(", Boundary: ") << cur.boundary();
1442 // Row & row = cur.textRow();
1443 // os << bformat(_(", Row b:%1$d e:%2$d"), row.pos(), row.endpos());
1444 #endif
1445 return os.str();
1449 docstring Text::getPossibleLabel(Cursor const & cur) const
1451 pit_type pit = cur.pit();
1453 Layout const * layout = &(pars_[pit].layout());
1455 docstring text;
1456 docstring par_text = pars_[pit].asString();
1457 string piece;
1458 // the return string of math matrices might contain linebreaks
1459 par_text = subst(par_text, '\n', '-');
1460 for (int i = 0; i < lyxrc.label_init_length; ++i) {
1461 if (par_text.empty())
1462 break;
1463 docstring head;
1464 par_text = split(par_text, head, ' ');
1465 // Is it legal to use spaces in labels ?
1466 if (i > 0)
1467 text += '-';
1468 text += head;
1471 // No need for a prefix if the user said so.
1472 if (lyxrc.label_init_length <= 0)
1473 return text;
1475 // Will contain the label type.
1476 docstring name;
1478 // For section, subsection, etc...
1479 if (layout->latextype == LATEX_PARAGRAPH && pit != 0) {
1480 Layout const * layout2 = &(pars_[pit - 1].layout());
1481 if (layout2->latextype != LATEX_PARAGRAPH) {
1482 --pit;
1483 layout = layout2;
1486 if (layout->latextype != LATEX_PARAGRAPH)
1487 name = from_ascii(layout->latexname());
1489 // for captions, we just take the caption type
1490 Inset * caption_inset = cur.innerInsetOfType(CAPTION_CODE);
1491 if (caption_inset)
1492 name = from_ascii(static_cast<InsetCaption *>(caption_inset)->type());
1494 // If none of the above worked, we'll see if we're inside various
1495 // types of insets and take our abbreviation from them.
1496 if (name.empty()) {
1497 InsetCode const codes[] = {
1498 FLOAT_CODE,
1499 WRAP_CODE,
1500 FOOT_CODE
1502 for (unsigned int i = 0; i < (sizeof codes / sizeof codes[0]); ++i) {
1503 Inset * float_inset = cur.innerInsetOfType(codes[i]);
1504 if (float_inset) {
1505 name = float_inset->name();
1506 break;
1511 // Create a correct prefix for prettyref
1512 if (name == "theorem")
1513 name = from_ascii("thm");
1514 else if (name == "Foot")
1515 name = from_ascii("fn");
1516 else if (name == "listing")
1517 name = from_ascii("lst");
1519 if (!name.empty())
1520 text = name.substr(0, 3) + ':' + text;
1522 return text;
1526 docstring Text::asString(int options) const
1528 return asString(0, pars_.size(), options);
1532 docstring Text::asString(pit_type beg, pit_type end, int options) const
1534 size_t i = size_t(beg);
1535 docstring str = pars_[i].asString(options);
1536 for (++i; i != size_t(end); ++i) {
1537 str += '\n';
1538 str += pars_[i].asString(options);
1540 return str;
1545 void Text::charsTranspose(Cursor & cur)
1547 LASSERT(this == cur.text(), /**/);
1549 pos_type pos = cur.pos();
1551 // If cursor is at beginning or end of paragraph, do nothing.
1552 if (pos == cur.lastpos() || pos == 0)
1553 return;
1555 Paragraph & par = cur.paragraph();
1557 // Get the positions of the characters to be transposed.
1558 pos_type pos1 = pos - 1;
1559 pos_type pos2 = pos;
1561 // In change tracking mode, ignore deleted characters.
1562 while (pos2 < cur.lastpos() && par.isDeleted(pos2))
1563 ++pos2;
1564 if (pos2 == cur.lastpos())
1565 return;
1567 while (pos1 >= 0 && par.isDeleted(pos1))
1568 --pos1;
1569 if (pos1 < 0)
1570 return;
1572 // Don't do anything if one of the "characters" is not regular text.
1573 if (par.isInset(pos1) || par.isInset(pos2))
1574 return;
1576 // Store the characters to be transposed (including font information).
1577 char_type const char1 = par.getChar(pos1);
1578 Font const font1 =
1579 par.getFontSettings(cur.buffer()->params(), pos1);
1581 char_type const char2 = par.getChar(pos2);
1582 Font const font2 =
1583 par.getFontSettings(cur.buffer()->params(), pos2);
1585 // And finally, we are ready to perform the transposition.
1586 // Track the changes if Change Tracking is enabled.
1587 bool const trackChanges = cur.buffer()->params().trackChanges;
1589 cur.recordUndo();
1591 par.eraseChar(pos2, trackChanges);
1592 par.eraseChar(pos1, trackChanges);
1593 par.insertChar(pos1, char2, font2, trackChanges);
1594 par.insertChar(pos2, char1, font1, trackChanges);
1596 cur.checkBufferStructure();
1598 // After the transposition, move cursor to after the transposition.
1599 setCursor(cur, cur.pit(), pos2);
1600 cur.forwardPos();
1604 DocIterator Text::macrocontextPosition() const
1606 return macrocontext_position_;
1610 void Text::setMacrocontextPosition(DocIterator const & pos)
1612 macrocontext_position_ = pos;
1616 docstring Text::previousWord(CursorSlice const & sl) const
1618 CursorSlice from = sl;
1619 CursorSlice to = sl;
1620 getWord(from, to, PREVIOUS_WORD);
1621 if (sl == from || to == from)
1622 return docstring();
1624 Paragraph const & par = sl.paragraph();
1625 return par.asString(from.pos(), to.pos());
1629 bool Text::completionSupported(Cursor const & cur) const
1631 Paragraph const & par = cur.paragraph();
1632 return cur.pos() > 0
1633 && (cur.pos() >= par.size() || !par.isLetter(cur.pos()))
1634 && par.isLetter(cur.pos() - 1);
1638 CompletionList const * Text::createCompletionList(Cursor const & cur) const
1640 return new TextCompletionList(cur);
1644 bool Text::insertCompletion(Cursor & cur, docstring const & s, bool /*finished*/)
1646 LASSERT(cur.bv().cursor() == cur, /**/);
1647 cur.insert(s);
1648 cur.bv().cursor() = cur;
1649 if (!(cur.disp_.update() & Update::Force))
1650 cur.updateFlags(cur.disp_.update() | Update::SinglePar);
1651 return true;
1655 docstring Text::completionPrefix(Cursor const & cur) const
1657 return previousWord(cur.top());
1660 } // namespace lyx